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 unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = DDIMPipeline SCREAMING_SNAKE_CASE__ = UNCONDITIONAL_IMAGE_GENERATION_PARAMS SCREAMING_SNAKE_CASE__ = PipelineTesterMixin.required_optional_params - { """num_images_per_prompt""", """latents""", """callback""", """callback_steps""", } SCREAMING_SNAKE_CASE__ = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): torch.manual_seed(0 ) UpperCamelCase__ = 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""") , ) UpperCamelCase__ = DDIMScheduler() UpperCamelCase__ = {"""unet""": unet, """scheduler""": scheduler} return components def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): if str(SCREAMING_SNAKE_CASE_ ).startswith("""mps""" ): UpperCamelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = { """batch_size""": 1, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCAmelCase_ (self ): UpperCamelCase__ = """cpu""" UpperCamelCase__ = self.get_dummy_components() UpperCamelCase__ = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = pipe(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase__ = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) UpperCamelCase__ = np.array( [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04] ) UpperCamelCase__ = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1E-3 ) def UpperCAmelCase_ (self ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def UpperCAmelCase_ (self ): super().test_save_load_local(expected_max_difference=3E-3 ) def UpperCAmelCase_ (self ): super().test_save_load_optional_components(expected_max_difference=3E-3 ) def UpperCAmelCase_ (self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = """google/ddpm-cifar10-32""" UpperCamelCase__ = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = DDIMScheduler() UpperCamelCase__ = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddim.to(SCREAMING_SNAKE_CASE_ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.manual_seed(0 ) UpperCamelCase__ = ddim(generator=SCREAMING_SNAKE_CASE_ , eta=0.0 , output_type="""numpy""" ).images UpperCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase__ = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase_ (self ): UpperCamelCase__ = """google/ddpm-ema-bedroom-256""" UpperCamelCase__ = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddpm.to(SCREAMING_SNAKE_CASE_ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.manual_seed(0 ) UpperCamelCase__ = ddpm(generator=SCREAMING_SNAKE_CASE_ , output_type="""numpy""" ).images UpperCamelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) UpperCamelCase__ = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
86
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
1
from PIL import Image def __magic_name__ ( __a : Image , __a : int ): '''simple docstring''' UpperCamelCase__ = (259 * (level + 255)) / (255 * (259 - level)) def contrast(__a : int ) -> int: return int(128 + factor * (c - 128) ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change contrast to 170 lowerCamelCase_ = change_contrast(img, 1_70) cont_img.save('''image_data/lena_high_contrast.png''', format='''png''')
86
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class __A( unittest.TestCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=18 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=4_00 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=True , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = num_channels UpperCamelCase__ = image_size UpperCamelCase__ = min_resolution UpperCamelCase__ = max_resolution UpperCamelCase__ = do_resize UpperCamelCase__ = size_divisor UpperCamelCase__ = do_rescale def UpperCAmelCase_ (self ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = GLPNImageProcessor if is_vision_available() else None def UpperCAmelCase_ (self ): UpperCamelCase__ = GLPNImageProcessingTester(self ) @property def UpperCAmelCase_ (self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size_divisor""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """resample""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_rescale""" ) ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCAmelCase_ (self ): # Initialize image_processing UpperCamelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) UpperCamelCase__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
86
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
1
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCamelCase_ = { '''configuration_swiftformer''': [ '''SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwiftFormerConfig''', '''SwiftFormerOnnxConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwiftFormerForImageClassification''', '''SwiftFormerModel''', '''SwiftFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
1
lowerCamelCase_ = ''' # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git ''' lowerCamelCase_ = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] lowerCamelCase_ = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
86
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
1
import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_size UpperCamelCase__ = num_channels UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = scope UpperCamelCase__ = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) UpperCamelCase__ = (image_size // patch_size) ** 2 UpperCamelCase__ = num_patches + 1 def UpperCAmelCase_ (self ): UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ (self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = ViTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = ViTForMaskedImageModeling(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCamelCase__ = 1 UpperCamelCase__ = ViTForMaskedImageModeling(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.type_sequence_label_size UpperCamelCase__ = ViTForImageClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCamelCase__ = 1 UpperCamelCase__ = ViTForImageClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = ViTModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = ViTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ (self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase__ = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. UpperCamelCase__ = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=4_80 ) UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) UpperCamelCase__ = inputs.pixel_values.to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , interpolate_pos_encoding=SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase__ = torch.Size((1, 36_01, 3_84) ) self.assertEqual(outputs.last_hidden_state.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def UpperCAmelCase_ (self ): UpperCamelCase__ = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) UpperCamelCase__ = inputs.pixel_values.to(SCREAMING_SNAKE_CASE_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )
86
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
1
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = DistilBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = DistilBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = DistilBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = DistilBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = DistilBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_choices UpperCamelCase__ = DistilBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ((UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__) , (UpperCamelCase__)) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": DistilBertModel, """fill-mask""": DistilBertForMaskedLM, """question-answering""": DistilBertForQuestionAnswering, """text-classification""": DistilBertForSequenceClassification, """token-classification""": DistilBertForTokenClassification, """zero-shot""": DistilBertForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True def UpperCAmelCase_ (self ): UpperCamelCase__ = DistilBertModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DistilBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @slow @require_torch_gpu def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return UpperCamelCase__ = True UpperCamelCase__ = model_class(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.jit.trace( SCREAMING_SNAKE_CASE_ , (inputs_dict["""input_ids"""].to("""cpu""" ), inputs_dict["""attention_mask"""].to("""cpu""" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(SCREAMING_SNAKE_CASE_ , os.path.join(SCREAMING_SNAKE_CASE_ , """traced_model.pt""" ) ) UpperCamelCase__ = torch.jit.load(os.path.join(SCREAMING_SNAKE_CASE_ , """traced_model.pt""" ) , map_location=SCREAMING_SNAKE_CASE_ ) loaded(inputs_dict["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) , inputs_dict["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = DistilBertModel.from_pretrained("""distilbert-base-uncased""" ) UpperCamelCase__ = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
86
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
1
from typing import Dict, 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, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCamelCase_ = logging.get_logger(__name__) class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""pixel_values"""] def __init__(self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 2_55 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = size if size is not None else {"""height""": 2_24, """width""": 2_24} UpperCamelCase__ = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24} UpperCamelCase__ = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ , param_name="""crop_size""" ) UpperCamelCase__ = do_resize UpperCamelCase__ = do_rescale UpperCamelCase__ = do_normalize UpperCamelCase__ = do_center_crop UpperCamelCase__ = crop_size UpperCamelCase__ = size UpperCamelCase__ = resample UpperCamelCase__ = rescale_factor UpperCamelCase__ = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN UpperCamelCase__ = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "shortest_edge" in size: UpperCamelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=size["""shortest_edge"""] , default_to_square=SCREAMING_SNAKE_CASE_ ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: UpperCamelCase__ = (size["""height"""], size["""width"""]) else: raise ValueError(F"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}" ) return resize(SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(F"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(SCREAMING_SNAKE_CASE_ , size=(size["""height"""], size["""width"""]) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ ): return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = do_resize if do_resize is not None else self.do_resize UpperCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase__ = crop_size if crop_size is not None else self.crop_size UpperCamelCase__ = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name="""crop_size""" , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = resample if resample is not None else self.resample UpperCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase__ = image_mean if image_mean is not None else self.image_mean UpperCamelCase__ = image_std if image_std is not None else self.image_std UpperCamelCase__ = size if size is not None else self.size UpperCamelCase__ = get_size_dict(SCREAMING_SNAKE_CASE_ ) if not is_batched(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [images] if not valid_images(SCREAMING_SNAKE_CASE_ ): 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.""" ) # All transformations expect numpy arrays. UpperCamelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: UpperCamelCase__ = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase__ = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
86
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
1
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): lowerCamelCase_ = { '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: lowerCamelCase_ = { '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = (images / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase__ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCamelCase__ = numpy_to_pil(__a ) return images def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' if images.ndim == 3: UpperCamelCase__ = images[None, ...] UpperCamelCase__ = (images * 255).round().astype("""uint8""" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images UpperCamelCase__ = [Image.fromarray(image.squeeze() , mode="""L""" ) for image in images] else: UpperCamelCase__ = [Image.fromarray(__a ) for image in images] return pil_images
86
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
1
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = torch.nn.Linear(10 , 10 ) UpperCamelCase__ = torch.optim.SGD(model.parameters() , 0.1 ) UpperCamelCase__ = Accelerator() UpperCamelCase__ = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) try: pickle.loads(pickle.dumps(SCREAMING_SNAKE_CASE_ ) ) except Exception as e: self.fail(F"Accelerated optimizer pickling failed with {e}" ) AcceleratorState._reset_state()
86
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
1
import argparse import torch from transformers import ( SpeechTaConfig, SpeechTaFeatureExtractor, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaProcessor, SpeechTaTokenizer, logging, ) from transformers.tokenization_utils import AddedToken logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger('''transformers.models.speecht5''') lowerCamelCase_ = { '''speech_encoder_prenet.layer_norm''': '''speecht5.encoder.prenet.feature_projection.layer_norm''', '''speech_encoder_prenet.post_extract_proj''': '''speecht5.encoder.prenet.feature_projection.projection''', '''speech_encoder_prenet.pos_conv.0''': '''speecht5.encoder.prenet.pos_conv_embed.conv''', '''speech_encoder_prenet.mask_emb''': '''speecht5.encoder.prenet.masked_spec_embed''', } lowerCamelCase_ = { '''text_encoder_prenet.encoder_prenet.0''': '''speecht5.encoder.prenet.embed_tokens''', '''text_encoder_prenet.encoder_prenet.1.alpha''': '''speecht5.encoder.prenet.encode_positions.alpha''', } lowerCamelCase_ = { '''speech_decoder_prenet.decoder_prenet.0.0.prenet.0.0''': '''speecht5.decoder.prenet.layers.0''', '''speech_decoder_prenet.decoder_prenet.0.0.prenet.1.0''': '''speecht5.decoder.prenet.layers.1''', '''speech_decoder_prenet.decoder_prenet.0.1''': '''speecht5.decoder.prenet.final_layer''', '''speech_decoder_prenet.decoder_prenet.1.alpha''': '''speecht5.decoder.prenet.encode_positions.alpha''', '''speech_decoder_prenet.spkembs_layer.0''': '''speecht5.decoder.prenet.speaker_embeds_layer''', } lowerCamelCase_ = { '''speech_decoder_postnet.feat_out''': '''speech_decoder_postnet.feat_out''', '''speech_decoder_postnet.prob_out''': '''speech_decoder_postnet.prob_out''', '''speech_decoder_postnet.postnet.postnet.0.0''': '''speech_decoder_postnet.layers.0.conv''', '''speech_decoder_postnet.postnet.postnet.0.1''': '''speech_decoder_postnet.layers.0.batch_norm''', '''speech_decoder_postnet.postnet.postnet.1.0''': '''speech_decoder_postnet.layers.1.conv''', '''speech_decoder_postnet.postnet.postnet.1.1''': '''speech_decoder_postnet.layers.1.batch_norm''', '''speech_decoder_postnet.postnet.postnet.2.0''': '''speech_decoder_postnet.layers.2.conv''', '''speech_decoder_postnet.postnet.postnet.2.1''': '''speech_decoder_postnet.layers.2.batch_norm''', '''speech_decoder_postnet.postnet.postnet.3.0''': '''speech_decoder_postnet.layers.3.conv''', '''speech_decoder_postnet.postnet.postnet.3.1''': '''speech_decoder_postnet.layers.3.batch_norm''', '''speech_decoder_postnet.postnet.postnet.4.0''': '''speech_decoder_postnet.layers.4.conv''', '''speech_decoder_postnet.postnet.postnet.4.1''': '''speech_decoder_postnet.layers.4.batch_norm''', } lowerCamelCase_ = { '''text_decoder_prenet.embed_tokens''': '''speecht5.decoder.prenet.embed_tokens''', } lowerCamelCase_ = { '''text_decoder_postnet.output_projection''': '''text_decoder_postnet.lm_head''', } lowerCamelCase_ = { '''encoder.layers.*.self_attn.k_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.k_proj''', '''encoder.layers.*.self_attn.v_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.v_proj''', '''encoder.layers.*.self_attn.q_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.q_proj''', '''encoder.layers.*.self_attn.out_proj''': '''speecht5.encoder.wrapped_encoder.layers.*.attention.out_proj''', '''encoder.layers.*.self_attn_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.layer_norm''', '''encoder.layers.*.fc1''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.intermediate_dense''', '''encoder.layers.*.fc2''': '''speecht5.encoder.wrapped_encoder.layers.*.feed_forward.output_dense''', '''encoder.layers.*.final_layer_norm''': '''speecht5.encoder.wrapped_encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''speecht5.encoder.wrapped_encoder.layer_norm''', '''encoder.pos_emb.pe_k''': '''speecht5.encoder.wrapped_encoder.embed_positions.pe_k''', } lowerCamelCase_ = { '''decoder.layers.*.self_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.k_proj''', '''decoder.layers.*.self_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.v_proj''', '''decoder.layers.*.self_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.q_proj''', '''decoder.layers.*.self_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn.out_proj''', '''decoder.layers.*.self_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.self_attn_layer_norm''', '''decoder.layers.*.encoder_attn.k_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.k_proj''', '''decoder.layers.*.encoder_attn.v_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.v_proj''', '''decoder.layers.*.encoder_attn.q_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.q_proj''', '''decoder.layers.*.encoder_attn.out_proj''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn.out_proj''', '''decoder.layers.*.encoder_attn_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.encoder_attn_layer_norm''', '''decoder.layers.*.fc1''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.intermediate_dense''', '''decoder.layers.*.fc2''': '''speecht5.decoder.wrapped_decoder.layers.*.feed_forward.output_dense''', '''decoder.layers.*.final_layer_norm''': '''speecht5.decoder.wrapped_decoder.layers.*.final_layer_norm''', } lowerCamelCase_ = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_TEXT_DECODER_PRENET, **MAPPING_TEXT_DECODER_POSTNET, } lowerCamelCase_ = { **MAPPING_TEXT_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } lowerCamelCase_ = { **MAPPING_SPEECH_ENCODER_PRENET, **MAPPING_ENCODER, **MAPPING_DECODER, **MAPPING_SPEECH_DECODER_PRENET, **MAPPING_SPEECH_DECODER_POSTNET, } lowerCamelCase_ = [] lowerCamelCase_ = [ '''encoder.version''', '''encoder.layers.*.norm_k.weight''', '''encoder.layers.*.norm_k.bias''', '''decoder.version''', '''decoder.layers.*.norm_k.weight''', '''decoder.layers.*.norm_k.bias''', '''decoder.pos_emb.pe_k''', '''speech_encoder_prenet.embed_positions._float_tensor''', '''text_decoder_prenet.embed_positions._float_tensor''', ] lowerCamelCase_ = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''speech_decoder_prenet.*''', '''speech_decoder_postnet.*''', ] lowerCamelCase_ = IGNORE_KEYS + [ '''encoder.proj''', '''speech_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] lowerCamelCase_ = IGNORE_KEYS + [ '''encoder.proj''', '''text_encoder_prenet.*''', '''text_decoder_prenet.*''', '''text_decoder_postnet.*''', ] def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : List[str] , __a : List[str] , __a : str ): '''simple docstring''' for attribute in key.split(""".""" ): UpperCamelCase__ = getattr(__a , __a ) if weight_type is not None: UpperCamelCase__ = getattr(__a , __a ).shape else: UpperCamelCase__ = 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": UpperCamelCase__ = value elif weight_type == "weight_g": UpperCamelCase__ = value elif weight_type == "weight_v": UpperCamelCase__ = value elif weight_type == "bias": UpperCamelCase__ = value elif weight_type == "running_mean": UpperCamelCase__ = value elif weight_type == "running_var": UpperCamelCase__ = value elif weight_type == "num_batches_tracked": UpperCamelCase__ = value else: UpperCamelCase__ = value logger.info(f"{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}." ) def __magic_name__ ( __a : int , __a : Any ): '''simple docstring''' for key in ignore_keys: if key.endswith(""".*""" ): if name.startswith(key[:-1] ): return True elif ".*." in key: UpperCamelCase__ , UpperCamelCase__ = key.split(""".*.""" ) if prefix in name and suffix in name: return True elif key in name: return True return False def __magic_name__ ( __a : Union[str, Any] , __a : Dict , __a : Dict ): '''simple docstring''' UpperCamelCase__ = [] if task == "s2t": UpperCamelCase__ = hf_model.speechta.encoder.prenet.feature_encoder UpperCamelCase__ = MAPPING_S2T UpperCamelCase__ = IGNORE_KEYS_S2T elif task == "t2s": UpperCamelCase__ = None UpperCamelCase__ = MAPPING_T2S UpperCamelCase__ = IGNORE_KEYS_T2S elif task == "s2s": UpperCamelCase__ = hf_model.speechta.encoder.prenet.feature_encoder UpperCamelCase__ = MAPPING_S2S UpperCamelCase__ = IGNORE_KEYS_S2S else: raise ValueError(f"Unsupported task: {task}" ) for name, value in fairseq_dict.items(): if should_ignore(__a , __a ): logger.info(f"{name} was ignored" ) continue UpperCamelCase__ = False if "conv_layers" in name: load_conv_layer( __a , __a , __a , __a , hf_model.config.feat_extract_norm == """group""" , ) UpperCamelCase__ = True else: for key, mapped_key in MAPPING.items(): # mapped_key = "speecht5." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if "*" in key: UpperCamelCase__ , UpperCamelCase__ = key.split(""".*.""" ) if prefix in name and suffix in name: UpperCamelCase__ = suffix # if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]: if key in name: UpperCamelCase__ = True if "*" in mapped_key: UpperCamelCase__ = name.split(__a )[0].split(""".""" )[-2] UpperCamelCase__ = mapped_key.replace("""*""" , __a ) if "weight_g" in name: UpperCamelCase__ = """weight_g""" elif "weight_v" in name: UpperCamelCase__ = """weight_v""" elif "bias" in name: UpperCamelCase__ = """bias""" elif "weight" in name: UpperCamelCase__ = """weight""" elif "running_mean" in name: UpperCamelCase__ = """running_mean""" elif "running_var" in name: UpperCamelCase__ = """running_var""" elif "num_batches_tracked" in name: UpperCamelCase__ = """num_batches_tracked""" else: UpperCamelCase__ = None set_recursively(__a , __a , __a , __a , __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(f"Unused weights: {unused_weights}" ) def __magic_name__ ( __a : int , __a : Union[str, Any] , __a : int , __a : Tuple , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = full_name.split("""conv_layers.""" )[-1] UpperCamelCase__ = name.split(""".""" ) UpperCamelCase__ = int(items[0] ) UpperCamelCase__ = 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." ) UpperCamelCase__ = 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." ) UpperCamelCase__ = 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.conv_layers[layer_id].layer_norm.bias.data.shape} was found." ) UpperCamelCase__ = 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.conv_layers[layer_id].layer_norm.weight.data.shape} was found." ) UpperCamelCase__ = value logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(__a ) @torch.no_grad() def __magic_name__ ( __a : Optional[int] , __a : List[str] , __a : List[str] , __a : Any=None , __a : str=None , __a : Union[str, Any]=None , ): '''simple docstring''' if config_path is not None: UpperCamelCase__ = SpeechTaConfig.from_pretrained(__a ) else: UpperCamelCase__ = SpeechTaConfig() if task == "s2t": UpperCamelCase__ = config.max_text_positions UpperCamelCase__ = SpeechTaForSpeechToText(__a ) elif task == "t2s": UpperCamelCase__ = 1_876 UpperCamelCase__ = 600 UpperCamelCase__ = config.max_speech_positions UpperCamelCase__ = SpeechTaForTextToSpeech(__a ) elif task == "s2s": UpperCamelCase__ = 1_876 UpperCamelCase__ = config.max_speech_positions UpperCamelCase__ = SpeechTaForSpeechToSpeech(__a ) else: raise ValueError(f"Unknown task name: {task}" ) if vocab_path: UpperCamelCase__ = SpeechTaTokenizer(__a , model_max_length=config.max_text_positions ) # Mask token behaves like a normal word, i.e. include the space before it UpperCamelCase__ = AddedToken("""<mask>""" , lstrip=__a , rstrip=__a ) UpperCamelCase__ = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) UpperCamelCase__ = SpeechTaFeatureExtractor() UpperCamelCase__ = SpeechTaProcessor(tokenizer=__a , feature_extractor=__a ) processor.save_pretrained(__a ) UpperCamelCase__ = torch.load(__a ) recursively_load_weights(fairseq_checkpoint["""model"""] , __a , __a ) model.save_pretrained(__a ) if repo_id: print("""Pushing to the hub...""" ) processor.push_to_hub(__a ) model.push_to_hub(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument( '''--task''', default='''s2t''', type=str, help='''Type of the SpeechT5 model you\'d like to convert. Should be one of \'s2t\', \'t2s\', \'s2s\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--vocab_path''', default=None, type=str, help='''Path to SentencePiece model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) lowerCamelCase_ = parser.parse_args() convert_speechta_checkpoint( args.task, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.vocab_path, args.push_to_hub, )
86
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
1
import inspect import unittest import warnings from math import ceil, floor from transformers import LevitConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_MAPPING, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, ) from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """num_attention_heads""" ) ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=[1_28, 2_56, 3_84] , SCREAMING_SNAKE_CASE_=[4, 6, 8] , SCREAMING_SNAKE_CASE_=[2, 3, 4] , SCREAMING_SNAKE_CASE_=[16, 16, 16] , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=[2, 2, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2] , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = num_channels UpperCamelCase__ = kernel_size UpperCamelCase__ = stride UpperCamelCase__ = padding UpperCamelCase__ = hidden_sizes UpperCamelCase__ = num_attention_heads UpperCamelCase__ = depths UpperCamelCase__ = key_dim UpperCamelCase__ = drop_path_rate UpperCamelCase__ = patch_size UpperCamelCase__ = attention_ratio UpperCamelCase__ = mlp_ratio UpperCamelCase__ = initializer_range UpperCamelCase__ = [ ["""Subsample""", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ["""Subsample""", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = num_labels UpperCamelCase__ = initializer_range def UpperCAmelCase_ (self ): UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase__ = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ (self ): return LevitConfig( image_size=self.image_size , num_channels=self.num_channels , kernel_size=self.kernel_size , stride=self.stride , padding=self.padding , patch_size=self.patch_size , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , depths=self.depths , key_dim=self.key_dim , drop_path_rate=self.drop_path_rate , mlp_ratio=self.mlp_ratio , attention_ratio=self.attention_ratio , initializer_range=self.initializer_range , down_ops=self.down_ops , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = LevitModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = (self.image_size, self.image_size) UpperCamelCase__ , UpperCamelCase__ = image_size[0], image_size[1] for _ in range(4 ): UpperCamelCase__ = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) UpperCamelCase__ = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1 ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, ceil(height / 4 ) * ceil(width / 4 ), self.hidden_sizes[-1]) , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = LevitForImageClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": LevitModel, """image-classification""": (LevitForImageClassification, LevitForImageClassificationWithTeacher), } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = LevitModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): 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 ): return @unittest.skip(reason="""Levit does not use inputs_embeds""" ) def UpperCAmelCase_ (self ): pass @unittest.skip(reason="""Levit does not support input and output embeddings""" ) def UpperCAmelCase_ (self ): pass @unittest.skip(reason="""Levit does not output attentions""" ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): def check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = outputs.hidden_states UpperCamelCase__ = len(self.model_tester.depths ) + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = (self.model_tester.image_size, self.model_tester.image_size) UpperCamelCase__ , UpperCamelCase__ = image_size[0], image_size[1] for _ in range(4 ): UpperCamelCase__ = floor( ( (height + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) UpperCamelCase__ = floor( ( (width + 2 * self.model_tester.padding - self.model_tester.kernel_size) / self.model_tester.stride ) + 1 ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [ height * width, self.model_tester.hidden_sizes[0], ] , ) UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = super()._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if return_labels: if model_class.__name__ == "LevitForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): if not self.model_tester.is_training: return UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = True for model_class in self.all_model_classes: # LevitForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(SCREAMING_SNAKE_CASE_ ) or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase__ = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return UpperCamelCase__ = False UpperCamelCase__ = True for model_class in self.all_model_classes: if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue # LevitForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "LevitForImageClassificationWithTeacher": continue UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase__ = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = [ {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float}, {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long}, {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(SCREAMING_SNAKE_CASE_ ), ] or model_class.__name__ == "LevitForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F"Testing {model_class} with {problem_type['title']}" ): UpperCamelCase__ = problem_type["""title"""] UpperCamelCase__ = problem_type["""num_labels"""] UpperCamelCase__ = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase__ = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) if problem_type["num_labels"] > 1: UpperCamelCase__ = inputs["""labels"""].unsqueeze(1 ).repeat(1 , problem_type["""num_labels"""] ) UpperCamelCase__ = inputs["""labels"""].to(problem_type["""dtype"""] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=SCREAMING_SNAKE_CASE_ ) as warning_list: UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F"Something is going wrong in the regression problem: intercepted {w.message}" ) loss.backward() @slow def UpperCAmelCase_ (self ): for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = LevitModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ (self ): return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase__ = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor([1.0448, -0.3745, -1.8317] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
86
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
1
import warnings from ..trainer import Trainer from ..utils import logging lowerCamelCase_ = logging.get_logger(__name__) class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): warnings.warn( """`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """ """instead.""" , SCREAMING_SNAKE_CASE_ , ) super().__init__(args=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
86
import os from datetime import datetime as dt from github import Github lowerCamelCase_ = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''enhancement''', '''new pipeline/model''', '''new scheduler''', '''wip''', ] def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Github(os.environ["""GITHUB_TOKEN"""] ) UpperCamelCase__ = g.get_repo("""huggingface/diffusers""" ) UpperCamelCase__ = repo.get_issues(state="""open""" ) for issue in open_issues: UpperCamelCase__ = sorted(issue.get_comments() , key=lambda __a : i.created_at , reverse=__a ) UpperCamelCase__ = comments[0] if len(__a ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
86
1
from collections import deque def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = deque() UpperCamelCase__ = [False for _ in range(__a )] UpperCamelCase__ = [-1 for _ in range(__a )] UpperCamelCase__ = index_of[:] def strong_connect(__a : int , __a : Optional[int] , __a : int ): UpperCamelCase__ = index # the number when this node is seen UpperCamelCase__ = index # lowest rank node reachable from here index += 1 stack.append(__a ) UpperCamelCase__ = True for w in g[v]: if index_of[w] == -1: UpperCamelCase__ = strong_connect(__a , __a , __a ) UpperCamelCase__ = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: UpperCamelCase__ = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: UpperCamelCase__ = [] UpperCamelCase__ = stack.pop() UpperCamelCase__ = False component.append(__a ) while w != v: UpperCamelCase__ = stack.pop() UpperCamelCase__ = False component.append(__a ) components.append(__a ) return index UpperCamelCase__ = [] for v in range(__a ): if index_of[v] == -1: strong_connect(__a , 0 , __a ) return components def __magic_name__ ( __a : Optional[Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = [[] for _ in range(__a )] for u, v in edges: g[u].append(__a ) return g if __name__ == "__main__": # Test lowerCamelCase_ = 7 lowerCamelCase_ = [0, 0, 1, 2, 3, 3, 4, 4, 6] lowerCamelCase_ = [1, 3, 2, 0, 1, 4, 5, 6, 5] lowerCamelCase_ = [(u, v) for u, v in zip(source, target)] lowerCamelCase_ = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
86
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ , UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
86
1
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib lowerCamelCase_ = get_logger() lowerCamelCase_ = None class __A( TensorFormatter[Mapping, """jax.Array""", Mapping] ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ): super().__init__(features=SCREAMING_SNAKE_CASE_ ) import jax from jaxlib.xla_client import Device if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError( F"Expected {device} to be a `str` not {type(SCREAMING_SNAKE_CASE_ )}, as `jaxlib.xla_extension.Device` " """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """ """the device with `str()` to get its string identifier that will be internally mapped """ """to the actual `jaxlib.xla_extension.Device`.""" ) UpperCamelCase__ = device if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: UpperCamelCase__ = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F"Device with string identifier {self.device} not listed among the available " F"devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default " F"device: {str(jax.devices()[0] )}." ) UpperCamelCase__ = str(jax.devices()[0] ) UpperCamelCase__ = jnp_array_kwargs @staticmethod def UpperCAmelCase_ (): import jax return {str(SCREAMING_SNAKE_CASE_ ): device for device in jax.devices()} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): import jax import jax.numpy as jnp if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and column: if all( isinstance(SCREAMING_SNAKE_CASE_ , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(SCREAMING_SNAKE_CASE_ , axis=0 ) return column def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): import jax import jax.numpy as jnp if isinstance(SCREAMING_SNAKE_CASE_ , (str, bytes, type(SCREAMING_SNAKE_CASE_ )) ): return value elif isinstance(SCREAMING_SNAKE_CASE_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() UpperCamelCase__ = {} if isinstance(SCREAMING_SNAKE_CASE_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: UpperCamelCase__ = {"""dtype""": jnp.intaa} else: UpperCamelCase__ = {"""dtype""": jnp.intaa} elif isinstance(SCREAMING_SNAKE_CASE_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): UpperCamelCase__ = {"""dtype""": jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = np.asarray(SCREAMING_SNAKE_CASE_ ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: UpperCamelCase__ = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(SCREAMING_SNAKE_CASE_ , **{**default_dtype, **self.jnp_array_kwargs} ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(SCREAMING_SNAKE_CASE_ , """__array__""" ) and not isinstance(SCREAMING_SNAKE_CASE_ , jax.Array ): UpperCamelCase__ = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) for substruct in data_struct] ) elif isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) for substruct in data_struct] ) return self._tensorize(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): return map_nested(self._recursive_tensorize , SCREAMING_SNAKE_CASE_ , map_list=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.numpy_arrow_extractor().extract_row(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.python_features_decoder.decode_row(SCREAMING_SNAKE_CASE_ ) return self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.numpy_arrow_extractor().extract_column(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.python_features_decoder.decode_column(SCREAMING_SNAKE_CASE_ , pa_table.column_names[0] ) UpperCamelCase__ = self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self._consolidate(SCREAMING_SNAKE_CASE_ ) return column def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.numpy_arrow_extractor().extract_batch(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.python_features_decoder.decode_batch(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.recursive_tensorize(SCREAMING_SNAKE_CASE_ ) for column_name in batch: UpperCamelCase__ = self._consolidate(batch[column_name] ) return batch
86
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
1
from __future__ import annotations def __magic_name__ ( __a : list[int] ): # This function is recursive '''simple docstring''' UpperCamelCase__ = len(__a ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else UpperCamelCase__ = array[0] UpperCamelCase__ = False UpperCamelCase__ = 1 UpperCamelCase__ = [] while not is_found and i < array_length: if array[i] < pivot: UpperCamelCase__ = True UpperCamelCase__ = [element for element in array[i:] if element >= array[i]] UpperCamelCase__ = longest_subsequence(__a ) if len(__a ) > len(__a ): UpperCamelCase__ = temp_array else: i += 1 UpperCamelCase__ = [element for element in array[1:] if element >= pivot] UpperCamelCase__ = [pivot, *longest_subsequence(__a )] if len(__a ) > len(__a ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
86
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
1
import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="None" , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = relative_attention UpperCamelCase__ = position_biased_input UpperCamelCase__ = pos_att_type UpperCamelCase__ = scope def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = DebertaVaModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = DebertaVaForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = DebertaVaForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = DebertaVaForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = DebertaVaForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase__ = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = DebertaVaModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = DebertaVaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class __A( unittest.TestCase ): """simple docstring""" @unittest.skip(reason="""Model not available yet""" ) def UpperCAmelCase_ (self ): pass @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = DebertaVaModel.from_pretrained("""microsoft/deberta-v2-xlarge""" ) UpperCamelCase__ = torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] ) UpperCamelCase__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. UpperCamelCase__ = torch.tensor( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) , F"{output[:, 1:4, 1:4]}" )
86
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: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): 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=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.seq_length // 2 UpperCamelCase__ = 0 # first forward pass UpperCamelCase__ , UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase__ = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase__ = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) 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 , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 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.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase__ = tokenizer.eos_token UpperCamelCase__ = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase__ = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase__ = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase__ = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [ """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ (self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = """multi_label_classification""" UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = 4_23_84 UpperCamelCase__ = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase__ = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
1
# Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def __magic_name__ ( __a : Optional[int] , __a : Dict , __a : List[str]=0 ): '''simple docstring''' if name is None: UpperCamelCase__ = None else: UpperCamelCase__ = """.""" * max(0 , spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" UpperCamelCase__ = fmt.format(__a ) # Print and recurse (if needed). if isinstance(__a , __a ): if msg is not None: print(__a ) for k in val.keys(): recursive_print(__a , val[k] , spaces + 2 ) elif isinstance(__a , torch.Tensor ): print(__a , """:""" , val.size() ) else: print(__a , """:""" , __a ) def __magic_name__ ( __a : Any , __a : List[Any] , __a : int , __a : str , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] UpperCamelCase__ = (num_heads, hidden_size, num_splits) + input_shape[1:] UpperCamelCase__ = param.view(*__a ) UpperCamelCase__ = param.transpose(0 , 2 ) UpperCamelCase__ = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] UpperCamelCase__ = (num_heads, num_splits, hidden_size) + input_shape[1:] UpperCamelCase__ = param.view(*__a ) UpperCamelCase__ = param.transpose(0 , 1 ).contiguous() UpperCamelCase__ = param.view(*__a ) return param def __magic_name__ ( __a : Dict , __a : Any , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = {} # old versions did not store training args UpperCamelCase__ = input_state_dict.get("""args""" , __a ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) UpperCamelCase__ = ds_args.padded_vocab_size UpperCamelCase__ = ds_args.max_position_embeddings UpperCamelCase__ = ds_args.hidden_size UpperCamelCase__ = ds_args.num_layers UpperCamelCase__ = ds_args.num_attention_heads UpperCamelCase__ = ds_args.ffn_hidden_size # pprint(config) # The number of heads. UpperCamelCase__ = config.n_head # The hidden_size per head. UpperCamelCase__ = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): UpperCamelCase__ = input_state_dict["""checkpoint_version"""] else: UpperCamelCase__ = 0.0 # The model. UpperCamelCase__ = input_state_dict["""model"""] # The language model. UpperCamelCase__ = model["""language_model"""] # The embeddings. UpperCamelCase__ = lm["""embedding"""] # The word embeddings. UpperCamelCase__ = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. UpperCamelCase__ = word_embeddings[: config.vocab_size, :] UpperCamelCase__ = word_embeddings # The position embeddings. UpperCamelCase__ = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] UpperCamelCase__ = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match" ) # Store the position embeddings. UpperCamelCase__ = pos_embeddings # The transformer. UpperCamelCase__ = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. UpperCamelCase__ = re.compile(R"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. UpperCamelCase__ = { """attention.dense""": """.attn.c_proj.""", """self_attention.dense""": """.attn.c_proj.""", """mlp.dense_h_to_4h""": """.mlp.c_fc.""", """mlp.dense_4h_to_h""": """.mlp.c_proj.""", } # Extract the layers. for key, val in transformer.items(): # Match the name. UpperCamelCase__ = layer_re.match(__a ) # Stop if that's not a layer if m is None: break # The index of the layer. UpperCamelCase__ = int(m.group(1 ) ) # The name of the operation. UpperCamelCase__ = m.group(2 ) # Is it a weight or a bias? UpperCamelCase__ = m.group(3 ) # The name of the layer. UpperCamelCase__ = f"transformer.h.{layer_idx}" # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): UpperCamelCase__ = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" UpperCamelCase__ = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. UpperCamelCase__ = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , __a , __a ) UpperCamelCase__ = causal_mask # Insert a "dummy" tensor for masked_bias. UpperCamelCase__ = torch.tensor(-1E4 , dtype=torch.floataa ) UpperCamelCase__ = masked_bias UpperCamelCase__ = fix_query_key_value_ordering(__a , __a , 3 , __a , __a ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. UpperCamelCase__ = out_val.transpose(0 , 1 ).contiguous() # Store. UpperCamelCase__ = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": UpperCamelCase__ = fix_query_key_value_ordering(__a , __a , 3 , __a , __a ) # Store. No change of shape. UpperCamelCase__ = out_val # Transpose the weights. elif weight_or_bias == "weight": UpperCamelCase__ = megatron_to_transformers[op_name] UpperCamelCase__ = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": UpperCamelCase__ = megatron_to_transformers[op_name] UpperCamelCase__ = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. UpperCamelCase__ = transformer["""final_layernorm.weight"""] UpperCamelCase__ = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. UpperCamelCase__ = word_embeddings # It should be done! return output_state_dict def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" , action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" , type=__a , help="""Path to the checkpoint file (.zip archive or direct .pt file)""" , ) parser.add_argument( """--config_file""" , default="""""" , type=__a , help="""An optional config json file describing the pre-trained model.""" , ) UpperCamelCase__ = parser.parse_args() # Extract the basename. UpperCamelCase__ = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f"Extracting PyTorch state dictionary from {args.path_to_checkpoint}" ) if args.path_to_checkpoint.endswith(""".zip""" ): with zipfile.ZipFile(args.path_to_checkpoint , """r""" ) as checkpoint: with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) else: UpperCamelCase__ = torch.load(args.path_to_checkpoint , map_location="""cpu""" ) UpperCamelCase__ = input_state_dict.get("""args""" , __a ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: UpperCamelCase__ = """gelu_fast""" elif ds_args.openai_gelu: UpperCamelCase__ = """gelu_new""" else: UpperCamelCase__ = """gelu""" else: # in the very early days this used to be "gelu_new" UpperCamelCase__ = """gelu_new""" # Spell out all parameters in case the defaults change. UpperCamelCase__ = GPTaConfig( vocab_size=50_257 , n_positions=1_024 , n_embd=1_024 , n_layer=24 , n_head=16 , n_inner=4_096 , activation_function=__a , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1E-5 , initializer_range=0.02 , summary_type="""cls_index""" , summary_use_proj=__a , summary_activation=__a , summary_proj_to_labels=__a , summary_first_dropout=0.1 , scale_attn_weights=__a , use_cache=__a , bos_token_id=50_256 , eos_token_id=50_256 , ) else: UpperCamelCase__ = GPTaConfig.from_json_file(args.config_file ) UpperCamelCase__ = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) UpperCamelCase__ = convert_megatron_checkpoint(__a , __a , __a ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(__a , __a ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: UpperCamelCase__ = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": UpperCamelCase__ = """gpt2""" elif tokenizer_type == "PretrainedFromHF": UpperCamelCase__ = ds_args.tokenizer_name_or_path else: raise ValueError(f"Unrecognized tokenizer_type {tokenizer_type}" ) else: UpperCamelCase__ = """gpt2""" UpperCamelCase__ = AutoTokenizer.from_pretrained(__a ) UpperCamelCase__ = type(__a ).__name__ UpperCamelCase__ = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(__a ) # Save tokenizer based on args print(f"Adding {tokenizer_class} tokenizer files" ) tokenizer.save_pretrained(__a ) # Store the state_dict to file. UpperCamelCase__ = os.path.join(__a , """pytorch_model.bin""" ) print(f"Saving checkpoint to \"{output_checkpoint_file}\"" ) torch.save(__a , __a ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
86
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
1
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase_ = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = XGLMTokenizer SCREAMING_SNAKE_CASE__ = XGLMTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True def UpperCAmelCase_ (self ): super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase__ = XGLMTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ (self ): UpperCamelCase__ = """<pad>""" UpperCamelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 10_08 ) def UpperCAmelCase_ (self ): self.assertEqual(self.get_tokenizer().vocab_size , 10_08 ) def UpperCAmelCase_ (self ): UpperCamelCase__ = XGLMTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) UpperCamelCase__ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def UpperCAmelCase_ (self ): return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) def UpperCAmelCase_ (self ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE_ , f.name ) UpperCamelCase__ = XGLMTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = pickle.dumps(SCREAMING_SNAKE_CASE_ ) pickle.loads(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): if not self.test_rust_tokenizer: return UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_rust_tokenizer() UpperCamelCase__ = """I was born in 92000, and this is falsé.""" UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.get_rust_tokenizer() UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = """Hello World!""" UpperCamelCase__ = [2, 3_12_27, 44_47, 35] self.assertListEqual(SCREAMING_SNAKE_CASE_ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off UpperCamelCase__ = [2, 10_18, 67, 11, 19_88, 26_17, 56_31, 2_78, 11, 34_07, 48, 7_16_30, 2_80_85, 4, 32_34, 1_57, 13, 6, 5, 6, 4, 35_26, 7_68, 15, 6_59, 57, 2_98, 39_83, 8_64, 1_29, 21, 6, 5, 1_36_75, 3_77, 6_52, 75_80, 1_03_41, 1_55, 28_17, 4_22, 16_66, 7, 16_74, 53, 1_13, 20_22_77, 1_78_92, 33, 60, 87, 4, 32_34, 1_57, 61, 26_67, 5_23_76, 19, 88, 23, 7_35] # fmt: on self.assertListEqual(SCREAMING_SNAKE_CASE_ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE_ ) ) @slow def UpperCAmelCase_ (self ): # fmt: off UpperCamelCase__ = { """input_ids""": [[2, 10_88_25, 11_63, 15, 8_80_10, 4_73, 1_58_98, 1_57, 1_36_72, 18_57, 3_12, 8, 23_80_21, 11_63, 53, 1_36_72, 18_57, 3_12, 8, 5_32_83, 18_23_96, 8, 1_85_66, 16, 3_67_33, 41_01, 8, 2_30, 24_40_17, 12_25_53, 7, 15, 13_25_97, 4, 2_93, 1_25_11, 76_10, 4, 34_14, 13_25_97, 9, 4, 3_23_61, 3_62, 4, 7_34, 2_85_12, 3_25_69, 18, 4, 3_23_61, 2_60_96, 1_49_82, 73, 1_87_15, 2_14_33, 23_52_61, 15, 4_92, 1_24_27, 16, 53, 1_87_15, 2_14_33, 6_54_54, 15, 2_36_59, 5_63, 16, 2_78, 5_97, 28_43, 5_95, 79_31, 18_23_96, 6_41_86, 22, 8_86, 5_95, 13_29_81, 53, 2_55_40, 34_49, 4_39_82, 3_99_01, 59_51, 8_78, 3_30, 4, 2_76_94, 8_02_69, 3_12, 53, 65_17, 1_17_80, 6_11, 2_04_08, 5], [2, 6, 13_25_97, 67, 4_28_97, 33, 5_92, 8, 16_37_29, 2_55_40, 3_61, 13_69_97, 10_95_14, 17_32_30, 7, 5_01, 60, 10_29_13, 1_96, 56_31, 2_35, 6_32_43, 4_73, 6, 23_17_57, 74, 52_77, 79_05, 53, 30_95, 3_73_17, 22, 4_54, 18_38_74, 5], [2, 2_68, 3_12_98, 4_65_30, 6, 13_29_35, 4_38_31, 7, 5_97, 32, 24, 36_88, 98_65, 5]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE_ , model_name="""facebook/xglm-564M""" , padding=SCREAMING_SNAKE_CASE_ , )
86
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
1
from bisect import bisect from itertools import accumulate def __magic_name__ ( __a : str , __a : Tuple , __a : int , __a : str ): '''simple docstring''' UpperCamelCase__ = sorted(zip(__a , __a ) , key=lambda __a : x[0] / x[1] , reverse=__a ) UpperCamelCase__ , UpperCamelCase__ = [i[0] for i in r], [i[1] for i in r] UpperCamelCase__ = list(accumulate(__a ) ) UpperCamelCase__ = bisect(__a , __a ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
86
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
1
import sys lowerCamelCase_ = ( '''73167176531330624919225119674426574742355349194934''' '''96983520312774506326239578318016984801869478851843''' '''85861560789112949495459501737958331952853208805511''' '''12540698747158523863050715693290963295227443043557''' '''66896648950445244523161731856403098711121722383113''' '''62229893423380308135336276614282806444486645238749''' '''30358907296290491560440772390713810515859307960866''' '''70172427121883998797908792274921901699720888093776''' '''65727333001053367881220235421809751254540594752243''' '''52584907711670556013604839586446706324415722155397''' '''53697817977846174064955149290862569321978468622482''' '''83972241375657056057490261407972968652414535100474''' '''82166370484403199890008895243450658541227588666881''' '''16427171479924442928230863465674813919123162824586''' '''17866458359124566529476545682848912883142607690042''' '''24219022671055626321111109370544217506941658960408''' '''07198403850962455444362981230987879927244284909188''' '''84580156166097919133875499200524063689912560717606''' '''05886116467109405077541002256983155200055935729725''' '''71636269561882670428252483600823257530420752963450''' ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = 1 for digit in s: product *= int(__a ) return product def __magic_name__ ( __a : str = N ): '''simple docstring''' UpperCamelCase__ = -sys.maxsize - 1 UpperCamelCase__ = n[:13] UpperCamelCase__ = 13 while cur_index < len(__a ) - 13: if int(n[cur_index] ) >= int(substr[0] ): UpperCamelCase__ = substr[1:] + n[cur_index] cur_index += 1 else: UpperCamelCase__ = max(__a , str_eval(__a ) ) UpperCamelCase__ = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f'{solution() = }')
86
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import OwlViTImageProcessor, OwlViTProcessor @require_vision class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = tempfile.mkdtemp() # fmt: off UpperCamelCase__ = ["""""", """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073], """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711], } UpperCamelCase__ = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE_ ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token="""!""" , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token="""!""" , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ (self ): UpperCamelCase__ = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] UpperCamelCase__ = [Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_rust_tokenizer() UpperCamelCase__ = self.get_image_processor() UpperCamelCase__ = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor_slow.save_pretrained(self.tmpdirname ) UpperCamelCase__ = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor_fast.save_pretrained(self.tmpdirname ) UpperCamelCase__ = OwlViTProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(processor_fast.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(processor_fast.image_processor , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) UpperCamelCase__ = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_image_processor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.prepare_image_inputs() UpperCamelCase__ = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) UpperCamelCase__ = processor(images=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_image_processor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = processor(text=SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""np""" ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_image_processor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = self.prepare_image_inputs() UpperCamelCase__ = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def UpperCAmelCase_ (self ): UpperCamelCase__ = """google/owlvit-base-patch32""" UpperCamelCase__ = OwlViTProcessor.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ["""cat""", """nasa badge"""] UpperCamelCase__ = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 16 self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def UpperCAmelCase_ (self ): UpperCamelCase__ = """google/owlvit-base-patch32""" UpperCamelCase__ = OwlViTProcessor.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [["""cat""", """nasa badge"""], ["""person"""]] UpperCamelCase__ = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 16 UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = max([len(SCREAMING_SNAKE_CASE_ ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def UpperCAmelCase_ (self ): UpperCamelCase__ = """google/owlvit-base-patch32""" UpperCamelCase__ = OwlViTProcessor.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ["""cat""", """nasa badge"""] UpperCamelCase__ = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 16 UpperCamelCase__ = inputs["""input_ids"""] UpperCamelCase__ = [ [4_94_06, 23_68, 4_94_07, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_94_06, 68_41, 1_13_01, 4_94_07, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask"""] ) self.assertEqual(inputs["""input_ids"""].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_image_processor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.prepare_image_inputs() UpperCamelCase__ = self.prepare_image_inputs() UpperCamelCase__ = processor(images=SCREAMING_SNAKE_CASE_ , query_images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , ["""query_pixel_values""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_image_processor() UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = OwlViTProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase__ = processor.batch_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
1
from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 class __A( nn.Module ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = (16, 32, 96, 256) SCREAMING_SNAKE_CASE__ = jnp.floataa def UpperCAmelCase_ (self ): UpperCamelCase__ = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) UpperCamelCase__ = [] for i in range(len(self.block_out_channels ) - 1 ): UpperCamelCase__ = self.block_out_channels[i] UpperCamelCase__ = self.block_out_channels[i + 1] UpperCamelCase__ = nn.Conv( SCREAMING_SNAKE_CASE_ , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = nn.Conv( SCREAMING_SNAKE_CASE_ , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = blocks UpperCamelCase__ = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.conv_in(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = nn.silu(SCREAMING_SNAKE_CASE_ ) for block in self.blocks: UpperCamelCase__ = block(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = nn.silu(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.conv_out(SCREAMING_SNAKE_CASE_ ) return embedding @flax_register_to_config class __A( nn.Module , __lowerCamelCase , __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 32 SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = (320, 640, 1280, 1280) SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = 8 SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = 1280 SCREAMING_SNAKE_CASE__ = 0.0 SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = jnp.floataa SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = "rgb" SCREAMING_SNAKE_CASE__ = (16, 32, 96, 256) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): # init input tensors UpperCamelCase__ = (1, self.in_channels, self.sample_size, self.sample_size) UpperCamelCase__ = jnp.zeros(SCREAMING_SNAKE_CASE_ , dtype=jnp.floataa ) UpperCamelCase__ = jnp.ones((1,) , dtype=jnp.intaa ) UpperCamelCase__ = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) UpperCamelCase__ = (1, 3, self.sample_size * 8, self.sample_size * 8) UpperCamelCase__ = jnp.zeros(SCREAMING_SNAKE_CASE_ , dtype=jnp.floataa ) UpperCamelCase__ , UpperCamelCase__ = jax.random.split(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = {"""params""": params_rng, """dropout""": dropout_rng} return self.init(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )["params"] def UpperCAmelCase_ (self ): UpperCamelCase__ = self.block_out_channels UpperCamelCase__ = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. UpperCamelCase__ = self.num_attention_heads or self.attention_head_dim # input UpperCamelCase__ = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time UpperCamelCase__ = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) UpperCamelCase__ = FlaxTimestepEmbedding(SCREAMING_SNAKE_CASE_ , dtype=self.dtype ) UpperCamelCase__ = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) UpperCamelCase__ = self.only_cross_attention if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = (only_cross_attention,) * len(self.down_block_types ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = (num_attention_heads,) * len(self.down_block_types ) # down UpperCamelCase__ = [] UpperCamelCase__ = [] UpperCamelCase__ = block_out_channels[0] UpperCamelCase__ = nn.Conv( SCREAMING_SNAKE_CASE_ , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(SCREAMING_SNAKE_CASE_ ) for i, down_block_type in enumerate(self.down_block_types ): UpperCamelCase__ = output_channel UpperCamelCase__ = block_out_channels[i] UpperCamelCase__ = i == len(SCREAMING_SNAKE_CASE_ ) - 1 if down_block_type == "CrossAttnDownBlock2D": UpperCamelCase__ = FlaxCrossAttnDownBlockaD( in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: UpperCamelCase__ = FlaxDownBlockaD( in_channels=SCREAMING_SNAKE_CASE_ , out_channels=SCREAMING_SNAKE_CASE_ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(SCREAMING_SNAKE_CASE_ ) for _ in range(self.layers_per_block ): UpperCamelCase__ = nn.Conv( SCREAMING_SNAKE_CASE_ , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(SCREAMING_SNAKE_CASE_ ) if not is_final_block: UpperCamelCase__ = nn.Conv( SCREAMING_SNAKE_CASE_ , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = down_blocks UpperCamelCase__ = controlnet_down_blocks # mid UpperCamelCase__ = block_out_channels[-1] UpperCamelCase__ = FlaxUNetMidBlockaDCrossAttn( in_channels=SCREAMING_SNAKE_CASE_ , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) UpperCamelCase__ = nn.Conv( SCREAMING_SNAKE_CASE_ , kernel_size=(1, 1) , padding="""VALID""" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 1.0 , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = False , ): UpperCamelCase__ = self.controlnet_conditioning_channel_order if channel_order == "bgr": UpperCamelCase__ = jnp.flip(SCREAMING_SNAKE_CASE_ , axis=1 ) # 1. time if not isinstance(SCREAMING_SNAKE_CASE_ , jnp.ndarray ): UpperCamelCase__ = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(SCREAMING_SNAKE_CASE_ , jnp.ndarray ) and len(timesteps.shape ) == 0: UpperCamelCase__ = timesteps.astype(dtype=jnp.floataa ) UpperCamelCase__ = jnp.expand_dims(SCREAMING_SNAKE_CASE_ , 0 ) UpperCamelCase__ = self.time_proj(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.time_embedding(SCREAMING_SNAKE_CASE_ ) # 2. pre-process UpperCamelCase__ = jnp.transpose(SCREAMING_SNAKE_CASE_ , (0, 2, 3, 1) ) UpperCamelCase__ = self.conv_in(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = jnp.transpose(SCREAMING_SNAKE_CASE_ , (0, 2, 3, 1) ) UpperCamelCase__ = self.controlnet_cond_embedding(SCREAMING_SNAKE_CASE_ ) sample += controlnet_cond # 3. down UpperCamelCase__ = (sample,) for down_block in self.down_blocks: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ , UpperCamelCase__ = down_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , deterministic=not train ) else: UpperCamelCase__ , UpperCamelCase__ = down_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , deterministic=not train ) down_block_res_samples += res_samples # 4. mid UpperCamelCase__ = self.mid_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , deterministic=not train ) # 5. contronet blocks UpperCamelCase__ = () for down_block_res_sample, controlnet_block in zip(SCREAMING_SNAKE_CASE_ , self.controlnet_down_blocks ): UpperCamelCase__ = controlnet_block(SCREAMING_SNAKE_CASE_ ) controlnet_down_block_res_samples += (down_block_res_sample,) UpperCamelCase__ = controlnet_down_block_res_samples UpperCamelCase__ = self.controlnet_mid_block(SCREAMING_SNAKE_CASE_ ) # 6. scaling UpperCamelCase__ = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=SCREAMING_SNAKE_CASE_ , mid_block_res_sample=SCREAMING_SNAKE_CASE_ )
86
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
1
def __magic_name__ ( __a : int = 100 ): '''simple docstring''' UpperCamelCase__ = n * (n + 1) * (2 * n + 1) / 6 UpperCamelCase__ = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f'{solution() = }')
86
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
1
from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def __magic_name__ ( __a : Dict[str, torch.Tensor] ): '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = [] UpperCamelCase__ = [] for rt in rc.restypes: UpperCamelCase__ = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) UpperCamelCase__ = {name: i for i, name in enumerate(__a )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) UpperCamelCase__ = torch.tensor( __a , dtype=torch.intaa , device=protein["""aatype"""].device , ) UpperCamelCase__ = torch.tensor( __a , dtype=torch.intaa , device=protein["""aatype"""].device , ) UpperCamelCase__ = torch.tensor( __a , dtype=torch.floataa , device=protein["""aatype"""].device , ) UpperCamelCase__ = protein["""aatype"""].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein UpperCamelCase__ = restype_atomaa_to_atomaa[protein_aatype] UpperCamelCase__ = restype_atomaa_mask[protein_aatype] UpperCamelCase__ = residx_atomaa_mask UpperCamelCase__ = residx_atomaa_to_atomaa.long() # create the gather indices for mapping back UpperCamelCase__ = restype_atomaa_to_atomaa[protein_aatype] UpperCamelCase__ = residx_atomaa_to_atomaa.long() # create the corresponding mask UpperCamelCase__ = torch.zeros([21, 37] , dtype=torch.floataa , device=protein["""aatype"""].device ) for restype, restype_letter in enumerate(rc.restypes ): UpperCamelCase__ = rc.restype_atoa[restype_letter] UpperCamelCase__ = rc.residue_atoms[restype_name] for atom_name in atom_names: UpperCamelCase__ = rc.atom_order[atom_name] UpperCamelCase__ = 1 UpperCamelCase__ = restype_atomaa_mask[protein_aatype] UpperCamelCase__ = residx_atomaa_mask return protein def __magic_name__ ( __a : Dict[str, torch.Tensor] ): '''simple docstring''' UpperCamelCase__ = tree_map(lambda __a : torch.tensor(__a , device=batch["""aatype"""].device ) , __a , np.ndarray ) UpperCamelCase__ = tensor_tree_map(lambda __a : np.array(__a ) , make_atomaa_masks(__a ) ) return out
86
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
1
def __magic_name__ ( __a : int = 10**9 ): '''simple docstring''' UpperCamelCase__ = 1 UpperCamelCase__ = 2 UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value UpperCamelCase__ = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(f'{solution() = }')
86
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''microsoft/table-transformer-detection''': ( '''https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json''' ), } class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """table-transformer""" SCREAMING_SNAKE_CASE__ = ["""past_key_values"""] SCREAMING_SNAKE_CASE__ = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__(self , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=1_00 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="sine" , SCREAMING_SNAKE_CASE_="resnet50" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.1 , **SCREAMING_SNAKE_CASE_ , ): 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__ = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = backbone_config.get("""model_type""" ) UpperCamelCase__ = CONFIG_MAPPING[backbone_model_type] UpperCamelCase__ = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) # set timm attributes to None UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None, None, None UpperCamelCase__ = use_timm_backbone UpperCamelCase__ = backbone_config UpperCamelCase__ = num_channels UpperCamelCase__ = num_queries UpperCamelCase__ = d_model UpperCamelCase__ = encoder_ffn_dim UpperCamelCase__ = encoder_layers UpperCamelCase__ = encoder_attention_heads UpperCamelCase__ = decoder_ffn_dim UpperCamelCase__ = decoder_layers UpperCamelCase__ = decoder_attention_heads UpperCamelCase__ = dropout UpperCamelCase__ = attention_dropout UpperCamelCase__ = activation_dropout UpperCamelCase__ = activation_function UpperCamelCase__ = init_std UpperCamelCase__ = init_xavier_std UpperCamelCase__ = encoder_layerdrop UpperCamelCase__ = decoder_layerdrop UpperCamelCase__ = encoder_layers UpperCamelCase__ = auxiliary_loss UpperCamelCase__ = position_embedding_type UpperCamelCase__ = backbone UpperCamelCase__ = use_pretrained_backbone UpperCamelCase__ = dilation # Hungarian matcher UpperCamelCase__ = class_cost UpperCamelCase__ = bbox_cost UpperCamelCase__ = giou_cost # Loss coefficients UpperCamelCase__ = mask_loss_coefficient UpperCamelCase__ = dice_loss_coefficient UpperCamelCase__ = bbox_loss_coefficient UpperCamelCase__ = giou_loss_coefficient UpperCamelCase__ = eos_coefficient super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase_ (self ): return self.encoder_attention_heads @property def UpperCAmelCase_ (self ): return self.d_model class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = version.parse("""1.11""" ) @property def UpperCAmelCase_ (self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def UpperCAmelCase_ (self ): return 1E-5 @property def UpperCAmelCase_ (self ): return 12
86
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
1
import math from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''facebook/data2vec-base-960h''': '''https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json''', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """data2vec-audio""" def __init__(self , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=30_72 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-5 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , SCREAMING_SNAKE_CASE_=(5, 2, 2, 2, 2, 2, 2) , SCREAMING_SNAKE_CASE_=(10, 3, 3, 3, 3, 2, 2) , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=19 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=0.05 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="sum" , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=(5_12, 5_12, 5_12, 5_12, 15_00) , SCREAMING_SNAKE_CASE_=(5, 3, 3, 1, 1) , SCREAMING_SNAKE_CASE_=(1, 2, 3, 1, 1) , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = hidden_size UpperCamelCase__ = feat_extract_activation UpperCamelCase__ = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = conv_bias UpperCamelCase__ = num_conv_pos_embeddings UpperCamelCase__ = num_conv_pos_embedding_groups UpperCamelCase__ = conv_pos_kernel_size UpperCamelCase__ = len(self.conv_dim ) UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_dropout UpperCamelCase__ = attention_dropout UpperCamelCase__ = activation_dropout UpperCamelCase__ = feat_proj_dropout UpperCamelCase__ = final_dropout UpperCamelCase__ = layerdrop UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = initializer_range UpperCamelCase__ = vocab_size UpperCamelCase__ = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" F" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`," F" `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 UpperCamelCase__ = mask_time_prob UpperCamelCase__ = mask_time_length UpperCamelCase__ = mask_time_min_masks UpperCamelCase__ = mask_feature_prob UpperCamelCase__ = mask_feature_length UpperCamelCase__ = mask_feature_min_masks # ctc loss UpperCamelCase__ = ctc_loss_reduction UpperCamelCase__ = ctc_zero_infinity # adapter UpperCamelCase__ = add_adapter UpperCamelCase__ = adapter_kernel_size UpperCamelCase__ = adapter_stride UpperCamelCase__ = num_adapter_layers UpperCamelCase__ = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCamelCase__ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCamelCase__ = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = xvector_output_dim @property def UpperCAmelCase_ (self ): return math.prod(self.conv_stride )
86
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
1
from __future__ import annotations class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = order # a_{0} ... a_{k} UpperCamelCase__ = [1.0] + [0.0] * order # b_{0} ... b_{k} UpperCamelCase__ = [1.0] + [0.0] * order # x[n-1] ... x[n-k] UpperCamelCase__ = [0.0] * self.order # y[n-1] ... y[n-k] UpperCamelCase__ = [0.0] * self.order def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if len(SCREAMING_SNAKE_CASE_ ) < self.order: UpperCamelCase__ = [1.0, *a_coeffs] if len(SCREAMING_SNAKE_CASE_ ) != self.order + 1: UpperCamelCase__ = ( F"Expected a_coeffs to have {self.order + 1} elements " F"for {self.order}-order filter, got {len(SCREAMING_SNAKE_CASE_ )}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) != self.order + 1: UpperCamelCase__ = ( F"Expected b_coeffs to have {self.order + 1} elements " F"for {self.order}-order filter, got {len(SCREAMING_SNAKE_CASE_ )}" ) raise ValueError(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = a_coeffs UpperCamelCase__ = b_coeffs def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) UpperCamelCase__ = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] UpperCamelCase__ = self.input_history[:-1] UpperCamelCase__ = self.output_history[:-1] UpperCamelCase__ = sample UpperCamelCase__ = result return result
86
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
1
import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowerCamelCase_ = { '''<''': operator.lt, '''<=''': operator.le, '''==''': operator.eq, '''!=''': operator.ne, '''>=''': operator.ge, '''>''': operator.gt, } def __magic_name__ ( __a : str , __a : Tuple , __a : List[Any] , __a : List[Any] , __a : int , __a : Optional[Any] ): '''simple docstring''' if got_ver is None or want_ver is None: raise ValueError( f"Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider" f" reinstalling {pkg}." ) if not ops[op](version.parse(__a ) , version.parse(__a ) ): raise ImportError( f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}" ) def __magic_name__ ( __a : str , __a : Optional[str] = None ): '''simple docstring''' UpperCamelCase__ = f"\n{hint}" if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __a ): UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = requirement, None, None else: UpperCamelCase__ = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __a ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" f" got {requirement}" ) UpperCamelCase__ , UpperCamelCase__ = match[0] UpperCamelCase__ = want_full.split(""",""" ) # there could be multiple requirements UpperCamelCase__ = {} for w in want_range: UpperCamelCase__ = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __a ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" f" but got {requirement}" ) UpperCamelCase__ , UpperCamelCase__ = match[0] UpperCamelCase__ = want_ver if op not in ops: raise ValueError(f"{requirement}: need one of {list(ops.keys() )}, but got {op}" ) # special case if pkg == "python": UpperCamelCase__ = """.""".join([str(__a ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__a , __a , __a , __a , __a , __a ) return # check if any version is installed try: UpperCamelCase__ = importlib.metadata.version(__a ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( f"The '{requirement}' distribution was not found and is required by this application. {hint}" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__a , __a , __a , __a , __a , __a ) def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__a , __a )
86
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
1
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar lowerCamelCase_ = TypeVar('''T''') class __A( Generic[T] ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ = True ): UpperCamelCase__ = {} # dictionary of lists UpperCamelCase__ = directed def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(SCREAMING_SNAKE_CASE_ ) self.adj_list[destination_vertex].append(SCREAMING_SNAKE_CASE_ ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: UpperCamelCase__ = [destination_vertex] UpperCamelCase__ = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(SCREAMING_SNAKE_CASE_ ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: UpperCamelCase__ = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: UpperCamelCase__ = [destination_vertex] UpperCamelCase__ = [] return self def __repr__(self ): return pformat(self.adj_list )
86
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
1
from ...configuration_utils import PretrainedConfig lowerCamelCase_ = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wikisql-supervised''': ( '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json''' ), '''google/tapas-base-finetuned-tabfact''': ( '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json''' ), } class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """tapas""" def __init__(self , SCREAMING_SNAKE_CASE_=3_05_22 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=30_72 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10_24 , SCREAMING_SNAKE_CASE_=[3, 2_56, 2_56, 2, 2_56, 2_56, 10] , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=10.0 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="ratio" , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_sizes UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps # Fine-tuning task hyperparameters UpperCamelCase__ = positive_label_weight UpperCamelCase__ = num_aggregation_labels UpperCamelCase__ = aggregation_loss_weight UpperCamelCase__ = use_answer_as_supervision UpperCamelCase__ = answer_loss_importance UpperCamelCase__ = use_normalized_answer_loss UpperCamelCase__ = huber_loss_delta UpperCamelCase__ = temperature UpperCamelCase__ = aggregation_temperature UpperCamelCase__ = use_gumbel_for_cells UpperCamelCase__ = use_gumbel_for_aggregation UpperCamelCase__ = average_approximation_function UpperCamelCase__ = cell_selection_preference UpperCamelCase__ = answer_loss_cutoff UpperCamelCase__ = max_num_rows UpperCamelCase__ = max_num_columns UpperCamelCase__ = average_logits_per_cell UpperCamelCase__ = select_one_column UpperCamelCase__ = allow_empty_column_selection UpperCamelCase__ = init_cell_selection_weights_to_zero UpperCamelCase__ = reset_position_index_per_cell UpperCamelCase__ = disable_per_token_loss # Aggregation hyperparameters UpperCamelCase__ = aggregation_labels UpperCamelCase__ = no_aggregation_label_index if isinstance(self.aggregation_labels , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in aggregation_labels.items()}
86
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
1
from math import ceil def __magic_name__ ( __a : int = 1_001 ): '''simple docstring''' UpperCamelCase__ = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): UpperCamelCase__ = 2 * i + 1 UpperCamelCase__ = 2 * i UpperCamelCase__ = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: lowerCamelCase_ = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
86
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
1
def __magic_name__ ( __a : int = 600_851_475_143 ): '''simple docstring''' try: UpperCamelCase__ = int(__a ) except (TypeError, ValueError): raise TypeError("""Parameter n must be int or castable to int.""" ) if n <= 0: raise ValueError("""Parameter n must be greater than or equal to one.""" ) UpperCamelCase__ = 2 UpperCamelCase__ = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 UpperCamelCase__ = i while n % i == 0: UpperCamelCase__ = n // i i += 1 return int(__a ) if __name__ == "__main__": print(f'{solution() = }')
86
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
1
from math import factorial def __magic_name__ ( __a : int , __a : int , __a : float ): '''simple docstring''' if successes > trials: raise ValueError("""successes must be lower or equal to trials""" ) if trials < 0 or successes < 0: raise ValueError("""the function is defined for non-negative integers""" ) if not isinstance(__a , __a ) or not isinstance(__a , __a ): raise ValueError("""the function is defined for non-negative integers""" ) if not 0 < prob < 1: raise ValueError("""prob has to be in range of 1 - 0""" ) UpperCamelCase__ = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! UpperCamelCase__ = float(factorial(__a ) ) coefficient /= factorial(__a ) * factorial(trials - successes ) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('''Probability of 2 successes out of 4 trails''') print('''with probability of 0.75 is:''', end=''' ''') print(binomial_distribution(2, 4, 0.75))
86
import os from datetime import datetime as dt from github import Github lowerCamelCase_ = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''enhancement''', '''new pipeline/model''', '''new scheduler''', '''wip''', ] def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Github(os.environ["""GITHUB_TOKEN"""] ) UpperCamelCase__ = g.get_repo("""huggingface/diffusers""" ) UpperCamelCase__ = repo.get_issues(state="""open""" ) for issue in open_issues: UpperCamelCase__ = sorted(issue.get_comments() , key=lambda __a : i.created_at , reverse=__a ) UpperCamelCase__ = comments[0] if len(__a ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
86
1
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def __magic_name__ ( __a : bool = True , *__a : Any , **__a : List[Any] ): '''simple docstring''' if not is_tqdm_available(): raise ImportError("""Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.""" ) UpperCamelCase__ = False if main_process_only: UpperCamelCase__ = PartialState().local_process_index == 0 return _tqdm(*__a , **__a , disable=__a )
86
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ , UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
86
1
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = Dict[str, Any] lowerCamelCase_ = List[Prediction] @add_end_docstrings(__lowerCamelCase ) class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if self.framework == "tf": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = {} if "threshold" in kwargs: UpperCamelCase__ = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return super().__call__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = load_image(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.IntTensor([[image.height, image.width]] ) UpperCamelCase__ = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: UpperCamelCase__ = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) UpperCamelCase__ = target_size return inputs def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = model_inputs.pop("""target_size""" ) UpperCamelCase__ = self.model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: UpperCamelCase__ = model_inputs["""bbox"""] return model_outputs def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0.9 ): UpperCamelCase__ = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. UpperCamelCase__ , UpperCamelCase__ = target_size[0].tolist() def unnormalize(SCREAMING_SNAKE_CASE_ ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 10_00), (height * bbox[1] / 10_00), (width * bbox[2] / 10_00), (height * bbox[3] / 10_00), ] ) ) UpperCamelCase__ , UpperCamelCase__ = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) UpperCamelCase__ = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] UpperCamelCase__ = [unnormalize(SCREAMING_SNAKE_CASE_ ) for bbox in model_outputs["""bbox"""].squeeze(0 )] UpperCamelCase__ = ["""score""", """label""", """box"""] UpperCamelCase__ = [dict(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) for vals in zip(scores.tolist() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel UpperCamelCase__ = self.image_processor.post_process_object_detection(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = raw_annotations[0] UpperCamelCase__ = raw_annotation["""scores"""] UpperCamelCase__ = raw_annotation["""labels"""] UpperCamelCase__ = raw_annotation["""boxes"""] UpperCamelCase__ = scores.tolist() UpperCamelCase__ = [self.model.config.idalabel[label.item()] for label in labels] UpperCamelCase__ = [self._get_bounding_box(SCREAMING_SNAKE_CASE_ ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] UpperCamelCase__ = ["""score""", """label""", """box"""] UpperCamelCase__ = [ dict(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = box.int().tolist() UpperCamelCase__ = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
86
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
1
import numpy as np class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = (0, 0) UpperCamelCase__ = None UpperCamelCase__ = 0 UpperCamelCase__ = 0 UpperCamelCase__ = 0 def __eq__(self , SCREAMING_SNAKE_CASE_ ): return self.position == cell.position def UpperCAmelCase_ (self ): print(self.position ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_=(5, 5) ): UpperCamelCase__ = np.zeros(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = world_size[0] UpperCamelCase__ = world_size[1] def UpperCAmelCase_ (self ): print(self.w ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] UpperCamelCase__ = cell.position[0] UpperCamelCase__ = cell.position[1] UpperCamelCase__ = [] for n in neughbour_cord: UpperCamelCase__ = current_x + n[0] UpperCamelCase__ = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: UpperCamelCase__ = Cell() UpperCamelCase__ = (x, y) UpperCamelCase__ = cell neighbours.append(SCREAMING_SNAKE_CASE_ ) return neighbours def __magic_name__ ( __a : Optional[Any] , __a : str , __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = [] _open.append(__a ) while _open: UpperCamelCase__ = np.argmin([n.f for n in _open] ) UpperCamelCase__ = _open[min_f] _closed.append(_open.pop(__a ) ) if current == goal: break for n in world.get_neigbours(__a ): for c in _closed: if c == n: continue UpperCamelCase__ = current.g + 1 UpperCamelCase__ , UpperCamelCase__ = n.position UpperCamelCase__ , UpperCamelCase__ = goal.position UpperCamelCase__ = (ya - ya) ** 2 + (xa - xa) ** 2 UpperCamelCase__ = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(__a ) UpperCamelCase__ = [] while current.parent is not None: path.append(current.position ) UpperCamelCase__ = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowerCamelCase_ = Gridworld() # Start position and goal lowerCamelCase_ = Cell() lowerCamelCase_ = (0, 0) lowerCamelCase_ = Cell() lowerCamelCase_ = (4, 4) print(f'path from {start.position} to {goal.position}') lowerCamelCase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowerCamelCase_ = 1 print(world.w)
86
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
1
def __magic_name__ ( __a : list , __a : list , __a : int ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[0] * n for i in range(__a )] for i in range(__a ): UpperCamelCase__ = y_points[i] for i in range(2 , __a ): for j in range(__a , __a ): UpperCamelCase__ = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
86
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: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): 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=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.seq_length // 2 UpperCamelCase__ = 0 # first forward pass UpperCamelCase__ , UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase__ = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase__ = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) 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 , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 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.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase__ = tokenizer.eos_token UpperCamelCase__ = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase__ = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase__ = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase__ = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [ """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ (self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = """multi_label_classification""" UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = 4_23_84 UpperCamelCase__ = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase__ = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCamelCase_ = {'''configuration_speech_encoder_decoder''': ['''SpeechEncoderDecoderConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''SpeechEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''FlaxSpeechEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
1
def __magic_name__ ( __a : int = 1_000 ): '''simple docstring''' UpperCamelCase__ = 2**power UpperCamelCase__ = str(__a ) UpperCamelCase__ = list(__a ) UpperCamelCase__ = 0 for i in list_num: sum_of_num += int(__a ) return sum_of_num if __name__ == "__main__": lowerCamelCase_ = int(input('''Enter the power of 2: ''').strip()) print('''2 ^ ''', power, ''' = ''', 2**power) lowerCamelCase_ = solution(power) print('''Sum of the digits is: ''', result)
86
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''s-JoL/Open-Llama-V1''': '''https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json''', } class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = """open-llama""" def __init__(self , SCREAMING_SNAKE_CASE_=10_00_00 , SCREAMING_SNAKE_CASE_=40_96 , SCREAMING_SNAKE_CASE_=1_10_08 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_="silu" , SCREAMING_SNAKE_CASE_=20_48 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-6 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = vocab_size UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = hidden_size UpperCamelCase__ = intermediate_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = initializer_range UpperCamelCase__ = rms_norm_eps UpperCamelCase__ = use_cache UpperCamelCase__ = kwargs.pop( """use_memorry_efficient_attention""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_dropout_prob UpperCamelCase__ = use_stable_embedding UpperCamelCase__ = shared_input_output_embedding UpperCamelCase__ = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE_ ) or len(self.rope_scaling ) != 2: raise ValueError( """`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, """ F"got {self.rope_scaling}" ) UpperCamelCase__ = self.rope_scaling.get("""type""" , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.rope_scaling.get("""factor""" , SCREAMING_SNAKE_CASE_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
86
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
1
import random from typing import Any def __magic_name__ ( __a : list ): '''simple docstring''' for _ in range(len(__a ) ): UpperCamelCase__ = random.randint(0 , len(__a ) - 1 ) UpperCamelCase__ = random.randint(0 , len(__a ) - 1 ) UpperCamelCase__ , UpperCamelCase__ = data[b], data[a] return data if __name__ == "__main__": lowerCamelCase_ = [0, 1, 2, 3, 4, 5, 6, 7] lowerCamelCase_ = ['''python''', '''says''', '''hello''', '''!'''] print('''Fisher-Yates Shuffle:''') print('''List''', integers, strings) print('''FY Shuffle''', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
86
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
1
lowerCamelCase_ = '''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
86
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
1
def __magic_name__ ( __a : Optional[int] , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = [0 for i in range(r + 1 )] # nc0 = 1 UpperCamelCase__ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. UpperCamelCase__ = min(__a , __a ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
86
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
1
import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = LEDTokenizer SCREAMING_SNAKE_CASE__ = LEDTokenizerFast SCREAMING_SNAKE_CASE__ = True def UpperCAmelCase_ (self ): super().setUp() UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): return "lower newer", "lower newer" @cached_property def UpperCAmelCase_ (self ): return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def UpperCAmelCase_ (self ): return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] UpperCamelCase__ = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , max_length=len(SCREAMING_SNAKE_CASE_ ) , padding=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) UpperCamelCase__ = batch.input_ids.tolist()[0] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) self.assertIn("""input_ids""" , SCREAMING_SNAKE_CASE_ ) self.assertIn("""attention_mask""" , SCREAMING_SNAKE_CASE_ ) self.assertNotIn("""labels""" , SCREAMING_SNAKE_CASE_ ) self.assertNotIn("""decoder_attention_mask""" , SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(text_target=SCREAMING_SNAKE_CASE_ , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def UpperCAmelCase_ (self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer( ["""I am a small frog""" * 10_24, """I am a small frog"""] , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(batch.input_ids.shape , (2, 51_22) ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""A long paragraph for summarization."""] UpperCamelCase__ = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) UpperCamelCase__ = tokenizer(text_target=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" ) UpperCamelCase__ = inputs["""input_ids"""] UpperCamelCase__ = targets["""input_ids"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def UpperCAmelCase_ (self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = ["""Summary of the text.""", """Another summary."""] UpperCamelCase__ = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * len(SCREAMING_SNAKE_CASE_ ) for x in encoded_output["""input_ids"""]] UpperCamelCase__ = tokenizer.pad(SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(outputs["""global_attention_mask"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
86
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
1
from __future__ import annotations lowerCamelCase_ = list[list[int]] # assigning initial values to the grid lowerCamelCase_ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution lowerCamelCase_ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def __magic_name__ ( __a : Matrix , __a : int , __a : int , __a : int ): '''simple docstring''' for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def __magic_name__ ( __a : Matrix ): '''simple docstring''' for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def __magic_name__ ( __a : Matrix ): '''simple docstring''' if location := find_empty_location(__a ): UpperCamelCase__ , UpperCamelCase__ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(__a , __a , __a , __a ): UpperCamelCase__ = digit if sudoku(__a ) is not None: return grid UpperCamelCase__ = 0 return None def __magic_name__ ( __a : Matrix ): '''simple docstring''' for row in grid: for cell in row: print(__a , end=""" """ ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 20) print_solution(example_grid) print('''\nExample grid solution:''') lowerCamelCase_ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
86
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
1
def __magic_name__ ( __a : list[list[int]] , __a : int , __a : int , __a : set ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = len(__a ), len(grid[0] ) if ( min(__a , __a ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) UpperCamelCase__ = 0 count += depth_first_search(__a , row + 1 , __a , __a ) count += depth_first_search(__a , row - 1 , __a , __a ) count += depth_first_search(__a , __a , col + 1 , __a ) count += depth_first_search(__a , __a , col - 1 , __a ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
86
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
1
import math def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 UpperCamelCase__ = 0 while num > 0: UpperCamelCase__ = num % 8 UpperCamelCase__ = octal + (remainder * math.floor(math.pow(10 , __a ) )) counter += 1 UpperCamelCase__ = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"0o{int(__a )}" def __magic_name__ ( ): '''simple docstring''' print("""\n2 in octal is:""" ) print(decimal_to_octal(2 ) ) # = 2 print("""\n8 in octal is:""" ) print(decimal_to_octal(8 ) ) # = 10 print("""\n65 in octal is:""" ) print(decimal_to_octal(65 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(216 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(512 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
86
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
1
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 lowerCamelCase_ = '''CompVis/stable-diffusion-v1-1''' lowerCamelCase_ = '''CompVis/stable-diffusion-v1-2''' lowerCamelCase_ = '''CompVis/stable-diffusion-v1-3''' lowerCamelCase_ = '''CompVis/stable-diffusion-v1-4''' class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True , ): super()._init_() UpperCamelCase__ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = StableDiffusionPipeline( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , requires_safety_checker=SCREAMING_SNAKE_CASE_ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCAmelCase_ (self ): return {k: getattr(self , SCREAMING_SNAKE_CASE_ ) for k in self.config.keys() if not k.startswith("""_""" )} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): return self.pipea( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) @torch.no_grad() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , **SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = """cuda""" if torch.cuda.is_available() else """cpu""" self.to(SCREAMING_SNAKE_CASE_ ) # 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__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCamelCase__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCamelCase__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCamelCase__ = self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE_ , height=SCREAMING_SNAKE_CASE_ , width=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , output_type=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , callback=SCREAMING_SNAKE_CASE_ , callback_steps=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # 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]] )
86
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
1
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( """The RoBERTa Model transformer with early exiting (DeeRoBERTa). """ , __lowerCamelCase , ) class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaConfig SCREAMING_SNAKE_CASE__ = """roberta""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = RobertaEmbeddings(SCREAMING_SNAKE_CASE_ ) self.init_weights() @add_start_docstrings( """RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. """ , __lowerCamelCase , ) class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaConfig SCREAMING_SNAKE_CASE__ = """roberta""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = config.num_labels UpperCamelCase__ = config.num_hidden_layers UpperCamelCase__ = DeeRobertaModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = nn.Dropout(config.hidden_dropout_prob ) UpperCamelCase__ = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=-1 , SCREAMING_SNAKE_CASE_=False , ): UpperCamelCase__ = self.num_layers try: UpperCamelCase__ = self.roberta( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , position_ids=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = outputs[1] UpperCamelCase__ = self.dropout(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.classifier(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: UpperCamelCase__ = e.message UpperCamelCase__ = e.exit_layer UpperCamelCase__ = outputs[0] if not self.training: UpperCamelCase__ = entropy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [] UpperCamelCase__ = [] if labels is not None: if self.num_labels == 1: # We are doing regression UpperCamelCase__ = MSELoss() UpperCamelCase__ = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: UpperCamelCase__ = CrossEntropyLoss() UpperCamelCase__ = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits UpperCamelCase__ = [] for highway_exit in outputs[-1]: UpperCamelCase__ = highway_exit[0] if not self.training: highway_logits_all.append(SCREAMING_SNAKE_CASE_ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression UpperCamelCase__ = MSELoss() UpperCamelCase__ = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: UpperCamelCase__ = CrossEntropyLoss() UpperCamelCase__ = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(SCREAMING_SNAKE_CASE_ ) if train_highway: UpperCamelCase__ = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: UpperCamelCase__ = (loss,) + outputs if not self.training: UpperCamelCase__ = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: UpperCamelCase__ = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
86
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
1
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertTokenizer SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = filter_non_english def UpperCAmelCase_ (self ): super().setUp() UpperCamelCase__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] UpperCamelCase__ = {} UpperCamelCase__ = {} for i, value in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = i UpperCamelCase__ = i UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ensure_ascii=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = RoCBertBasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] UpperCamelCase__ = {} for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = i UpperCamelCase__ = RoCBertWordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_ , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def UpperCAmelCase_ (self ): self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def UpperCAmelCase_ (self ): self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def UpperCAmelCase_ (self ): self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: UpperCamelCase__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = F"A, naïve {tokenizer_r.mask_token} AllenNLP sentence." UpperCamelCase__ = tokenizer_r.encode_plus( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer_r.do_lower_case if hasattr(SCREAMING_SNAKE_CASE_ , """do_lower_case""" ) else False UpperCamelCase__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""的""", """人""", """有"""] UpperCamelCase__ = """""".join(SCREAMING_SNAKE_CASE_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = True UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = False UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCamelCase__ = [ F"##{token}" if idx != 0 else token for idx, token in enumerate(SCREAMING_SNAKE_CASE_ ) ] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCamelCase__ = tokenizer.encode("""你好""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""你是谁""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizers(do_lower_case=SCREAMING_SNAKE_CASE_ ) for tokenizer in tokenizers: with self.subTest(F"{tokenizer.__class__.__name__}" ): UpperCamelCase__ = """你好,你是谁""" UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_tokens_to_shape_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_tokens_to_pronunciation_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.prepare_for_model( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase_ = { '''configuration_chinese_clip''': [ '''CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ChineseCLIPConfig''', '''ChineseCLIPOnnxConfig''', '''ChineseCLIPTextConfig''', '''ChineseCLIPVisionConfig''', ], '''processing_chinese_clip''': ['''ChineseCLIPProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''ChineseCLIPFeatureExtractor'''] lowerCamelCase_ = ['''ChineseCLIPImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ChineseCLIPModel''', '''ChineseCLIPPreTrainedModel''', '''ChineseCLIPTextModel''', '''ChineseCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
86
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
1
def __magic_name__ ( __a : int ): '''simple docstring''' if num <= 0: raise ValueError("""Input must be a positive integer""" ) UpperCamelCase__ = [True] * (num + 1) UpperCamelCase__ = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , __a ): UpperCamelCase__ = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase_ = int(input('''Enter a positive integer: ''').strip()) print(prime_sieve_eratosthenes(user_num))
86
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
1
import argparse import os 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_task_guides.py lowerCamelCase_ = '''src/transformers''' lowerCamelCase_ = '''docs/source/en/tasks''' def __magic_name__ ( __a : Dict , __a : List[str] , __a : Optional[int] ): '''simple docstring''' with open(__a , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: UpperCamelCase__ = f.readlines() # Find the start prompt. UpperCamelCase__ = 0 while not lines[start_index].startswith(__a ): start_index += 1 start_index += 1 UpperCamelCase__ = start_index while not lines[end_index].startswith(__a ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase_ = direct_transformers_import(TRANSFORMERS_PATH) lowerCamelCase_ = { '''asr.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, '''audio_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, '''language_modeling.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, '''image_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, '''masked_language_modeling.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, '''multiple_choice.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, '''object_detection.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, '''question_answering.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, '''semantic_segmentation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, '''sequence_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, '''summarization.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, '''token_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, '''translation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, '''video_classification.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, '''document_question_answering.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, '''monocular_depth_estimation.md''': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). lowerCamelCase_ = { '''summarization.md''': ('''nllb''',), '''translation.md''': ('''nllb''',), } def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = TASK_GUIDE_TO_MODELS[task_guide] UpperCamelCase__ = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(__a , set() ) UpperCamelCase__ = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([f"[{name}](../model_doc/{code})" for code, name in model_names.items()] ) + "\n" def __magic_name__ ( __a : Union[str, Any] , __a : Union[str, Any]=False ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = _find_text_in_file( filename=os.path.join(__a , __a ) , start_prompt="""<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->""" , end_prompt="""<!--End of the generated tip-->""" , ) UpperCamelCase__ = get_model_list_for_task(__a ) if current_list != new_list: if overwrite: with open(os.path.join(__a , __a ) , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( f"The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`" """ to fix this.""" ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCamelCase_ = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
86
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
1
def __magic_name__ ( __a : Union[str, Any] , __a : List[Any] ): '''simple docstring''' return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def __magic_name__ ( __a : Union[str, Any] , __a : Tuple=0 ): '''simple docstring''' return sorted(__a , key=lambda __a : x[column] ) def __magic_name__ ( __a : List[str] , __a : Optional[int] , __a : Dict=float("""inf""" ) ): '''simple docstring''' for i in range(points_counts - 1 ): for j in range(i + 1 , __a ): UpperCamelCase__ = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: UpperCamelCase__ = current_dis return min_dis def __magic_name__ ( __a : Dict , __a : Optional[int] , __a : Union[str, Any]=float("""inf""" ) ): '''simple docstring''' for i in range(min(6 , points_counts - 1 ) , __a ): for j in range(max(0 , i - 6 ) , __a ): UpperCamelCase__ = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: UpperCamelCase__ = current_dis return min_dis def __magic_name__ ( __a : Any , __a : Optional[int] , __a : Optional[int] ): '''simple docstring''' if points_counts <= 3: return dis_between_closest_pair(__a , __a ) # recursion UpperCamelCase__ = points_counts // 2 UpperCamelCase__ = closest_pair_of_points_sqr( __a , points_sorted_on_y[:mid] , __a ) UpperCamelCase__ = closest_pair_of_points_sqr( __a , points_sorted_on_y[mid:] , points_counts - mid ) UpperCamelCase__ = min(__a , __a ) UpperCamelCase__ = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(__a ) UpperCamelCase__ = dis_between_closest_in_strip( __a , len(__a ) , __a ) return min(__a , __a ) def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = column_based_sort(__a , column=0 ) UpperCamelCase__ = column_based_sort(__a , column=1 ) return ( closest_pair_of_points_sqr( __a , __a , __a ) ) ** 0.5 if __name__ == "__main__": lowerCamelCase_ = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print('''Distance:''', closest_pair_of_points(points, len(points)))
86
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
1
from collections.abc import Callable import numpy as np def __magic_name__ ( __a : Callable , __a : float , __a : float , __a : float , __a : float ): '''simple docstring''' UpperCamelCase__ = int(np.ceil((x_end - xa) / step_size ) ) UpperCamelCase__ = np.zeros((n + 1,) ) UpperCamelCase__ = ya UpperCamelCase__ = xa for k in range(__a ): UpperCamelCase__ = y[k] + step_size * ode_func(__a , y[k] ) UpperCamelCase__ = y[k] + ( (step_size / 2) * (ode_func(__a , y[k] ) + ode_func(x + step_size , __a )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
86
import os from datetime import datetime as dt from github import Github lowerCamelCase_ = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''enhancement''', '''new pipeline/model''', '''new scheduler''', '''wip''', ] def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Github(os.environ["""GITHUB_TOKEN"""] ) UpperCamelCase__ = g.get_repo("""huggingface/diffusers""" ) UpperCamelCase__ = repo.get_issues(state="""open""" ) for issue in open_issues: UpperCamelCase__ = sorted(issue.get_comments() , key=lambda __a : i.created_at , reverse=__a ) UpperCamelCase__ = comments[0] if len(__a ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
86
1
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ , UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
86
1
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} lowerCamelCase_ = { "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" }, } lowerCamelCase_ = {"allegro/herbert-base-cased": 5_14} lowerCamelCase_ = {} class __A( _lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ = PRETRAINED_INIT_CONFIGURATION SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ = HerbertTokenizer def __init__(self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="<s>" , SCREAMING_SNAKE_CASE_="<unk>" , SCREAMING_SNAKE_CASE_="<pad>" , SCREAMING_SNAKE_CASE_="<mask>" , SCREAMING_SNAKE_CASE_="</s>" , **SCREAMING_SNAKE_CASE_ , ): super().__init__( A__ , A__ , tokenizer_file=A__ , cls_token=A__ , unk_token=A__ , pad_token=A__ , mask_token=A__ , sep_token=A__ , **A__ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase__ = [self.cls_token_id] UpperCamelCase__ = [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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A__ , token_ids_a=A__ , already_has_special_tokens=A__ ) if token_ids_a is None: return [1] + ([0] * len(A__ )) + [1] return [1] + ([0] * len(A__ )) + [1] + ([0] * len(A__ )) + [1] def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase__ = [self.sep_token_id] UpperCamelCase__ = [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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ): UpperCamelCase__ = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
700
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
0
import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( _snake_case , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = LEDTokenizer SCREAMING_SNAKE_CASE__ = LEDTokenizerFast SCREAMING_SNAKE_CASE__ = True def UpperCAmelCase_ (self ): super().setUp() UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(lowerCAmelCase__ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowerCAmelCase__ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): return "lower newer", "lower newer" @cached_property def UpperCAmelCase_ (self ): return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def UpperCAmelCase_ (self ): return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] UpperCamelCase__ = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(lowerCAmelCase__ , max_length=len(lowerCAmelCase__ ) , padding=lowerCAmelCase__ , return_tensors="""pt""" ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) UpperCamelCase__ = batch.input_ids.tolist()[0] self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(lowerCAmelCase__ , padding=lowerCAmelCase__ , return_tensors="""pt""" ) self.assertIn("""input_ids""" , lowerCAmelCase__ ) self.assertIn("""attention_mask""" , lowerCAmelCase__ ) self.assertNotIn("""labels""" , lowerCAmelCase__ ) self.assertNotIn("""decoder_attention_mask""" , lowerCAmelCase__ ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(text_target=lowerCAmelCase__ , max_length=32 , padding="""max_length""" , return_tensors="""pt""" ) self.assertEqual(32 , targets["""input_ids"""].shape[1] ) @require_torch def UpperCAmelCase_ (self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer( ["""I am a small frog""" * 10_24, """I am a small frog"""] , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , return_tensors="""pt""" ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertEqual(batch.input_ids.shape , (2, 51_22) ) @require_torch def UpperCAmelCase_ (self ): UpperCamelCase__ = ["""A long paragraph for summarization."""] UpperCamelCase__ = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = tokenizer(lowerCAmelCase__ , return_tensors="""pt""" ) UpperCamelCase__ = tokenizer(text_target=lowerCAmelCase__ , return_tensors="""pt""" ) UpperCamelCase__ = inputs["""input_ids"""] UpperCamelCase__ = targets["""input_ids"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def UpperCAmelCase_ (self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: UpperCamelCase__ = ["""Summary of the text.""", """Another summary."""] UpperCamelCase__ = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] UpperCamelCase__ = tokenizer(lowerCAmelCase__ , padding=lowerCAmelCase__ ) UpperCamelCase__ = [[0] * len(lowerCAmelCase__ ) for x in encoded_output["""input_ids"""]] UpperCamelCase__ = tokenizer.pad(lowerCAmelCase__ ) self.assertSequenceEqual(outputs["""global_attention_mask"""] , lowerCAmelCase__ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ ) UpperCamelCase__ = tokenizer_p.encode_plus(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( lowerCAmelCase__ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( lowerCAmelCase__ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
701
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
0
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( snake_case__ ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""image_processor""", """tokenizer"""] SCREAMING_SNAKE_CASE__ = """BlipImageProcessor""" SCREAMING_SNAKE_CASE__ = ("""BertTokenizer""", """BertTokenizerFast""") def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = False super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) UpperCamelCase__ = self.image_processor def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): 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__ = self.tokenizer UpperCamelCase__ = self.tokenizer( text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , stride=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_overflowing_tokens=UpperCAmelCase_ , return_special_tokens_mask=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_length=UpperCAmelCase_ , verbose=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) return text_encoding # add pixel_values UpperCamelCase__ = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) if text is not None: UpperCamelCase__ = self.tokenizer( text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , stride=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_overflowing_tokens=UpperCAmelCase_ , return_special_tokens_mask=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_length=UpperCAmelCase_ , verbose=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) else: UpperCamelCase__ = None if text_encoding is not None: encoding_image_processor.update(UpperCAmelCase_ ) return encoding_image_processor def UpperCAmelCase_ (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) def UpperCAmelCase_ (self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) @property def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer.model_input_names UpperCamelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
702
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: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): 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=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.seq_length // 2 UpperCamelCase__ = 0 # first forward pass UpperCamelCase__ , UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase__ = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase__ = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) 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 , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 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.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase__ = tokenizer.eos_token UpperCamelCase__ = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase__ = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase__ = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase__ = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [ """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ (self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = """multi_label_classification""" UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = 4_23_84 UpperCamelCase__ = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase__ = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
0
from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar lowerCamelCase_ = TypeVar('''T''') class __A( Generic[T] ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = data UpperCamelCase__ = None def __str__(self ): return F"{self.data}" class __A( Generic[T] ): """simple docstring""" def __init__(self ): UpperCamelCase__ = None def __iter__(self ): UpperCamelCase__ = self.top while node: yield node.data UpperCamelCase__ = node.next def __str__(self ): return "->".join([str(A_ ) for item in self] ) def __len__(self ): return len(tuple(iter(self ) ) ) def UpperCAmelCase_ (self ): return self.top is None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = Node(A_ ) if not self.is_empty(): UpperCamelCase__ = self.top UpperCamelCase__ = node def UpperCAmelCase_ (self ): if self.is_empty(): raise IndexError("""pop from empty stack""" ) assert isinstance(self.top , A_ ) UpperCamelCase__ = self.top UpperCamelCase__ = self.top.next return pop_node.data def UpperCAmelCase_ (self ): if self.is_empty(): raise IndexError("""peek from empty stack""" ) assert self.top is not None return self.top.data def UpperCAmelCase_ (self ): UpperCamelCase__ = None if __name__ == "__main__": from doctest import testmod testmod()
703
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
0
import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger('''transformers.models.speecht5''') def __magic_name__ ( __a : str , __a : Any , __a : Tuple ): hf_model.apply_weight_norm() UpperCamelCase__ = checkpoint['input_conv.weight_g'] UpperCamelCase__ = checkpoint['input_conv.weight_v'] UpperCamelCase__ = checkpoint['input_conv.bias'] for i in range(len(config.upsample_rates ) ): UpperCamelCase__ = checkpoint[f"upsamples.{i}.1.weight_g"] UpperCamelCase__ = checkpoint[f"upsamples.{i}.1.weight_v"] UpperCamelCase__ = checkpoint[f"upsamples.{i}.1.bias"] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): UpperCamelCase__ = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_g"] UpperCamelCase__ = checkpoint[f"blocks.{i}.convs1.{j}.1.weight_v"] UpperCamelCase__ = checkpoint[f"blocks.{i}.convs1.{j}.1.bias"] UpperCamelCase__ = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_g"] UpperCamelCase__ = checkpoint[f"blocks.{i}.convs2.{j}.1.weight_v"] UpperCamelCase__ = checkpoint[f"blocks.{i}.convs2.{j}.1.bias"] UpperCamelCase__ = checkpoint['output_conv.1.weight_g'] UpperCamelCase__ = checkpoint['output_conv.1.weight_v'] UpperCamelCase__ = checkpoint['output_conv.1.bias'] hf_model.remove_weight_norm() @torch.no_grad() def __magic_name__ ( __a : Dict , __a : int , __a : List[Any] , __a : List[str]=None , __a : List[str]=None , ): if config_path is not None: UpperCamelCase__ = SpeechTaHifiGanConfig.from_pretrained(_lowercase ) else: UpperCamelCase__ = SpeechTaHifiGanConfig() UpperCamelCase__ = SpeechTaHifiGan(_lowercase ) UpperCamelCase__ = torch.load(_lowercase ) load_weights(orig_checkpoint["""model"""]["""generator"""] , _lowercase , _lowercase ) UpperCamelCase__ = np.load(_lowercase ) UpperCamelCase__ = stats[0].reshape(-1 ) UpperCamelCase__ = stats[1].reshape(-1 ) UpperCamelCase__ = torch.from_numpy(_lowercase ).float() UpperCamelCase__ = torch.from_numpy(_lowercase ).float() model.save_pretrained(_lowercase ) if repo_id: print("""Pushing to the hub...""" ) model.push_to_hub(_lowercase ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--stats_path''', required=True, default=None, type=str, help='''Path to stats.npy file''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) lowerCamelCase_ = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
704
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCamelCase_ = {"configuration_vit_mae": ["VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMAEConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ "VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMAEForPreTraining", "ViTMAELayer", "ViTMAEModel", "ViTMAEPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ "TFViTMAEForPreTraining", "TFViTMAEModel", "TFViTMAEPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
705
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 class __A( __lowerCamelCase , __lowerCamelCase ): """simple docstring""" @register_to_config def __init__(self , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = ("DownEncoderBlock2D",) , SCREAMING_SNAKE_CASE_ = ("UpDecoderBlock2D",) , SCREAMING_SNAKE_CASE_ = (64,) , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = "silu" , SCREAMING_SNAKE_CASE_ = 3 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 2_56 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 0.1_8215 , SCREAMING_SNAKE_CASE_ = "group" , ): super().__init__() # pass init params to Encoder UpperCamelCase__ = Encoder( in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , down_block_types=UpperCAmelCase_ , block_out_channels=UpperCAmelCase_ , layers_per_block=UpperCAmelCase_ , act_fn=UpperCAmelCase_ , norm_num_groups=UpperCAmelCase_ , double_z=UpperCAmelCase_ , ) UpperCamelCase__ = vq_embed_dim if vq_embed_dim is not None else latent_channels UpperCamelCase__ = nn.Convad(UpperCAmelCase_ , UpperCAmelCase_ , 1 ) UpperCamelCase__ = VectorQuantizer(UpperCAmelCase_ , UpperCAmelCase_ , beta=0.25 , remap=UpperCAmelCase_ , sane_index_shape=UpperCAmelCase_ ) UpperCamelCase__ = nn.Convad(UpperCAmelCase_ , UpperCAmelCase_ , 1 ) # pass init params to Decoder UpperCamelCase__ = Decoder( in_channels=UpperCAmelCase_ , out_channels=UpperCAmelCase_ , up_block_types=UpperCAmelCase_ , block_out_channels=UpperCAmelCase_ , layers_per_block=UpperCAmelCase_ , act_fn=UpperCAmelCase_ , norm_num_groups=UpperCAmelCase_ , norm_type=UpperCAmelCase_ , ) @apply_forward_hook def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True ): UpperCamelCase__ = self.encoder(UpperCAmelCase_ ) UpperCamelCase__ = self.quant_conv(UpperCAmelCase_ ) if not return_dict: return (h,) return VQEncoderOutput(latents=UpperCAmelCase_ ) @apply_forward_hook def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = True ): # also go through quantization layer if not force_not_quantize: UpperCamelCase__ = self.quantize(UpperCAmelCase_ ) else: UpperCamelCase__ = h UpperCamelCase__ = self.post_quant_conv(UpperCAmelCase_ ) UpperCamelCase__ = self.decoder(UpperCAmelCase_ , quant if self.config.norm_type == """spatial""" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=UpperCAmelCase_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = True ): UpperCamelCase__ = sample UpperCamelCase__ = self.encode(UpperCAmelCase_ ).latents UpperCamelCase__ = self.decode(UpperCAmelCase_ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=UpperCAmelCase_ )
706
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
0
import doctest from collections import deque import numpy as np class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = [2, 1, 2, -1] UpperCamelCase__ = [1, 2, 3, 4] def UpperCAmelCase_ (self ): UpperCamelCase__ = len(self.first_signal ) UpperCamelCase__ = len(self.second_signal ) UpperCamelCase__ = max(_lowercase , _lowercase ) # create a zero matrix of max_length x max_length UpperCamelCase__ = [[0] * max_length for i in range(_lowercase )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(_lowercase ): UpperCamelCase__ = deque(self.second_signal ) rotated_signal.rotate(_lowercase ) for j, item in enumerate(_lowercase ): matrix[i][j] += item # multiply the matrix with the first signal UpperCamelCase__ = np.matmul(np.transpose(_lowercase ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(_lowercase , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
707
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
0
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = ArgumentParser( description=( """PyTorch TPU distributed training launch """ """helper utility that will spawn up """ """multiple distributed processes""" ) ) # Optional arguments for the launch helper parser.add_argument("""--num_cores""" , type=__A , default=1 , help="""Number of TPU cores to use (1 or 8).""" ) # positional parser.add_argument( """training_script""" , type=__A , help=( """The full path to the single TPU training """ """program/script to be launched in parallel, """ """followed by all the arguments for the """ """training script""" ) , ) # rest from the training program parser.add_argument("""training_script_args""" , nargs=__A ) return parser.parse_args() def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = parse_args() # Import training_script as a module. UpperCamelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) UpperCamelCase__ = script_fpath.stem UpperCamelCase__ = importlib.import_module(__A ) # Patch sys.argv UpperCamelCase__ = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
708
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
0
import cva import numpy as np class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if k in (0.04, 0.06): UpperCamelCase__ = k UpperCamelCase__ = window_size else: raise ValueError("""invalid k value""" ) def __str__(self ): return str(self.k ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = cva.imread(_lowerCAmelCase , 0 ) UpperCamelCase__ , UpperCamelCase__ = img.shape UpperCamelCase__ = [] UpperCamelCase__ = img.copy() UpperCamelCase__ = cva.cvtColor(_lowerCAmelCase , cva.COLOR_GRAY2RGB ) UpperCamelCase__ , UpperCamelCase__ = np.gradient(_lowerCAmelCase ) UpperCamelCase__ = dx**2 UpperCamelCase__ = dy**2 UpperCamelCase__ = dx * dy UpperCamelCase__ = 0.04 UpperCamelCase__ = self.window_size // 2 for y in range(_lowerCAmelCase , h - offset ): for x in range(_lowerCAmelCase , w - offset ): UpperCamelCase__ = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() UpperCamelCase__ = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() UpperCamelCase__ = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() UpperCamelCase__ = (wxx * wyy) - (wxy**2) UpperCamelCase__ = wxx + wyy UpperCamelCase__ = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 2_55 ) return color_img, corner_list if __name__ == "__main__": lowerCamelCase_ = HarrisCorner(0.04, 3) lowerCamelCase_ = edge_detect.detect('''path_to_image''') cva.imwrite('''detect.png''', color_img)
709
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
0
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder lowerCamelCase_ = "__DUMMY_TRANSFORMERS_USER__" lowerCamelCase_ = "Dummy User" lowerCamelCase_ = "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" lowerCamelCase_ = "https://hub-ci.huggingface.co" lowerCamelCase_ = CI_HUB_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}" lowerCamelCase_ = CI_HUB_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}" lowerCamelCase_ = Path('''~/.huggingface/hub_ci_token''').expanduser() @pytest.fixture def __magic_name__ ( __a : Tuple ): monkeypatch.setattr( """huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE""" , lowerCamelCase__ ) @pytest.fixture def __magic_name__ ( __a : Union[str, Any] ): monkeypatch.setattr("""datasets.config.HF_ENDPOINT""" , lowerCamelCase__ ) monkeypatch.setattr("""datasets.config.HUB_DATASETS_URL""" , lowerCamelCase__ ) @pytest.fixture def __magic_name__ ( __a : int ): monkeypatch.setattr("""huggingface_hub.hf_api.HfFolder.path_token""" , lowerCamelCase__ ) @pytest.fixture def __magic_name__ ( __a : Union[str, Any] , __a : List[Any] ): HfFolder.save_token(lowerCamelCase__ ) yield HfFolder.delete_token() @pytest.fixture(scope="""session""" ) def __magic_name__ ( ): return HfApi(endpoint=lowerCamelCase__ ) @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Optional[Any] ): UpperCamelCase__ = HfFolder.get_token() HfFolder.save_token(lowerCamelCase__ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(lowerCamelCase__ ) @pytest.fixture def __magic_name__ ( __a : Optional[Any] ): def _cleanup_repo(__a : List[Any] ): hf_api.delete_repo(lowerCamelCase__ , token=lowerCamelCase__ , repo_type="""dataset""" ) return _cleanup_repo @pytest.fixture def __magic_name__ ( __a : Dict ): @contextmanager def _temporary_repo(__a : List[str] ): try: yield repo_id finally: cleanup_repo(lowerCamelCase__ ) return _temporary_repo @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Any , __a : Union[str, Any] , __a : Optional[int] ): UpperCamelCase__ = f"repo_txt_data-{int(time.time() * 1_0E3 )}" UpperCamelCase__ = f"{CI_HUB_USER}/{repo_name}" hf_api.create_repo(lowerCamelCase__ , token=lowerCamelCase__ , repo_type="""dataset""" , private=lowerCamelCase__ ) hf_api.upload_file( token=lowerCamelCase__ , path_or_fileobj=str(lowerCamelCase__ ) , path_in_repo="""data/text_data.txt""" , repo_id=lowerCamelCase__ , repo_type="""dataset""" , ) yield repo_id try: hf_api.delete_repo(lowerCamelCase__ , token=lowerCamelCase__ , repo_type="""dataset""" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __magic_name__ ( __a : Tuple , __a : Any , __a : Any ): return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Tuple , __a : Tuple , __a : List[str] ): UpperCamelCase__ = f"repo_zipped_txt_data-{int(time.time() * 1_0E3 )}" UpperCamelCase__ = f"{CI_HUB_USER}/{repo_name}" hf_api.create_repo(lowerCamelCase__ , token=lowerCamelCase__ , repo_type="""dataset""" , private=lowerCamelCase__ ) hf_api.upload_file( token=lowerCamelCase__ , path_or_fileobj=str(lowerCamelCase__ ) , path_in_repo="""data.zip""" , repo_id=lowerCamelCase__ , repo_type="""dataset""" , ) yield repo_id try: hf_api.delete_repo(lowerCamelCase__ , token=lowerCamelCase__ , repo_type="""dataset""" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __magic_name__ ( __a : List[str] , __a : Union[str, Any] , __a : Optional[Any] ): return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope="""session""" ) def __magic_name__ ( __a : Dict , __a : List[Any] , __a : Optional[int] ): UpperCamelCase__ = f"repo_zipped_img_data-{int(time.time() * 1_0E3 )}" UpperCamelCase__ = f"{CI_HUB_USER}/{repo_name}" hf_api.create_repo(lowerCamelCase__ , token=lowerCamelCase__ , repo_type="""dataset""" , private=lowerCamelCase__ ) hf_api.upload_file( token=lowerCamelCase__ , path_or_fileobj=str(lowerCamelCase__ ) , path_in_repo="""data.zip""" , repo_id=lowerCamelCase__ , repo_type="""dataset""" , ) yield repo_id try: hf_api.delete_repo(lowerCamelCase__ , token=lowerCamelCase__ , repo_type="""dataset""" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def __magic_name__ ( __a : Tuple , __a : List[Any] , __a : List[Any] ): return hf_private_dataset_repo_zipped_img_data_
710
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
0
import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def __magic_name__ ( __a : Optional[int] , __a : str , __a : str , __a : Path , __a : str = None , __a : str = None , __a : str = None , ): '''simple docstring''' if config_name_or_path is None: UpperCamelCase__ = "facebook/rag-token-base" if model_type == "rag_token" else "facebook/rag-sequence-base" if generator_tokenizer_name_or_path is None: UpperCamelCase__ = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: UpperCamelCase__ = question_encoder_name_or_path UpperCamelCase__ = RagTokenForGeneration if model_type == "rag_token" else RagSequenceForGeneration # Save model. UpperCamelCase__ = RagConfig.from_pretrained(_lowerCAmelCase ) UpperCamelCase__ = AutoConfig.from_pretrained(_lowerCAmelCase ) UpperCamelCase__ = AutoConfig.from_pretrained(_lowerCAmelCase ) UpperCamelCase__ = gen_config UpperCamelCase__ = question_encoder_config UpperCamelCase__ = model_class.from_pretrained_question_encoder_generator( _lowerCAmelCase , _lowerCAmelCase , config=_lowerCAmelCase ) rag_model.save_pretrained(_lowerCAmelCase ) # Sanity check. model_class.from_pretrained(_lowerCAmelCase ) # Save tokenizers. UpperCamelCase__ = AutoTokenizer.from_pretrained(_lowerCAmelCase ) gen_tokenizer.save_pretrained(dest_dir / """generator_tokenizer/""" ) UpperCamelCase__ = AutoTokenizer.from_pretrained(_lowerCAmelCase ) question_encoder_tokenizer.save_pretrained(dest_dir / """question_encoder_tokenizer/""" ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument( '''--model_type''', choices=['''rag_sequence''', '''rag_token'''], required=True, type=str, help='''RAG model type: rag_sequence, rag_token''', ) parser.add_argument('''--dest''', type=str, required=True, help='''Path to the output checkpoint directory.''') parser.add_argument('''--generator_name_or_path''', type=str, required=True, help='''Generator model identifier''') parser.add_argument( '''--question_encoder_name_or_path''', type=str, required=True, help='''Question encoder model identifier''' ) parser.add_argument( '''--generator_tokenizer_name_or_path''', type=str, help='''Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``''', ) parser.add_argument( '''--question_encoder_tokenizer_name_or_path''', type=str, help='''Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``''', ) parser.add_argument( '''--config_name_or_path''', type=str, help=( '''Identifier of the model config to use, if not provided, resolves to a base config for a given''' ''' ``model_type``''' ), ) lowerCamelCase_ = parser.parse_args() lowerCamelCase_ = Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
711
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
0
import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = LxmertTokenizer SCREAMING_SNAKE_CASE__ = LxmertTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True def UpperCAmelCase_ (self ): super().setUp() UpperCamelCase__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """UNwant\u00E9d,running""" UpperCamelCase__ = """unwanted, running""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file ) UpperCamelCase__ = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(_a , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_a ) , [7, 4, 5, 10, 8, 9] ) def UpperCAmelCase_ (self ): if not self.test_rust_tokenizer: return UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = self.get_rust_tokenizer() UpperCamelCase__ = """I was born in 92000, and this is falsé.""" UpperCamelCase__ = tokenizer.tokenize(_a ) UpperCamelCase__ = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) UpperCamelCase__ = tokenizer.encode(_a , add_special_tokens=_a ) UpperCamelCase__ = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) UpperCamelCase__ = self.get_rust_tokenizer() UpperCamelCase__ = tokenizer.encode(_a ) UpperCamelCase__ = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a )
712
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
0
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser lowerCamelCase_ = logging.getLogger(__name__) torch.set_grad_enabled(False) lowerCamelCase_ = '''cuda''' if torch.cuda.is_available() else '''cpu''' def __magic_name__ ( __a : int , __a : str=100 , __a : Union[str, Any]=" " ): '''simple docstring''' UpperCamelCase__ = text.split(__UpperCAmelCase ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(__UpperCAmelCase ) , __UpperCAmelCase )] def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = [], [] for title, text in zip(documents["""title"""] , documents["""text"""] ): if text is not None: for passage in split_text(__UpperCAmelCase ): titles.append(title if title is not None else """""" ) texts.append(__UpperCAmelCase ) return {"title": titles, "text": texts} def __magic_name__ ( __a : Union[str, Any] , __a : str , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ctx_tokenizer( documents["""title"""] , documents["""text"""] , truncation=__UpperCAmelCase , padding="""longest""" , return_tensors="""pt""" )["""input_ids"""] UpperCamelCase__ = ctx_encoder(input_ids.to(device=__UpperCAmelCase ) , return_dict=__UpperCAmelCase ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def __magic_name__ ( __a : str , __a : Any , __a : str , ): '''simple docstring''' logger.info("""Step 1 - Create the dataset""" ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way UpperCamelCase__ = load_dataset( """csv""" , data_files=[rag_example_args.csv_path] , split="""train""" , delimiter="""\t""" , column_names=["""title""", """text"""] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words UpperCamelCase__ = dataset.map(__UpperCAmelCase , batched=__UpperCAmelCase , num_proc=processing_args.num_proc ) # And compute the embeddings UpperCamelCase__ = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=__UpperCAmelCase ) UpperCamelCase__ = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) UpperCamelCase__ = Features( {"""text""": Value("""string""" ), """title""": Value("""string""" ), """embeddings""": Sequence(Value("""float32""" ) )} ) # optional, save as float32 instead of float64 to save space UpperCamelCase__ = dataset.map( partial(__UpperCAmelCase , ctx_encoder=__UpperCAmelCase , ctx_tokenizer=__UpperCAmelCase ) , batched=__UpperCAmelCase , batch_size=processing_args.batch_size , features=__UpperCAmelCase , ) # And finally save your dataset UpperCamelCase__ = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset""" ) dataset.save_to_disk(__UpperCAmelCase ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info("""Step 2 - Index the dataset""" ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search UpperCamelCase__ = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index("""embeddings""" , custom_index=__UpperCAmelCase ) # And save the index UpperCamelCase__ = os.path.join(rag_example_args.output_dir , """my_knowledge_dataset_hnsw_index.faiss""" ) dataset.get_index("""embeddings""" ).save(__UpperCAmelCase ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = field( default=str(Path(_snake_case ).parent / """test_run""" / """dummy-kb""" / """my_knowledge_dataset.csv""" ) , metadata={"""help""": """Path to a tab-separated csv file with columns \'title\' and \'text\'"""} , ) SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={"""help""": """Question that is passed as input to RAG. Default is \'What does Moses\' rod turn into ?\'."""} , ) SCREAMING_SNAKE_CASE__ = field( default="""facebook/rag-sequence-nq""" , metadata={"""help""": """The RAG model to use. Either \'facebook/rag-sequence-nq\' or \'facebook/rag-token-nq\'"""} , ) SCREAMING_SNAKE_CASE__ = field( default="""facebook/dpr-ctx_encoder-multiset-base""" , metadata={ """help""": ( """The DPR context encoder model to use. Either \'facebook/dpr-ctx_encoder-single-nq-base\' or""" """ \'facebook/dpr-ctx_encoder-multiset-base\'""" ) } , ) SCREAMING_SNAKE_CASE__ = field( default=str(Path(_snake_case ).parent / """test_run""" / """dummy-kb""" ) , metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""} , ) @dataclass class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = field( default=_snake_case , metadata={ """help""": """The number of processes to use to split the documents into passages. Default is single process.""" } , ) SCREAMING_SNAKE_CASE__ = field( default=16 , metadata={ """help""": """The batch size to use when computing the passages embeddings using the DPR context encoder.""" } , ) @dataclass class __A: """simple docstring""" SCREAMING_SNAKE_CASE__ = field( default=768 , metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""} , ) SCREAMING_SNAKE_CASE__ = field( default=128 , metadata={ """help""": ( """The number of bi-directional links created for every new element during the HNSW index construction.""" ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) lowerCamelCase_ = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: lowerCamelCase_ = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
713
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
0
lowerCamelCase_ = '''Input must be a string of 8 numbers plus letter''' lowerCamelCase_ = '''TRWAGMYFPDXBNJZSQVHLCKE''' def __magic_name__ ( __a : Optional[int] ): '''simple docstring''' if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): UpperCamelCase__ = f"Expected string as input, found {type(lowerCAmelCase__ ).__name__}" raise TypeError(lowerCAmelCase__ ) UpperCamelCase__ = spanish_id.replace("""-""" , """""" ).upper() if len(lowerCAmelCase__ ) != 9: raise ValueError(lowerCAmelCase__ ) try: UpperCamelCase__ = int(spanish_id_clean[0:8] ) UpperCamelCase__ = spanish_id_clean[8] except ValueError as ex: raise ValueError(lowerCAmelCase__ ) from ex if letter.isdigit(): raise ValueError(lowerCAmelCase__ ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
714
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __magic_name__ ( __a : Dict , __a : List[Any] ): '''simple docstring''' if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer UpperCamelCase__ = flax_key_tuple[:-1] + ("""weight""",) UpperCamelCase__ = torch.permute(__A , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(__A ): # linear layer UpperCamelCase__ = flax_key_tuple[:-1] + ("""weight""",) UpperCamelCase__ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: UpperCamelCase__ = flax_key_tuple[:-1] + ("""weight""",) return flax_key_tuple, flax_tensor def __magic_name__ ( __a : Tuple , __a : List[Any] , __a : Tuple ): '''simple docstring''' if "metadata" in layer: UpperCamelCase__ = layer.split("""metadata""" ) UpperCamelCase__ = """""".join(split_layer[0] )[:-1] UpperCamelCase__ = [tuple(("""metadata""" + split_layer[1]).split("""/""" ) )] elif "kvstore" in layer: UpperCamelCase__ = layer.split("""kvstore""" ) UpperCamelCase__ = """""".join(split_layer[0] )[:-1] UpperCamelCase__ = [tuple(("""kvstore""" + split_layer[1]).split("""/""" ) )] else: UpperCamelCase__ = layer.split("""/""" ) UpperCamelCase__ = """/""".join(split_layer[:-1] ) UpperCamelCase__ = (split_layer[-1],) if "kvstore/path" in layer: UpperCamelCase__ = f"{switch_checkpoint_path}/{checkpoint_info[layer]}" elif "kvstore/driver" in layer: UpperCamelCase__ = """file""" else: UpperCamelCase__ = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __magic_name__ ( __a : Union[str, Any] , __a : str ): '''simple docstring''' UpperCamelCase__ = rename_keys(__A ) UpperCamelCase__ = {} for k, v in current_block.items(): UpperCamelCase__ = v UpperCamelCase__ = new_current_block torch.save(__A , __A ) def __magic_name__ ( __a : int , __a : List[Any] , __a : Optional[Any] , __a : List[str] , __a : Optional[Any] = WEIGHTS_NAME ): '''simple docstring''' UpperCamelCase__ = convert_file_size_to_int(__A ) UpperCamelCase__ = [] UpperCamelCase__ = {} UpperCamelCase__ = 0 UpperCamelCase__ = 0 os.makedirs(__A , exist_ok=__A ) with gfile.GFile(switch_checkpoint_path + """/checkpoint""" , """rb""" ) as fp: UpperCamelCase__ = serialization.msgpack_restore(fp.read() )["""optimizer"""]["""target"""] UpperCamelCase__ = flatten_dict(__A , sep="""/""" ) UpperCamelCase__ = {} for layer in checkpoint_info.keys(): UpperCamelCase__ = get_key_and_tensorstore_dict( __A , __A , __A ) if curr_real_layer_name in all_layers: UpperCamelCase__ = content else: UpperCamelCase__ = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file UpperCamelCase__ = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() UpperCamelCase__ = torch.tensor(__A ) UpperCamelCase__ = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts UpperCamelCase__ = rename_base_flax_keys(tuple(key.split("""/""" ) ) , __A ) UpperCamelCase__ = """/""".join(__A ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: UpperCamelCase__ = os.path.join( __A , weights_name.replace(""".bin""" , f"-{len(__A )+1:05d}-of-???.bin" ) ) rename_and_save_block(__A , __A ) sharded_state_dicts.append(current_block.keys() ) del current_block UpperCamelCase__ = {} UpperCamelCase__ = 0 UpperCamelCase__ = raw_weights.to(getattr(__A , __A ) ) current_block_size += weight_size total_size += weight_size # Add the last block UpperCamelCase__ = os.path.join(__A , weights_name.replace(""".bin""" , f"-{len(__A )+1:05d}-of-???.bin" ) ) rename_and_save_block(__A , __A ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(__A ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index UpperCamelCase__ = {} UpperCamelCase__ = {} for idx, shard in enumerate(__A ): UpperCamelCase__ = weights_name.replace( """.bin""" , f"-{idx+1:05d}-of-{len(__A ):05d}.bin" ) # len(sharded_state_dicts):05d} UpperCamelCase__ = os.path.join(__A , weights_name.replace(""".bin""" , f"-{idx+1:05d}-of-???.bin" ) ) os.rename(__A , os.path.join(__A , __A ) ) UpperCamelCase__ = shard for key in shard: UpperCamelCase__ = shard_file # Add the metadata UpperCamelCase__ = {"""total_size""": total_size} UpperCamelCase__ = {"""metadata""": metadata, """weight_map""": weight_map} with open(os.path.join(__A , __A ) , """w""" , encoding="""utf-8""" ) as f: UpperCamelCase__ = json.dumps(__A , indent=2 , sort_keys=__A ) + """\n""" f.write(__A ) return metadata, index if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--switch_t5x_checkpoint_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600''', type=str, required=False, help='''Path to a directory containing a folder per layer. Follows the original Google format.''', ) parser.add_argument('''--max_shard_size''', default='''10GB''', required=False, help='''Max shard size''') parser.add_argument('''--dtype''', default='''bfloat16''', type=str, required=False, help='''dtype of the saved model''') parser.add_argument( '''--pytorch_dump_folder_path''', default='''/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted''', type=str, required=False, help='''Path to the output pytorch model.''', ) lowerCamelCase_ = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __magic_name__ ( ): '''simple docstring''' from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer UpperCamelCase__ = SwitchTransformersConfig.from_pretrained("""google/switch-base-8""" ) config.save_pretrained("""/home/arthur_huggingface_co/transformers/switch_converted""" ) UpperCamelCase__ = SwitchTransformersForConditionalGeneration.from_pretrained( """/home/arthur_huggingface_co/transformers/switch_converted""" , device_map="""auto""" ) UpperCamelCase__ = TaTokenizer.from_pretrained("""t5-small""" ) UpperCamelCase__ = """A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.""" UpperCamelCase__ = tokenizer(__A , return_tensors="""pt""" ).input_ids UpperCamelCase__ = model.generate(__A , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
715
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
716
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
0
import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase_ = logging.get_logger(__name__) def __magic_name__ ( __a : int , __a : Any , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = os.path.abspath(_lowerCamelCase ) logger.info(f"Converting TensorFlow checkpoint from {tf_path}" ) # Load weights from TF model UpperCamelCase__ = tf.train.list_variables(_lowerCamelCase ) UpperCamelCase__ = [] UpperCamelCase__ = [] UpperCamelCase__ = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") UpperCamelCase__ = full_name.split("""/""" ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(f"Skipping non-model layer {full_name}" ) continue if "optimizer" in full_name: logger.info(f"Skipping optimization layer {full_name}" ) continue if name[0] == "model": # ignore initial 'model' UpperCamelCase__ = name[1:] # figure out how many levels deep the name is UpperCamelCase__ = 0 for _name in name: if _name.startswith("""layer_with_weights""" ): depth += 1 else: break layer_depth.append(_lowerCamelCase ) # read data UpperCamelCase__ = tf.train.load_variable(_lowerCamelCase , _lowerCamelCase ) names.append("""/""".join(_lowerCamelCase ) ) arrays.append(_lowerCamelCase ) logger.info(f"Read a total of {len(_lowerCamelCase ):,} layers" ) # Sanity check if len(set(_lowerCamelCase ) ) != 1: raise ValueError(f"Found layer names with different depths (layer depth {list(set(_lowerCamelCase ) )})" ) UpperCamelCase__ = list(set(_lowerCamelCase ) )[0] if layer_depth != 1: raise ValueError( """The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP""" """ heads.""" ) # convert layers logger.info("""Converting weights...""" ) for full_name, array in zip(_lowerCamelCase , _lowerCamelCase ): UpperCamelCase__ = full_name.split("""/""" ) UpperCamelCase__ = model UpperCamelCase__ = [] for i, m_name in enumerate(_lowerCamelCase ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith("""layer_with_weights""" ): UpperCamelCase__ = int(m_name.split("""-""" )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(["""embeddings""", """LayerNorm"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """embeddings""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """LayerNorm""" ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(["""encoder""", """layer""", str(layer_num - 4 )] ) UpperCamelCase__ = getattr(_lowerCamelCase , """encoder""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """layer""" ) UpperCamelCase__ = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(["""pooler""", """dense"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """pooler""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """dense""" ) elif m_name == "embeddings": trace.append("""embeddings""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """embeddings""" ) if layer_num == 0: trace.append("""word_embeddings""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """word_embeddings""" ) elif layer_num == 1: trace.append("""position_embeddings""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """position_embeddings""" ) elif layer_num == 2: trace.append("""token_type_embeddings""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """token_type_embeddings""" ) else: raise ValueError(f"Unknown embedding layer with name {full_name}" ) trace.append("""weight""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """weight""" ) elif m_name == "_attention_layer": # self-attention layer trace.extend(["""attention""", """self"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """attention""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """self""" ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(["""attention""", """output""", """LayerNorm"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """attention""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """output""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """LayerNorm""" ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(["""attention""", """output""", """dense"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """attention""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """output""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """dense""" ) elif m_name == "_output_dense": # output dense trace.extend(["""output""", """dense"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """output""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """dense""" ) elif m_name == "_output_layer_norm": # output dense trace.extend(["""output""", """LayerNorm"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """output""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """LayerNorm""" ) elif m_name == "_key_dense": # attention key trace.append("""key""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """key""" ) elif m_name == "_query_dense": # attention query trace.append("""query""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """query""" ) elif m_name == "_value_dense": # attention value trace.append("""value""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """value""" ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(["""intermediate""", """dense"""] ) UpperCamelCase__ = getattr(_lowerCamelCase , """intermediate""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """dense""" ) elif m_name == "_output_layer_norm": # output layer norm trace.append("""output""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """output""" ) # weights & biases elif m_name in ["bias", "beta"]: trace.append("""bias""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """bias""" ) elif m_name in ["kernel", "gamma"]: trace.append("""weight""" ) UpperCamelCase__ = getattr(_lowerCamelCase , """weight""" ) else: logger.warning(f"Ignored {m_name}" ) # for certain layers reshape is necessary UpperCamelCase__ = ".".join(_lowerCamelCase ) if re.match(R"""(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)""" , _lowerCamelCase ) or re.match( R"""(\S+)\.attention\.output\.dense\.weight""" , _lowerCamelCase ): UpperCamelCase__ = array.reshape(pointer.data.shape ) if "kernel" in full_name: UpperCamelCase__ = array.transpose() if pointer.shape == array.shape: UpperCamelCase__ = torch.from_numpy(_lowerCamelCase ) else: raise ValueError( f"Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:" f" {array.shape}" ) logger.info(f"Successfully set variable {full_name} to PyTorch layer {trace}" ) return model def __magic_name__ ( __a : List[Any] , __a : List[str] , __a : str ): '''simple docstring''' logger.info(f"Loading model based on config from {config_path}..." ) UpperCamelCase__ = BertConfig.from_json_file(_lowerCamelCase ) UpperCamelCase__ = BertModel(_lowerCamelCase ) # Load weights from checkpoint logger.info(f"Loading weights from checkpoint {tf_checkpoint_path}..." ) load_tfa_weights_in_bert(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # Save pytorch-model logger.info(f"Saving PyTorch model to {pytorch_dump_path}..." ) torch.save(model.state_dict() , _lowerCamelCase ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument( '''--tf_checkpoint_path''', type=str, required=True, help='''Path to the TensorFlow 2.x checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', type=str, required=True, help='''The config json file corresponding to the BERT model. This specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', type=str, required=True, help='''Path to the output PyTorch model (must include filename).''', ) lowerCamelCase_ = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
717
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
0
import logging from transformers.configuration_utils import PretrainedConfig lowerCamelCase_ = logging.getLogger(__name__) class __A( _UpperCAmelCase ): SCREAMING_SNAKE_CASE__ = """masked_bert""" def __init__(self , SCREAMING_SNAKE_CASE_=3_05_22 , SCREAMING_SNAKE_CASE_=7_68 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=30_72 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1E-12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="topK" , SCREAMING_SNAKE_CASE_="constant" , SCREAMING_SNAKE_CASE_=0.0 , **SCREAMING_SNAKE_CASE_ , ): super().__init__(pad_token_id=lowerCamelCase_ , **lowerCamelCase_ ) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = pruning_method UpperCamelCase__ = mask_init UpperCamelCase__ = mask_scale
718
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
0
import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device lowerCamelCase_ = False class __A( unittest.TestCase ): """simple docstring""" pass @slow @require_torch_gpu class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion""" ) pipe.to(__UpperCamelCase ) pipe.set_progress_bar_config(disable=__UpperCamelCase ) UpperCamelCase__ = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg""" ) UpperCamelCase__ = torch.manual_seed(0 ) UpperCamelCase__ = pipe( image=__UpperCamelCase , generator=__UpperCamelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" , ).images UpperCamelCase__ = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCamelCase__ = np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
719
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = XLMRobertaModel.from_pretrained("""xlm-roberta-base""" ) UpperCamelCase__ = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] ) # The dog is cute and lives in the garden house UpperCamelCase__ = torch.Size((1, 12, 7_68) ) # batch_size, sequence_length, embedding_vector_dim UpperCamelCase__ = torch.tensor( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): UpperCamelCase__ = model(snake_case_ )["""last_hidden_state"""].detach() self.assertEqual(output.shape , snake_case_ ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , snake_case_ , atol=1E-3 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = XLMRobertaModel.from_pretrained("""xlm-roberta-large""" ) UpperCamelCase__ = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] ) # The dog is cute and lives in the garden house UpperCamelCase__ = torch.Size((1, 12, 10_24) ) # batch_size, sequence_length, embedding_vector_dim UpperCamelCase__ = torch.tensor( [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): UpperCamelCase__ = model(snake_case_ )["""last_hidden_state"""].detach() self.assertEqual(output.shape , snake_case_ ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , snake_case_ , atol=1E-3 ) )
720
import os from datetime import datetime as dt from github import Github lowerCamelCase_ = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''enhancement''', '''new pipeline/model''', '''new scheduler''', '''wip''', ] def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Github(os.environ["""GITHUB_TOKEN"""] ) UpperCamelCase__ = g.get_repo("""huggingface/diffusers""" ) UpperCamelCase__ = repo.get_issues(state="""open""" ) for issue in open_issues: UpperCamelCase__ = sorted(issue.get_comments() , key=lambda __a : i.created_at , reverse=__a ) UpperCamelCase__ = comments[0] if len(__a ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="""closed""" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="""open""" ) issue.remove_from_labels("""stale""" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( """This issue has been automatically marked as stale because it has not had """ """recent activity. If you think this still needs to be addressed """ """please comment on this thread.\n\nPlease note that issues that do not follow the """ """[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) """ """are likely to be ignored.""" ) issue.add_to_labels("""stale""" ) if __name__ == "__main__": main()
86
0
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = FlaxMTaForConditionalGeneration.from_pretrained("""google/mt5-small""" ) UpperCamelCase__ = AutoTokenizer.from_pretrained("""google/mt5-small""" ) UpperCamelCase__ = tokenizer("""Hello there""" , return_tensors="""np""" ).input_ids UpperCamelCase__ = tokenizer("""Hi I am""" , return_tensors="""np""" ).input_ids UpperCamelCase__ = shift_tokens_right(_lowercase , model.config.pad_token_id , model.config.decoder_start_token_id ) UpperCamelCase__ = model(_lowercase , decoder_input_ids=_lowercase ).logits UpperCamelCase__ = optax.softmax_cross_entropy(_lowercase , onehot(_lowercase , logits.shape[-1] ) ).mean() UpperCamelCase__ = -(labels.shape[-1] * loss.item()) UpperCamelCase__ = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
721
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = image.size UpperCamelCase__ , UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if isinstance(SCREAMING_SNAKE_CASE_ , PIL.Image.Image ): UpperCamelCase__ = preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = image.to(device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(SCREAMING_SNAKE_CASE_ ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = torch.clamp(SCREAMING_SNAKE_CASE_ , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
86
0
'''simple docstring''' from jiwer import compute_measures import datasets lowerCamelCase_ = '''\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ''' lowerCamelCase_ = '''\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. ''' lowerCamelCase_ = ''' Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = ["this is the prediction", "there is an other sample"] >>> references = ["this is the reference", "there is another one"] >>> wer = datasets.load_metric("wer") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/jitsi/jiwer/"""] , reference_urls=[ """https://en.wikipedia.org/wiki/Word_error_rate""", ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=False ): if concatenate_texts: return compute_measures(A_ , A_ )["wer"] else: UpperCamelCase__ = 0 UpperCamelCase__ = 0 for prediction, reference in zip(A_ , A_ ): UpperCamelCase__ = compute_measures(A_ , A_ ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
700
def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' UpperCamelCase__ = len(__a ) UpperCamelCase__ = len(__a ) UpperCamelCase__ = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase__ = True for i in range(__a ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase__ = True if a[i].islower(): UpperCamelCase__ = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
86
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase_ = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
701
from __future__ import annotations lowerCamelCase_ = '''#''' class __A: """simple docstring""" def __init__(self ): UpperCamelCase__ = {} def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in text: if char not in trie: UpperCamelCase__ = {} UpperCamelCase__ = trie[char] UpperCamelCase__ = True def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self._trie for char in prefix: if char in trie: UpperCamelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [] for c, v in d.items(): UpperCamelCase__ = [""" """] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE_ )] result.extend(SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = Trie() lowerCamelCase_ = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = trie.find_word(__a ) return tuple(string + word for word in suffixes ) def __magic_name__ ( ): '''simple docstring''' print(autocomplete_using_trie("""de""" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
86
0
from __future__ import annotations def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' if partitions <= 0: raise ValueError("""partitions must be a positive number!""" ) if partitions > number_of_bytes: raise ValueError("""partitions can not > number_of_bytes!""" ) UpperCamelCase__ = number_of_bytes // partitions UpperCamelCase__ = [] for i in range(__a ): UpperCamelCase__ = i * bytes_per_partition + 1 UpperCamelCase__ = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f"{start_bytes}-{end_bytes}" ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
702
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: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5_12 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_input_mask UpperCamelCase__ = use_token_type_ids UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_act UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_size UpperCamelCase__ = type_sequence_label_size UpperCamelCase__ = initializer_range UpperCamelCase__ = num_labels UpperCamelCase__ = num_choices UpperCamelCase__ = scope def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_input_mask: UpperCamelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase__ = None if self.use_token_type_ids: UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ (self ): 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=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = BioGptForCausalLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() # create attention mask UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.seq_length // 2 UpperCamelCase__ = 0 # first forward pass UpperCamelCase__ , UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCamelCase__ = ids_tensor((1,) , SCREAMING_SNAKE_CASE_ ).item() + 1 UpperCamelCase__ = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCamelCase__ = random_other_next_tokens # append to next input_ids and attn_mask UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ )] , dim=1 , ) # get two different outputs UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase__ = torch.ones(input_ids.shape , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # first forward pass UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCamelCase__ = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )["""last_hidden_state"""] UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ )[ """last_hidden_state""" ] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase__ = BioGptForCausalLM(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) 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 , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = BioGptModel(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 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.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = BioGptForTokenClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() ( ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ( UpperCamelCase__ ) , ) = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = (BioGptForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptModelTester(self ) UpperCamelCase__ = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCamelCase__ = type self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*SCREAMING_SNAKE_CASE_ , gradient_checkpointing=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = """left""" # Define PAD Token = EOS Token = 50256 UpperCamelCase__ = tokenizer.eos_token UpperCamelCase__ = model.config.eos_token_id # use different length sentences to test batching UpperCamelCase__ = [ """Hello, my dog is a little""", """Today, I""", ] UpperCamelCase__ = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs["""input_ids"""].to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( input_ids=SCREAMING_SNAKE_CASE_ , attention_mask=inputs["""attention_mask"""].to(SCREAMING_SNAKE_CASE_ ) , ) UpperCamelCase__ = tokenizer(sentences[0] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = inputs_non_padded.shape[-1] - inputs["""attention_mask"""][-1].long().sum().cpu().item() UpperCamelCase__ = tokenizer(sentences[1] , return_tensors="""pt""" ).input_ids.to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate(input_ids=SCREAMING_SNAKE_CASE_ , max_length=model.config.max_length - num_paddings ) UpperCamelCase__ = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_non_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.decode(output_padded[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [ """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ (self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = BioGptModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ (self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase__ = 3 UpperCamelCase__ = """multi_label_classification""" UpperCamelCase__ = input_dict["""input_ids"""] UpperCamelCase__ = input_ids.ne(1 ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCamelCase__ = BioGptForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __A( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCamelCase__ = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase__ = 4_23_84 UpperCamelCase__ = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) UpperCamelCase__ = BioGptForCausalLM.from_pretrained("""microsoft/biogpt""" ) model.to(SCREAMING_SNAKE_CASE_ ) torch.manual_seed(0 ) UpperCamelCase__ = tokenizer("""COVID-19 is""" , return_tensors="""pt""" ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = model.generate( **SCREAMING_SNAKE_CASE_ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase__ = tokenizer.decode(output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """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(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
86
0
import math def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' if 0 not in (x, y): # We use the relation x^y = y*log10(x), where 10 is the base. return y * math.logaa(snake_case_ ) else: if x == 0: # 0 raised to any number is 0 return 0 elif y == 0: return 1 # any number raised to 0 is 1 raise AssertionError("""This should never happen""" ) if __name__ == "__main__": # Main function # Read two numbers from input and typecast them to int using map function. # Here x is the base and y is the power. lowerCamelCase_ = """Enter the base and the power separated by a comma: """ lowerCamelCase_ = map(int, input(prompt).split(''',''')) lowerCamelCase_ = map(int, input(prompt).split(''',''')) # We find the log of each number, using the function res(), which takes two # arguments. lowerCamelCase_ = res(xa, ya) lowerCamelCase_ = res(xa, ya) # We check for the largest number if resa > resa: print('''Largest number is''', xa, '''^''', ya) elif resa > resa: print('''Largest number is''', xa, '''^''', ya) else: print('''Both are equal''')
703
from PIL import Image def __magic_name__ ( __a : Image , __a : float ): '''simple docstring''' def brightness(__a : int ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("""level must be between -255.0 (black) and 255.0 (white)""" ) return img.point(__a ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change brightness to 100 lowerCamelCase_ = change_brightness(img, 1_00) brigt_img.save('''image_data/lena_brightness.png''', format='''png''')
86
0
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
704
lowerCamelCase_ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10_00_00)] def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution lowerCamelCase_ = [None] * 10_00_00_00 lowerCamelCase_ = True lowerCamelCase_ = False def __magic_name__ ( __a : int ): '''simple docstring''' if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore UpperCamelCase__ = chain(next_number(__a ) ) UpperCamelCase__ = number_chain while number < 10_000_000: UpperCamelCase__ = number_chain number *= 10 return number_chain def __magic_name__ ( __a : int = 10_000_000 ): '''simple docstring''' for i in range(1 , __a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__a ) if __name__ == "__main__": import doctest doctest.testmod() print(f'{solution() = }')
86
0
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = image.size UpperCamelCase__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 UpperCamelCase__ = image.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) UpperCamelCase__ = np.array(__a ).astype(np.floataa ) / 255.0 UpperCamelCase__ = image[None].transpose(0 , 3 , 1 , 2 ) UpperCamelCase__ = torch.from_numpy(__a ) return 2.0 * image - 1.0 class __A( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules(vqvae=_a , unet=_a , scheduler=_a ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_00 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , ): if isinstance(_a , PIL.Image.Image ): UpperCamelCase__ = 1 elif isinstance(_a , torch.Tensor ): UpperCamelCase__ = image.shape[0] else: raise ValueError(F"`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_a )}" ) if isinstance(_a , PIL.Image.Image ): UpperCamelCase__ = preprocess(_a ) UpperCamelCase__ = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image UpperCamelCase__ = (batch_size, self.unet.config.in_channels // 2, height, width) UpperCamelCase__ = next(self.unet.parameters() ).dtype UpperCamelCase__ = randn_tensor(_a , generator=_a , device=self.device , dtype=_a ) UpperCamelCase__ = image.to(device=self.device , dtype=_a ) # set timesteps and move to the correct device self.scheduler.set_timesteps(_a , device=self.device ) UpperCamelCase__ = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for t in self.progress_bar(_a ): # concat latents and low resolution image in the channel dimension. UpperCamelCase__ = torch.cat([latents, image] , dim=1 ) UpperCamelCase__ = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual UpperCamelCase__ = self.unet(_a , _a ).sample # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # decode the image latents with the VQVAE UpperCamelCase__ = self.vqvae.decode(_a ).sample UpperCamelCase__ = torch.clamp(_a , -1.0 , 1.0 ) UpperCamelCase__ = image / 2 + 0.5 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
705
import argparse import hashlib import os import urllib import warnings import torch from torch import nn from tqdm import tqdm from transformers import WhisperConfig, WhisperForConditionalGeneration lowerCamelCase_ = { '''tiny.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt''', '''tiny''': '''https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt''', '''base.en''': '''https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt''', '''base''': '''https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt''', '''small.en''': '''https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt''', '''small''': '''https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt''', '''medium.en''': '''https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt''', '''medium''': '''https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt''', '''large''': '''https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large.pt''', '''large-v2''': '''https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt''', } def __magic_name__ ( __a : List[str] ): '''simple docstring''' UpperCamelCase__ = ["""layers""", """blocks"""] for k in ignore_keys: state_dict.pop(__a , __a ) lowerCamelCase_ = { '''blocks''': '''layers''', '''mlp.0''': '''fc1''', '''mlp.2''': '''fc2''', '''mlp_ln''': '''final_layer_norm''', '''.attn.query''': '''.self_attn.q_proj''', '''.attn.key''': '''.self_attn.k_proj''', '''.attn.value''': '''.self_attn.v_proj''', '''.attn_ln''': '''.self_attn_layer_norm''', '''.attn.out''': '''.self_attn.out_proj''', '''.cross_attn.query''': '''.encoder_attn.q_proj''', '''.cross_attn.key''': '''.encoder_attn.k_proj''', '''.cross_attn.value''': '''.encoder_attn.v_proj''', '''.cross_attn_ln''': '''.encoder_attn_layer_norm''', '''.cross_attn.out''': '''.encoder_attn.out_proj''', '''decoder.ln.''': '''decoder.layer_norm.''', '''encoder.ln.''': '''encoder.layer_norm.''', '''token_embedding''': '''embed_tokens''', '''encoder.positional_embedding''': '''encoder.embed_positions.weight''', '''decoder.positional_embedding''': '''decoder.embed_positions.weight''', '''ln_post''': '''layer_norm''', } def __magic_name__ ( __a : Dict ): '''simple docstring''' UpperCamelCase__ = list(s_dict.keys() ) for key in keys: UpperCamelCase__ = key for k, v in WHISPER_MAPPING.items(): if k in key: UpperCamelCase__ = new_key.replace(__a , __a ) print(f"{key} -> {new_key}" ) UpperCamelCase__ = s_dict.pop(__a ) return s_dict def __magic_name__ ( __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ , UpperCamelCase__ = emb.weight.shape UpperCamelCase__ = nn.Linear(__a , __a , bias=__a ) UpperCamelCase__ = emb.weight.data return lin_layer def __magic_name__ ( __a : str , __a : str ): '''simple docstring''' os.makedirs(__a , exist_ok=__a ) UpperCamelCase__ = os.path.basename(__a ) UpperCamelCase__ = url.split("""/""" )[-2] UpperCamelCase__ = os.path.join(__a , __a ) if os.path.exists(__a ) and not os.path.isfile(__a ): raise RuntimeError(f"{download_target} exists and is not a regular file" ) if os.path.isfile(__a ): UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() == expected_shaaaa: return model_bytes else: warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(__a ) as source, open(__a , """wb""" ) as output: with tqdm( total=int(source.info().get("""Content-Length""" ) ) , ncols=80 , unit="""iB""" , unit_scale=__a , unit_divisor=1_024 ) as loop: while True: UpperCamelCase__ = source.read(8_192 ) if not buffer: break output.write(__a ) loop.update(len(__a ) ) UpperCamelCase__ = open(__a , """rb""" ).read() if hashlib.shaaaa(__a ).hexdigest() != expected_shaaaa: raise RuntimeError( """Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model.""" ) return model_bytes def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] ): '''simple docstring''' if ".pt" not in checkpoint_path: UpperCamelCase__ = _download(_MODELS[checkpoint_path] ) else: UpperCamelCase__ = torch.load(__a , map_location="""cpu""" ) UpperCamelCase__ = original_checkpoint["""dims"""] UpperCamelCase__ = original_checkpoint["""model_state_dict"""] UpperCamelCase__ = state_dict["""decoder.token_embedding.weight"""] remove_ignore_keys_(__a ) rename_keys(__a ) UpperCamelCase__ = True UpperCamelCase__ = state_dict["""decoder.layers.0.fc1.weight"""].shape[0] UpperCamelCase__ = WhisperConfig( vocab_size=dimensions["""n_vocab"""] , encoder_ffn_dim=__a , decoder_ffn_dim=__a , num_mel_bins=dimensions["""n_mels"""] , d_model=dimensions["""n_audio_state"""] , max_target_positions=dimensions["""n_text_ctx"""] , encoder_layers=dimensions["""n_audio_layer"""] , encoder_attention_heads=dimensions["""n_audio_head"""] , decoder_layers=dimensions["""n_text_layer"""] , decoder_attention_heads=dimensions["""n_text_state"""] , max_source_positions=dimensions["""n_audio_ctx"""] , ) UpperCamelCase__ = WhisperForConditionalGeneration(__a ) UpperCamelCase__ , UpperCamelCase__ = model.model.load_state_dict(__a , strict=__a ) if len(__a ) > 0 and not set(__a ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" f" but all the following weights are missing {missing}" ) if tie_embeds: UpperCamelCase__ = make_linear_from_emb(model.model.decoder.embed_tokens ) else: UpperCamelCase__ = proj_out_weights model.save_pretrained(__a ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() # # Required parameters parser.add_argument('''--checkpoint_path''', type=str, help='''Patht to the downloaded checkpoints''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCamelCase_ = parser.parse_args() convert_openai_whisper_to_tfms(args.checkpoint_path, args.pytorch_dump_folder_path)
86
0
import pprint import requests lowerCamelCase_ = '''https://zenquotes.io/api''' def __magic_name__ ( ): '''simple docstring''' return requests.get(API_ENDPOINT_URL + """/today""" ).json() def __magic_name__ ( ): '''simple docstring''' return requests.get(API_ENDPOINT_URL + """/random""" ).json() if __name__ == "__main__": lowerCamelCase_ = random_quotes() pprint.pprint(response)
706
def __magic_name__ ( __a : int ): '''simple docstring''' UpperCamelCase__ = [[0 for _ in range(__a )] for _ in range(m + 1 )] for i in range(m + 1 ): UpperCamelCase__ = 1 for n in range(m + 1 ): for k in range(1 , __a ): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: lowerCamelCase_ = int(input('''Enter a number: ''').strip()) print(partition(n)) except ValueError: print('''Please enter a number.''') else: try: lowerCamelCase_ = int(sys.argv[1]) print(partition(n)) except ValueError: print('''Please pass a number.''')
86
0
def __magic_name__ ( __a : Optional[int] = 50_000_000 ): '''simple docstring''' UpperCamelCase__ = set() UpperCamelCase__ = int((limit - 24) ** (1 / 2) ) UpperCamelCase__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __snake_case ) ) ) for primea in primes: UpperCamelCase__ = primea * primea for primea in primes: UpperCamelCase__ = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: UpperCamelCase__ = primea * primea * primea * primea UpperCamelCase__ = square + cube + tetr if total >= limit: break ret.add(__snake_case ) return len(__snake_case ) if __name__ == "__main__": print(f'{solution() = }')
707
class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = graph self._normalize_graph(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = None def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if sources is int: UpperCamelCase__ = [sources] if sinks is int: UpperCamelCase__ = [sinks] if len(SCREAMING_SNAKE_CASE_ ) == 0 or len(SCREAMING_SNAKE_CASE_ ) == 0: return UpperCamelCase__ = sources[0] UpperCamelCase__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(SCREAMING_SNAKE_CASE_ ) > 1 or len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: UpperCamelCase__ = max_input_flow UpperCamelCase__ = 0 UpperCamelCase__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: UpperCamelCase__ = max_input_flow UpperCamelCase__ = size - 1 def UpperCAmelCase_ (self ): if self.maximum_flow_algorithm is None: raise Exception("""You need to set maximum flow algorithm before.""" ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = algorithm(self ) class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = flow_network UpperCamelCase__ = flow_network.verticesCount UpperCamelCase__ = flow_network.sourceIndex UpperCamelCase__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that UpperCamelCase__ = flow_network.graph UpperCamelCase__ = False def UpperCAmelCase_ (self ): if not self.executed: self._algorithm() UpperCamelCase__ = True def UpperCAmelCase_ (self ): pass class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) # use this to save your result UpperCamelCase__ = -1 def UpperCAmelCase_ (self ): if not self.executed: raise Exception("""You should execute algorithm before using its result!""" ) return self.maximum_flow class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ ): super().__init__(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = [[0] * self.verticies_count for i in range(self.verticies_count )] UpperCamelCase__ = [0] * self.verticies_count UpperCamelCase__ = [0] * self.verticies_count def UpperCAmelCase_ (self ): UpperCamelCase__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule UpperCamelCase__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list UpperCamelCase__ = 0 while i < len(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = vertices_list[i] UpperCamelCase__ = self.heights[vertex_index] self.process_vertex(SCREAMING_SNAKE_CASE_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase__ = 0 else: i += 1 UpperCamelCase__ = sum(self.preflow[self.source_index] ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.relabel(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): UpperCamelCase__ = self.heights[to_index] if min_height is not None: UpperCamelCase__ = min_height + 1 if __name__ == "__main__": lowerCamelCase_ = [0] lowerCamelCase_ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCamelCase_ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCamelCase_ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCamelCase_ = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
86
0
import colorsys from PIL import Image # type: ignore def __magic_name__ ( __a : float , __a : float , __a : int ): '''simple docstring''' UpperCamelCase__ = x UpperCamelCase__ = y for step in range(UpperCAmelCase__ ): # noqa: B007 UpperCamelCase__ = a * a - b * b + x UpperCamelCase__ = 2 * a * b + y UpperCamelCase__ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def __magic_name__ ( __a : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def __magic_name__ ( __a : float ): '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(UpperCAmelCase__ , 1 , 1 ) ) def __magic_name__ ( __a : int = 800 , __a : int = 600 , __a : float = -0.6 , __a : float = 0 , __a : float = 3.2 , __a : int = 50 , __a : bool = True , ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (image_width, image_height) ) UpperCamelCase__ = img.load() # loop through the image-coordinates for image_x in range(UpperCAmelCase__ ): for image_y in range(UpperCAmelCase__ ): # determine the figure-coordinates based on the image-coordinates UpperCamelCase__ = figure_width / image_width * image_height UpperCamelCase__ = figure_center_x + (image_x / image_width - 0.5) * figure_width UpperCamelCase__ = figure_center_y + (image_y / image_height - 0.5) * figure_height UpperCamelCase__ = get_distance(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: UpperCamelCase__ = get_color_coded_rgb(UpperCAmelCase__ ) else: UpperCamelCase__ = get_black_and_white_rgb(UpperCAmelCase__ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure lowerCamelCase_ = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
708
from timeit import timeit def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: number &= number - 1 result += 1 return result def __magic_name__ ( __a : int ): '''simple docstring''' if number < 0: raise ValueError("""the value of input must not be negative""" ) UpperCamelCase__ = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __magic_name__ ( ): '''simple docstring''' def do_benchmark(__a : int ) -> None: UpperCamelCase__ = """import __main__ as z""" print(f"Benchmark when {number = }:" ) print(f"{get_set_bits_count_using_modulo_operator(__a ) = }" ) UpperCamelCase__ = timeit("""z.get_set_bits_count_using_modulo_operator(25)""" , setup=__a ) print(f"timeit() runs in {timing} seconds" ) print(f"{get_set_bits_count_using_brian_kernighans_algorithm(__a ) = }" ) UpperCamelCase__ = timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" , setup=__a , ) print(f"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(__a ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
86
0
import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = inspect.getfile(accelerate.test_utils ) UpperCamelCase__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """external_deps""", """test_metrics.py"""] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 UpperCamelCase__ = test_metrics @require_cpu def UpperCAmelCase_ (self ): debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def UpperCAmelCase_ (self ): debug_launcher(self.test_metrics.main ) @require_single_gpu def UpperCAmelCase_ (self ): self.test_metrics.main() @require_multi_gpu def UpperCAmelCase_ (self ): print(F"Found {torch.cuda.device_count()} devices." ) UpperCamelCase__ = ["torchrun", F"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(lowerCAmelCase__ , env=os.environ.copy() )
709
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class __A( __lowerCamelCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] ) , type=pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""bool""" ) , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=Value("""int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([1, 2, 3] , try_type=Value("""int32""" ) ) ) self.assertEqual(arr.type , pa.intaa() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=Value("""int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , type=ArrayaD((1, 3) , """int64""" ) ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence([[[1, 2, 3]]] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , ArrayaDExtensionType((1, 3) , """int64""" ) ) def UpperCAmelCase_ (self ): UpperCamelCase__ = pa.array(TypedSequence(["""foo""", """bar"""] , try_type=ArrayaD((1, 3) , """int64""" ) ) ) self.assertEqual(arr.type , pa.string() ) @require_pil def UpperCAmelCase_ (self ): import PIL.Image UpperCamelCase__ = PIL.Image.fromarray(np.arange(10 , dtype=np.uinta ).reshape(2 , 5 ) ) with patch( """datasets.arrow_writer.cast_to_python_objects""" , side_effect=SCREAMING_SNAKE_CASE_ ) as mock_cast_to_python_objects: UpperCamelCase__ = pa.array(TypedSequence([{"""path""": None, """bytes""": b"""image_bytes"""}, pil_image] , type=Image() ) ) UpperCamelCase__ , UpperCamelCase__ = mock_cast_to_python_objects.call_args_list[-1] self.assertIn("""optimize_list_casting""" , SCREAMING_SNAKE_CASE_ ) self.assertFalse(kwargs["""optimize_list_casting"""] ) def __magic_name__ ( __a : List[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferReader(__a ) if isinstance(__a , pa.Buffer ) else pa.memory_map(__a ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Tuple , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""] )} ) with ArrowWriter(stream=__a , features=__a ) as writer: writer.write({"""labels""": 0} ) writer.write({"""labels""": 1} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pa.ipc.open_stream(__a ) UpperCamelCase__ = f.read_all() UpperCamelCase__ = pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(__a ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=[1, 2] ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: with pytest.raises(__a ): writer.write({"""col_1""": """foo""", """col_2""": 1} , key=10 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=10 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() @pytest.mark.parametrize("""writer_batch_size""" , [None, 2, 10] ) def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter( stream=__a , writer_batch_size=__a , hash_salt="""split_name""" , check_duplicates=__a , ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} , key=1 ) writer.write({"""col_1""": """bar""", """col_2""": 2} , key=2 ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : List[Any] , __a : Optional[int] ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) writer.write_batch({"""col_1""": [], """col_2""": []} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Union[str, Any] , __a : Any ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize("""writer_batch_size""" , [None, 1, 10] ) @pytest.mark.parametrize( """fields""" , [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}] ) def __magic_name__ ( __a : Optional[Any] , __a : int ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() UpperCamelCase__ = pa.schema(__a ) if fields else None with ArrowWriter(stream=__a , schema=__a , writer_batch_size=__a ) as writer: writer.write_row(pa.Table.from_pydict({"""col_1""": ["""foo"""], """col_2""": [1]} ) ) writer.write_row(pa.Table.from_pydict({"""col_1""": ["""bar"""], """col_2""": [2]} ) ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(output.getvalue() , expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def __magic_name__ ( ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase__ = {"""col_1""": pa.string(), """col_2""": pa.intaa()} UpperCamelCase__ = os.path.join(__a , """test.arrow""" ) with ArrowWriter(path=__a , schema=pa.schema(__a ) ) as writer: writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(__a , metadata=writer._schema.metadata ) _check_output(__a , 1 ) def __magic_name__ ( __a : Any ): '''simple docstring''' if pa.types.is_list(__a ): return get_base_dtype(arr_type.value_type ) else: return arr_type def __magic_name__ ( __a : Optional[int] , __a : Any ): '''simple docstring''' if isinstance(lst[0] , __a ): change_first_primitive_element_in_list(lst[0] , __a ) else: UpperCamelCase__ = value @pytest.mark.parametrize("""optimized_int_type, expected_dtype""" , [(None, pa.intaa()), (Value("""int32""" ), pa.intaa())] ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Union[str, Any] , __a : Optional[int] , __a : Tuple ): '''simple docstring''' UpperCamelCase__ = pa.array(TypedSequence(__a , optimized_int_type=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( """col, expected_dtype""" , [ ("""attention_mask""", pa.inta()), ("""special_tokens_mask""", pa.inta()), ("""token_type_ids""", pa.inta()), ("""input_ids""", pa.intaa()), ("""other""", pa.intaa()), ] , ) @pytest.mark.parametrize("""sequence""" , [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def __magic_name__ ( __a : Optional[int] , __a : str , __a : Optional[Any] ): '''simple docstring''' UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications UpperCamelCase__ = copy.deepcopy(__a ) UpperCamelCase__ = np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(__a , __a ) UpperCamelCase__ = pa.array(OptimizedTypedSequence(__a , col=__a ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize("""raise_exception""" , [False, True] ) def __magic_name__ ( __a : List[str] , __a : List[str] ): '''simple docstring''' UpperCamelCase__ = str(tmp_path / """dataset-train.arrow""" ) try: with ArrowWriter(path=__a ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def __magic_name__ ( __a : Tuple ): '''simple docstring''' UpperCamelCase__ = """mock://dataset-train.arrow""" with ArrowWriter(path=__a , storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs , type(__a ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(__a ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter(stream=__a ) as writer: writer.write({"""col_1""": """foo""", """col_2""": 1} ) writer.write({"""col_1""": """bar""", """col_2""": 2} ) UpperCamelCase__ , UpperCamelCase__ = writer.finalize() assert num_examples == 2 assert num_bytes > 0 UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize("""embed_local_files""" , [False, True] ) def __magic_name__ ( __a : str , __a : Any ): '''simple docstring''' import PIL.Image UpperCamelCase__ = str(tmp_path / """test_image_rgb.jpg""" ) PIL.Image.fromarray(np.zeros((5, 5) , dtype=np.uinta ) ).save(__a , format="""png""" ) UpperCamelCase__ = pa.BufferOutputStream() with ParquetWriter( stream=__a , features=Features({"""image""": Image()} ) , embed_local_files=__a ) as writer: writer.write({"""image""": image_path} ) writer.finalize() UpperCamelCase__ = pa.BufferReader(output.getvalue() ) UpperCamelCase__ = pq.read_table(__a ) UpperCamelCase__ = pa_table.to_pydict() if embed_local_files: assert isinstance(out["""image"""][0]["""path"""] , __a ) with open(__a , """rb""" ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = pa.schema([pa.field("""col_1""" , pa.string() , nullable=__a )] ) UpperCamelCase__ = pa.BufferOutputStream() with ArrowWriter(stream=__a ) as writer: writer._build_writer(inferred_schema=__a ) assert writer._schema == pa.schema([pa.field("""col_1""" , pa.string() )] )
86
0
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def __magic_name__ ( ): UpperCamelCase__ = ArgumentParser("""Accelerate CLI tool""" , usage="""accelerate <command> [<args>]""" , allow_abbrev=UpperCAmelCase__ ) UpperCamelCase__ = parser.add_subparsers(help="""accelerate command helpers""" ) # Register commands get_config_parser(subparsers=UpperCAmelCase__ ) env_command_parser(subparsers=UpperCAmelCase__ ) launch_command_parser(subparsers=UpperCAmelCase__ ) tpu_command_parser(subparsers=UpperCAmelCase__ ) test_command_parser(subparsers=UpperCAmelCase__ ) # Let's go UpperCamelCase__ = parser.parse_args() if not hasattr(UpperCAmelCase__ , """func""" ): parser.print_help() exit(1 ) # Run args.func(UpperCAmelCase__ ) if __name__ == "__main__": main()
710
from sklearn.metrics import matthews_corrcoef import datasets lowerCamelCase_ = ''' Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] ''' lowerCamelCase_ = ''' Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results[\'matthews_correlation\'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric("matthews_correlation") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results[\'matthews_correlation\'], 2)) -0.25 ''' lowerCamelCase_ = '''\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ (self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): return { "matthews_correlation": float(matthews_corrcoef(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , sample_weight=SCREAMING_SNAKE_CASE_ ) ), }
86
0
import inspect import unittest from transformers import MobileViTVaConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __A( __UpperCAmelCase ): """simple docstring""" def UpperCAmelCase_ ( self ): UpperCamelCase__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , """width_multiplier""" ) ) class __A: """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_="swish" , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=0.25 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_size UpperCamelCase__ = num_channels UpperCamelCase__ = make_divisible(5_12 * width_multiplier , divisor=8 ) UpperCamelCase__ = hidden_act UpperCamelCase__ = conv_kernel_size UpperCamelCase__ = output_stride UpperCamelCase__ = classifier_dropout_prob UpperCamelCase__ = use_labels UpperCamelCase__ = is_training UpperCamelCase__ = num_labels UpperCamelCase__ = initializer_range UpperCamelCase__ = scope UpperCamelCase__ = width_multiplier UpperCamelCase__ = ffn_dropout UpperCamelCase__ = attn_dropout def UpperCAmelCase_ ( self ): UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase__ = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCAmelCase_ ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCAmelCase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = MobileViTVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model(UpperCAmelCase_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCAmelCase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = MobileViTVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = MobileViTVaForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase__ = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) UpperCamelCase__ = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCAmelCase_ ( self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ = ( { """feature-extraction""": MobileViTVaModel, """image-classification""": MobileViTVaForImageClassification, """image-segmentation""": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ ( self ): UpperCamelCase__ = MobileViTVaModelTester(self ) UpperCamelCase__ = MobileViTVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason="""MobileViTV2 does not output attentions""" ) def UpperCAmelCase_ ( self ): pass @require_torch_multi_gpu @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run.""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(UpperCAmelCase_ ) UpperCamelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def UpperCAmelCase_ ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def UpperCAmelCase_ ( self ): def check_hidden_states_output(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): UpperCamelCase__ = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) UpperCamelCase__ = outputs.hidden_states UpperCamelCase__ = 5 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. UpperCamelCase__ = 2 for i in range(len(UpperCAmelCase_ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def UpperCAmelCase_ ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def UpperCAmelCase_ ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def UpperCAmelCase_ ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = MobileViTVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase_ ( self ): return ( MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self ): UpperCamelCase__ = MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256""" ).to( UpperCAmelCase_ ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(**UpperCAmelCase_ ) # verify the logits UpperCamelCase__ = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) UpperCamelCase__ = torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self ): UpperCamelCase__ = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) UpperCamelCase__ = model.to(UpperCAmelCase_ ) UpperCamelCase__ = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(**UpperCAmelCase_ ) UpperCamelCase__ = outputs.logits # verify the logits UpperCamelCase__ = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) UpperCamelCase__ = torch.tensor( [ [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]], [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]], [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self ): UpperCamelCase__ = MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) UpperCamelCase__ = model.to(UpperCAmelCase_ ) UpperCamelCase__ = MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3""" ) UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=UpperCAmelCase_ , return_tensors="""pt""" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): UpperCamelCase__ = model(**UpperCAmelCase_ ) UpperCamelCase__ = outputs.logits.detach().cpu() UpperCamelCase__ = image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_ , target_sizes=[(50, 60)] ) UpperCamelCase__ = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , UpperCAmelCase_ ) UpperCamelCase__ = image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_ ) UpperCamelCase__ = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , UpperCAmelCase_ )
711
def __magic_name__ ( __a : str ): '''simple docstring''' return credit_card_number.startswith(("""34""", """35""", """37""", """4""", """5""", """6""") ) def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = credit_card_number UpperCamelCase__ = 0 UpperCamelCase__ = len(__a ) - 2 for i in range(__a , -1 , -2 ): # double the value of every second digit UpperCamelCase__ = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 UpperCamelCase__ = cc_number[:i] + str(__a ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__a ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def __magic_name__ ( __a : str ): '''simple docstring''' UpperCamelCase__ = f"{credit_card_number} is an invalid credit card number because" if not credit_card_number.isdigit(): print(f"{error_message} it has nonnumerical characters." ) return False if not 13 <= len(__a ) <= 16: print(f"{error_message} of its length." ) return False if not validate_initial_digits(__a ): print(f"{error_message} of its first two digits." ) return False if not luhn_validation(__a ): print(f"{error_message} it fails the Luhn check." ) return False print(f"{credit_card_number} is a valid credit card number." ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('''4111111111111111''') validate_credit_card_number('''32323''')
86
0
import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __A( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = DebertaTokenizer SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = DebertaTokenizerFast def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] UpperCamelCase__ = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) ) UpperCamelCase__ = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] UpperCamelCase__ = {'''unk_token''': '''[UNK]'''} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(UpperCamelCase__ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(UpperCamelCase__ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = '''lower newer''' UpperCamelCase__ = '''lower newer''' return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = '''lower newer''' UpperCamelCase__ = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] UpperCamelCase__ = tokenizer.tokenize(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , UpperCamelCase__ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = tokenizer("""Hello""" , """World""" ) UpperCamelCase__ = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd["""token_type_ids"""] , UpperCamelCase__ ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""microsoft/deberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=UpperCamelCase__ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=UpperCamelCase__ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(UpperCamelCase__ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(UpperCamelCase__ , UpperCamelCase__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: UpperCamelCase__ = tokenizer_class.from_pretrained("""microsoft/deberta-base""" ) UpperCamelCase__ = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] UpperCamelCase__ = tokenizer(UpperCamelCase__ , padding=UpperCamelCase__ ) UpperCamelCase__ = [tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ ) for seq in encoding['''input_ids''']] # fmt: off UpperCamelCase__ = { '''input_ids''': [ [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on UpperCamelCase__ = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , UpperCamelCase__ ) for expected, decoded in zip(UpperCamelCase__ , UpperCamelCase__ ): self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
712
def __magic_name__ ( __a : int = 50 ): '''simple docstring''' UpperCamelCase__ = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f'{solution() = }')
86
0
import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, 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.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class __A: """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=30 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = decoder_seq_length # For common tests UpperCamelCase__ = self.decoder_seq_length UpperCamelCase__ = is_training UpperCamelCase__ = use_attention_mask UpperCamelCase__ = use_labels UpperCamelCase__ = vocab_size UpperCamelCase__ = d_model UpperCamelCase__ = d_model UpperCamelCase__ = decoder_layers UpperCamelCase__ = decoder_layers UpperCamelCase__ = decoder_ffn_dim UpperCamelCase__ = decoder_attention_heads UpperCamelCase__ = decoder_attention_heads UpperCamelCase__ = eos_token_id UpperCamelCase__ = bos_token_id UpperCamelCase__ = pad_token_id UpperCamelCase__ = decoder_start_token_id UpperCamelCase__ = use_cache UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = None UpperCamelCase__ = decoder_seq_length UpperCamelCase__ = 2 UpperCamelCase__ = 1 def UpperCAmelCase_ (self ): UpperCamelCase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) UpperCamelCase__ = None if self.use_attention_mask: UpperCamelCase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) UpperCamelCase__ = None if self.use_labels: UpperCamelCase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) UpperCamelCase__ = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): UpperCamelCase__ = True UpperCamelCase__ = TrOCRDecoder(config=_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ).eval() UpperCamelCase__ = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass UpperCamelCase__ = model(_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE ) UpperCamelCase__ = model(_SCREAMING_SNAKE_CASE ) UpperCamelCase__ = model(_SCREAMING_SNAKE_CASE , use_cache=_SCREAMING_SNAKE_CASE ) self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) ) self.parent.assertTrue(len(_SCREAMING_SNAKE_CASE ) == len(_SCREAMING_SNAKE_CASE ) + 1 ) UpperCamelCase__ = outputs["""past_key_values"""] # create hypothetical next token and extent to next_input_ids UpperCamelCase__ = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and UpperCamelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCamelCase__ = model(_SCREAMING_SNAKE_CASE )["""last_hidden_state"""] UpperCamelCase__ = model(_SCREAMING_SNAKE_CASE , past_key_values=_SCREAMING_SNAKE_CASE )["""last_hidden_state"""] # select random slice UpperCamelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCamelCase__ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() UpperCamelCase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1E-3 ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_torch class __A( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = (TrOCRForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False def UpperCAmelCase_ (self ): UpperCamelCase__ = TrOCRStandaloneDecoderModelTester(self , is_training=_SCREAMING_SNAKE_CASE ) UpperCamelCase__ = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): self.config_tester.run_common_tests() def UpperCAmelCase_ (self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*_SCREAMING_SNAKE_CASE ) def UpperCAmelCase_ (self ): return @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def UpperCAmelCase_ (self ): pass
713
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A( __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = RobertaTokenizer SCREAMING_SNAKE_CASE__ = RobertaTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = {"""cls_token""": """<s>"""} def UpperCAmelCase_ (self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt UpperCamelCase__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] UpperCamelCase__ = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] UpperCamelCase__ = {"""unk_token""": """<unk>"""} UpperCamelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCamelCase__ = 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(SCREAMING_SNAKE_CASE_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , **SCREAMING_SNAKE_CASE_ ): kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = """lower newer""" UpperCamelCase__ = """lower newer""" return input_text, output_text def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCamelCase__ = """lower newer""" UpperCamelCase__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] UpperCamelCase__ = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) # , add_prefix_space=True) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokens + [tokenizer.unk_token] UpperCamelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) , [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2] , ) @slow def UpperCAmelCase_ (self ): UpperCamelCase__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) UpperCamelCase__ = tokenizer.encode("""sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def UpperCAmelCase_ (self ): UpperCamelCase__ = self.get_tokenizer() UpperCamelCase__ = """Encode this sequence.""" UpperCamelCase__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Testing spaces after special tokens UpperCamelCase__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ )} ) # mask token has a left space UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """Encode <mask> sequence""" UpperCamelCase__ = """Encode <mask>sequence""" UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.encode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = encoded.index(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): pass def UpperCAmelCase_ (self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = """A, <mask> AllenNLP sentence.""" UpperCamelCase__ = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) UpperCamelCase__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) UpperCamelCase__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE_ , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def UpperCAmelCase_ (self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) UpperCamelCase__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""add_prefix_space"""] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(post_processor_state["""trim_offsets"""] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` UpperCamelCase__ = F"{text_of_1_token} {text_of_1_token}" UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ) + 1, len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(SCREAMING_SNAKE_CASE_ ), len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = F" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ) + 1, 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , ) UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained( SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_r(SCREAMING_SNAKE_CASE_ , return_offsets_mapping=SCREAMING_SNAKE_CASE_ , add_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(SCREAMING_SNAKE_CASE_ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(SCREAMING_SNAKE_CASE_ ), 1 + len(SCREAMING_SNAKE_CASE_ ) + 1 + len(SCREAMING_SNAKE_CASE_ )) , )
86
0
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def __magic_name__ ( __a : Tuple ): '''simple docstring''' def wrapper(*__a : str , **__a : Any ): UpperCamelCase__ = timeit.default_timer() UpperCamelCase__ = func(*__a , **__a ) UpperCamelCase__ = timeit.default_timer() - starttime return delta UpperCamelCase__ = func.__name__ return wrapper def __magic_name__ ( __a : str , __a : int=100 , __a : Any=None ): '''simple docstring''' UpperCamelCase__ = [] UpperCamelCase__ = seq_shapes or {} for i in range(__a ): UpperCamelCase__ = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(__a , _ArrayXD ): UpperCamelCase__ = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(__a , datasets.Value ): if v.dtype == "string": UpperCamelCase__ = """The small grey turtle was surprisingly fast when challenged.""" else: UpperCamelCase__ = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(__a , datasets.Sequence ): while isinstance(__a , datasets.Sequence ): UpperCamelCase__ = v.feature UpperCamelCase__ = seq_shapes[k] UpperCamelCase__ = np.random.rand(*__a ).astype(v.dtype ) UpperCamelCase__ = data dummy_data.append((i, example) ) return dummy_data def __magic_name__ ( __a : List[Any] , __a : List[Any] , __a : List[Any]=100 , __a : List[Any]=None ): '''simple docstring''' UpperCamelCase__ = generate_examples(__a , num_examples=__a , seq_shapes=__a ) with ArrowWriter(features=__a , path=__a ) as writer: for key, record in dummy_data: UpperCamelCase__ = features.encode_example(__a ) writer.write(__a ) UpperCamelCase__ = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f"Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}." ) UpperCamelCase__ = datasets.Dataset.from_file(filename=__a , info=datasets.DatasetInfo(features=__a ) ) return dataset
714
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed lowerCamelCase_ = { '''distilbert''': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), '''roberta''': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), '''bert''': (BertConfig, BertForMaskedLM, BertTokenizer), '''gpt2''': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def __magic_name__ ( __a : Any ): '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def __magic_name__ ( __a : List[Any] , __a : Any ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False elif args.student_type == "gpt2": UpperCamelCase__ = False def __magic_name__ ( __a : int , __a : Dict ): '''simple docstring''' if args.student_type == "roberta": UpperCamelCase__ = False def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = argparse.ArgumentParser(description="""Training""" ) parser.add_argument("""--force""" , action="""store_true""" , help="""Overwrite dump_path if it already exists.""" ) parser.add_argument( """--dump_path""" , type=__a , required=__a , help="""The output directory (log, checkpoints, parameters, etc.)""" ) parser.add_argument( """--data_file""" , type=__a , required=__a , help="""The binarized file (tokenized + tokens_to_ids) and grouped by sequence.""" , ) parser.add_argument( """--student_type""" , type=__a , choices=["""distilbert""", """roberta""", """gpt2"""] , required=__a , help="""The student type (DistilBERT, RoBERTa).""" , ) parser.add_argument("""--student_config""" , type=__a , required=__a , help="""Path to the student configuration.""" ) parser.add_argument( """--student_pretrained_weights""" , default=__a , type=__a , help="""Load student initialization checkpoint.""" ) parser.add_argument( """--teacher_type""" , choices=["""bert""", """roberta""", """gpt2"""] , required=__a , help="""Teacher type (BERT, RoBERTa).""" ) parser.add_argument("""--teacher_name""" , type=__a , required=__a , help="""The teacher model.""" ) parser.add_argument("""--temperature""" , default=2.0 , type=__a , help="""Temperature for the softmax temperature.""" ) parser.add_argument( """--alpha_ce""" , default=0.5 , type=__a , help="""Linear weight for the distillation loss. Must be >=0.""" ) parser.add_argument( """--alpha_mlm""" , default=0.0 , type=__a , help="""Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.""" , ) parser.add_argument("""--alpha_clm""" , default=0.5 , type=__a , help="""Linear weight for the CLM loss. Must be >=0.""" ) parser.add_argument("""--alpha_mse""" , default=0.0 , type=__a , help="""Linear weight of the MSE loss. Must be >=0.""" ) parser.add_argument( """--alpha_cos""" , default=0.0 , type=__a , help="""Linear weight of the cosine embedding loss. Must be >=0.""" ) parser.add_argument( """--mlm""" , action="""store_true""" , help="""The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.""" ) parser.add_argument( """--mlm_mask_prop""" , default=0.15 , type=__a , help="""Proportion of tokens for which we need to make a prediction.""" , ) parser.add_argument("""--word_mask""" , default=0.8 , type=__a , help="""Proportion of tokens to mask out.""" ) parser.add_argument("""--word_keep""" , default=0.1 , type=__a , help="""Proportion of tokens to keep.""" ) parser.add_argument("""--word_rand""" , default=0.1 , type=__a , help="""Proportion of tokens to randomly replace.""" ) parser.add_argument( """--mlm_smoothing""" , default=0.7 , type=__a , help="""Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).""" , ) parser.add_argument("""--token_counts""" , type=__a , help="""The token counts in the data_file for MLM.""" ) parser.add_argument( """--restrict_ce_to_mask""" , action="""store_true""" , help="""If true, compute the distillation loss only the [MLM] prediction distribution.""" , ) parser.add_argument( """--freeze_pos_embs""" , action="""store_true""" , help="""Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only.""" , ) parser.add_argument( """--freeze_token_type_embds""" , action="""store_true""" , help="""Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.""" , ) parser.add_argument("""--n_epoch""" , type=__a , default=3 , help="""Number of pass on the whole dataset.""" ) parser.add_argument("""--batch_size""" , type=__a , default=5 , help="""Batch size (for each process).""" ) parser.add_argument( """--group_by_size""" , action="""store_false""" , help="""If true, group sequences that have similar length into the same batch. Default is true.""" , ) parser.add_argument( """--gradient_accumulation_steps""" , type=__a , default=50 , help="""Gradient accumulation for larger training batches.""" , ) parser.add_argument("""--warmup_prop""" , default=0.05 , type=__a , help="""Linear warmup proportion.""" ) parser.add_argument("""--weight_decay""" , default=0.0 , type=__a , help="""Weight decay if we apply some.""" ) parser.add_argument("""--learning_rate""" , default=5E-4 , type=__a , help="""The initial learning rate for Adam.""" ) parser.add_argument("""--adam_epsilon""" , default=1E-6 , type=__a , help="""Epsilon for Adam optimizer.""" ) parser.add_argument("""--max_grad_norm""" , default=5.0 , type=__a , help="""Max gradient norm.""" ) parser.add_argument("""--initializer_range""" , default=0.02 , type=__a , help="""Random initialization range.""" ) parser.add_argument( """--fp16""" , action="""store_true""" , help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" , ) parser.add_argument( """--fp16_opt_level""" , type=__a , default="""O1""" , help=( """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].""" """See details at https://nvidia.github.io/apex/amp.html""" ) , ) parser.add_argument("""--n_gpu""" , type=__a , default=1 , help="""Number of GPUs in the node.""" ) parser.add_argument("""--local_rank""" , type=__a , default=-1 , help="""Distributed training - Local rank""" ) parser.add_argument("""--seed""" , type=__a , default=56 , help="""Random seed""" ) parser.add_argument("""--log_interval""" , type=__a , default=500 , help="""Tensorboard logging interval.""" ) parser.add_argument("""--checkpoint_interval""" , type=__a , default=4_000 , help="""Checkpoint interval.""" ) UpperCamelCase__ = parser.parse_args() sanity_checks(__a ) # ARGS # init_gpu_params(__a ) set_seed(__a ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" """ itUse `--force` if you want to overwrite it""" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"Experiment will be dumped and logged in {args.dump_path}" ) # SAVE PARAMS # logger.info(f"Param: {args}" ) with open(os.path.join(args.dump_path , """parameters.json""" ) , """w""" ) as f: json.dump(vars(__a ) , __a , indent=4 ) git_log(args.dump_path ) UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.student_type] UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCamelCase__ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCamelCase__ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCamelCase__ = tokenizer.all_special_tokens.index(__a ) UpperCamelCase__ = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}" ) UpperCamelCase__ = special_tok_ids UpperCamelCase__ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}" ) with open(args.data_file , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)" ) with open(args.token_counts , """rb""" ) as fp: UpperCamelCase__ = pickle.load(__a ) UpperCamelCase__ = np.maximum(__a , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCamelCase__ = 0.0 # do not predict special tokens UpperCamelCase__ = torch.from_numpy(__a ) else: UpperCamelCase__ = None UpperCamelCase__ = LmSeqsDataset(params=__a , data=__a ) logger.info("""Data loader created.""" ) # STUDENT # logger.info(f"Loading student config from {args.student_config}" ) UpperCamelCase__ = student_config_class.from_pretrained(args.student_config ) UpperCamelCase__ = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}" ) UpperCamelCase__ = student_model_class.from_pretrained(args.student_pretrained_weights , config=__a ) else: UpperCamelCase__ = student_model_class(__a ) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}" ) logger.info("""Student loaded.""" ) # TEACHER # UpperCamelCase__ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=__a ) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}" ) logger.info(f"Teacher loaded from {args.teacher_name}." ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(__a , __a ) if args.freeze_token_type_embds: freeze_token_type_embeddings(__a , __a ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCamelCase__ = Distiller( params=__a , dataset=__a , token_probs=__a , student=__a , teacher=__a ) distiller.train() logger.info("""Let's go get some drinks.""" ) if __name__ == "__main__": main()
86
0
def __magic_name__ ( __a : Any ): '''simple docstring''' UpperCamelCase__ = 0 while len(SCREAMING_SNAKE_CASE_ ) > 1: UpperCamelCase__ = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): UpperCamelCase__ = files.index(min(SCREAMING_SNAKE_CASE_ ) ) temp += files[min_index] files.pop(SCREAMING_SNAKE_CASE_ ) files.append(SCREAMING_SNAKE_CASE_ ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
715
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
86
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A( __snake_case , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = KandinskyVaaPipeline SCREAMING_SNAKE_CASE__ = [ 'image_embeds', 'negative_image_embeds', ] SCREAMING_SNAKE_CASE__ = ['image_embeds', 'negative_image_embeds'] SCREAMING_SNAKE_CASE__ = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] SCREAMING_SNAKE_CASE__ = False @property def UpperCAmelCase_ (self ): return 32 @property def UpperCAmelCase_ (self ): return 32 @property def UpperCAmelCase_ (self ): return self.time_input_dim @property def UpperCAmelCase_ (self ): return self.time_input_dim * 4 @property def UpperCAmelCase_ (self ): return 1_00 @property def UpperCAmelCase_ (self ): torch.manual_seed(0 ) UpperCamelCase__ = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } UpperCamelCase__ = UNetaDConditionModel(**A_ ) return model @property def UpperCAmelCase_ (self ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCAmelCase_ (self ): torch.manual_seed(0 ) UpperCamelCase__ = VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase_ (self ): UpperCamelCase__ = self.dummy_unet UpperCamelCase__ = self.dummy_movq UpperCamelCase__ = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule="""linear""" , beta_start=0.0_0085 , beta_end=0.012 , clip_sample=A_ , set_alpha_to_one=A_ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=A_ , ) UpperCamelCase__ = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ): UpperCamelCase__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(A_ ) ).to(A_ ) UpperCamelCase__ = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( A_ ) if str(A_ ).startswith("""mps""" ): UpperCamelCase__ = torch.manual_seed(A_ ) else: UpperCamelCase__ = torch.Generator(device=A_ ).manual_seed(A_ ) UpperCamelCase__ = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def UpperCAmelCase_ (self ): UpperCamelCase__ = "cpu" UpperCamelCase__ = self.get_dummy_components() UpperCamelCase__ = self.pipeline_class(**A_ ) UpperCamelCase__ = pipe.to(A_ ) pipe.set_progress_bar_config(disable=A_ ) UpperCamelCase__ = pipe(**self.get_dummy_inputs(A_ ) ) UpperCamelCase__ = output.images UpperCamelCase__ = pipe( **self.get_dummy_inputs(A_ ) , return_dict=A_ , )[0] UpperCamelCase__ = image[0, -3:, -3:, -1] UpperCamelCase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCamelCase__ = np.array( [0.623_7976, 1.0, 0.3644_1332, 1.0, 0.7063_9634, 0.2987_7186, 0.8565_2125, 0.521_6843, 0.5445_4046] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ (self ): UpperCamelCase__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy""" ) UpperCamelCase__ = KandinskyVaaPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(A_ ) UpperCamelCase__ = KandinskyVaaPipeline.from_pretrained( """kandinsky-community/kandinsky-2-2-decoder""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipeline.to(A_ ) pipeline.set_progress_bar_config(disable=A_ ) UpperCamelCase__ = "red cat, 4k photo" UpperCamelCase__ = torch.Generator(device="""cuda""" ).manual_seed(0 ) UpperCamelCase__ = pipe_prior( A_ , generator=A_ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() UpperCamelCase__ = torch.Generator(device="""cuda""" ).manual_seed(0 ) UpperCamelCase__ = pipeline( image_embeds=A_ , negative_image_embeds=A_ , generator=A_ , num_inference_steps=1_00 , output_type="""np""" , ) UpperCamelCase__ = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(A_ , A_ )
716
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def __magic_name__ ( __a : int , __a : List[str] , __a : str=[] ): '''simple docstring''' UpperCamelCase__ = size[0] - overlap_pixels * 2 UpperCamelCase__ = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCamelCase__ = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCamelCase__ = np.pad(__a , mode="""linear_ramp""" , pad_width=__a , end_values=0 ) if "l" in remove_borders: UpperCamelCase__ = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCamelCase__ = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCamelCase__ = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCamelCase__ = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def __magic_name__ ( __a : int , __a : Dict , __a : Optional[int] ): '''simple docstring''' return max(__a , min(__a , __a ) ) def __magic_name__ ( __a : [int] , __a : [int] , __a : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def __magic_name__ ( __a : [int] , __a : int , __a : [int] ): '''simple docstring''' UpperCamelCase__ = list(__a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCamelCase__ = clamp_rect(__a , [0, 0] , [image_size[0], image_size[1]] ) return rect def __magic_name__ ( __a : Optional[int] , __a : Tuple , __a : str , __a : List[Any] ): '''simple docstring''' UpperCamelCase__ = Image.new("""RGB""" , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__a , (original_slice, 0) ) return result def __magic_name__ ( __a : int , __a : int ): '''simple docstring''' UpperCamelCase__ = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCamelCase__ = tile.crop(__a ) return tile def __magic_name__ ( __a : List[str] , __a : Any ): '''simple docstring''' UpperCamelCase__ = n % d return n - divisor class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 3_50 , ): super().__init__( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , low_res_scheduler=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , max_noise_level=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): torch.manual_seed(0 ) UpperCamelCase__ = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCamelCase__ = add_overlap_rect(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , image.size ) UpperCamelCase__ = image.crop(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCamelCase__ = translated_slice_x - (original_image_slice / 2) UpperCamelCase__ = max(0 , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = squeeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = to_input.size UpperCamelCase__ = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCamelCase__ = super(SCREAMING_SNAKE_CASE_ , self ).__call__(image=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).images[0] UpperCamelCase__ = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = unsqueeze_tile(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCamelCase__ = [] if x == 0: remove_borders.append("""l""" ) elif crop_rect[2] == image.size[0]: remove_borders.append("""r""" ) if y == 0: remove_borders.append("""t""" ) elif crop_rect[3] == image.size[1]: remove_borders.append("""b""" ) UpperCamelCase__ = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=SCREAMING_SNAKE_CASE_ ) , mode="""L""" , ) final_image.paste( SCREAMING_SNAKE_CASE_ , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 75 , SCREAMING_SNAKE_CASE_ = 9.0 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 1_28 , SCREAMING_SNAKE_CASE_ = 32 , SCREAMING_SNAKE_CASE_ = 32 , ): UpperCamelCase__ = Image.new("""RGB""" , (image.size[0] * 4, image.size[1] * 4) ) UpperCamelCase__ = math.ceil(image.size[0] / tile_size ) UpperCamelCase__ = math.ceil(image.size[1] / tile_size ) UpperCamelCase__ = tcx * tcy UpperCamelCase__ = 0 for y in range(SCREAMING_SNAKE_CASE_ ): for x in range(SCREAMING_SNAKE_CASE_ ): self._process_tile( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prompt=SCREAMING_SNAKE_CASE_ , num_inference_steps=SCREAMING_SNAKE_CASE_ , guidance_scale=SCREAMING_SNAKE_CASE_ , noise_level=SCREAMING_SNAKE_CASE_ , negative_prompt=SCREAMING_SNAKE_CASE_ , num_images_per_prompt=SCREAMING_SNAKE_CASE_ , eta=SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , latents=SCREAMING_SNAKE_CASE_ , ) current_count += 1 if callback is not None: callback({"""progress""": current_count / total_tile_count, """image""": final_image} ) return final_image def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = """stabilityai/stable-diffusion-x4-upscaler""" UpperCamelCase__ = StableDiffusionTiledUpscalePipeline.from_pretrained(__a , revision="""fp16""" , torch_dtype=torch.floataa ) UpperCamelCase__ = pipe.to("""cuda""" ) UpperCamelCase__ = Image.open("""../../docs/source/imgs/diffusers_library.jpg""" ) def callback(__a : Optional[int] ): print(f"progress: {obj['progress']:.4f}" ) obj["image"].save("""diffusers_library_progress.jpg""" ) UpperCamelCase__ = pipe(image=__a , prompt="""Black font, white background, vector""" , noise_level=40 , callback=__a ) final_image.save("""diffusers_library.jpg""" ) if __name__ == "__main__": main()
86
0
import os import re import shutil import sys import tempfile import unittest import black lowerCamelCase_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. lowerCamelCase_ = ''' def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states ''' class __A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ (self ): UpperCamelCase__ = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , """models/bert/""" ) ) UpperCamelCase__ = self.transformer_dir shutil.copy( os.path.join(SCREAMING_SNAKE_CASE_ , """src/transformers/models/bert/modeling_bert.py""" ) , os.path.join(self.transformer_dir , """models/bert/modeling_bert.py""" ) , ) def UpperCAmelCase_ (self ): UpperCamelCase__ = """src/transformers""" shutil.rmtree(self.transformer_dir ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ): UpperCamelCase__ = comment + F"\nclass {class_name}(nn.Module):\n" + class_code if overwrite_result is not None: UpperCamelCase__ = comment + F"\nclass {class_name}(nn.Module):\n" + overwrite_result UpperCamelCase__ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 ) UpperCamelCase__ = black.format_str(SCREAMING_SNAKE_CASE_ , mode=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = os.path.join(self.transformer_dir , """new_code.py""" ) with open(SCREAMING_SNAKE_CASE_ , """w""" , newline="""\n""" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(SCREAMING_SNAKE_CASE_ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ , """r""" ) as f: self.assertTrue(f.read() , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): UpperCamelCase__ = check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead""" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): # Base copy consistency self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , SCREAMING_SNAKE_CASE_ , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , re.sub("""Bert""" , """TestModel""" , SCREAMING_SNAKE_CASE_ ) , ) # Copy consistency with a really long name UpperCamelCase__ = """TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( F"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}" , F"{long_class_name}LMPredictionHead" , re.sub("""Bert""" , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , SCREAMING_SNAKE_CASE_ , overwrite_result=re.sub("""Bert""" , """TestModel""" , SCREAMING_SNAKE_CASE_ ) , ) def UpperCAmelCase_ (self ): UpperCamelCase__ = check_copies.LOCALIZED_READMES["""README_zh-hans.md"""] UpperCamelCase__ = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),""" """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**""" """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders""" """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang""" """ Luong, Quoc V. Le, Christopher D. Manning.""" ) UpperCamelCase__ = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) UpperCamelCase__ = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文""" """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自""" """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather""" """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,""" """ Christopher D. Manning 发布。\n""" ) UpperCamelCase__ , UpperCamelCase__ = check_copies.convert_to_localized_md( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , localized_readme["""format_model_list"""] ) self.assertFalse(SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ , UpperCamelCase__ = check_copies.convert_to_localized_md( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , localized_readme["""format_model_list"""] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.""" ) UpperCamelCase__ = ( """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and""" """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) UpperCamelCase__ = ( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) UpperCamelCase__ , UpperCamelCase__ = check_copies.convert_to_localized_md( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , localized_readme["""format_model_list"""] ) # Check if the model link is synchronized. self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
717
import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging lowerCamelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __A( __lowerCamelCase ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , safety_checker=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase_ (self , SCREAMING_SNAKE_CASE_ = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase__ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase_ (self ): self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 5_12 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ): if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = 1 elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = len(SCREAMING_SNAKE_CASE_ ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE_ )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(SCREAMING_SNAKE_CASE_ )}." ) # get prompt text embeddings UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) UpperCamelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: UpperCamelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F" {self.tokenizer.model_max_length} tokens: {removed_text}" ) UpperCamelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: UpperCamelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = text_embeddings.shape UpperCamelCase__ = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase__ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase__ = 42 if negative_prompt is None: UpperCamelCase__ = [""""""] elif type(SCREAMING_SNAKE_CASE_ ) is not type(SCREAMING_SNAKE_CASE_ ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE_ )} !=" F" {type(SCREAMING_SNAKE_CASE_ )}." ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase__ = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE_ )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: UpperCamelCase__ = negative_prompt UpperCamelCase__ = text_input_ids.shape[-1] UpperCamelCase__ = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors="""pt""" , ) UpperCamelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCamelCase__ = uncond_embeddings.shape[1] UpperCamelCase__ = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) UpperCamelCase__ = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase__ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase__ = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) UpperCamelCase__ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to(self.device ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase__ = torch.randn( SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=self.device , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) UpperCamelCase__ = latents_reference.to(self.device ) UpperCamelCase__ = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images UpperCamelCase__ = (latents_shape[3] - latents_shape_reference[3]) // 2 UpperCamelCase__ = (latents_shape[2] - latents_shape_reference[2]) // 2 UpperCamelCase__ = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx UpperCamelCase__ = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy UpperCamelCase__ = 0 if dx < 0 else dx UpperCamelCase__ = 0 if dy < 0 else dy UpperCamelCase__ = max(-dx , 0 ) UpperCamelCase__ = max(-dy , 0 ) # import pdb # pdb.set_trace() UpperCamelCase__ = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand UpperCamelCase__ = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase__ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase__ = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase__ = {} if accepts_eta: UpperCamelCase__ = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance UpperCamelCase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase__ = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase__ = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform guidance if do_classifier_free_guidance: UpperCamelCase__ , UpperCamelCase__ = noise_pred.chunk(2 ) UpperCamelCase__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase__ = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 1 / 0.1_8215 * latents UpperCamelCase__ = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCamelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: UpperCamelCase__ = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) , return_tensors="""pt""" ).to( self.device ) UpperCamelCase__ , UpperCamelCase__ = self.safety_checker( images=SCREAMING_SNAKE_CASE_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: UpperCamelCase__ = None if output_type == "pil": UpperCamelCase__ = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
86
0
import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser( description=( '''Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned''' ''' Distillation''' ) ) parser.add_argument('''--model_type''', default='''bert''', choices=['''bert''']) parser.add_argument('''--model_name''', default='''bert-base-uncased''', type=str) parser.add_argument('''--dump_checkpoint''', default='''serialization_dir/tf_bert-base-uncased_0247911.pth''', type=str) parser.add_argument('''--vocab_transform''', action='''store_true''') lowerCamelCase_ = parser.parse_args() if args.model_type == "bert": lowerCamelCase_ = BertForMaskedLM.from_pretrained(args.model_name) lowerCamelCase_ = '''bert''' else: raise ValueError('''args.model_type should be "bert".''') lowerCamelCase_ = model.state_dict() lowerCamelCase_ = {} for w in ["word_embeddings", "position_embeddings"]: lowerCamelCase_ = state_dict[f'{prefix}.embeddings.{w}.weight'] for w in ["weight", "bias"]: lowerCamelCase_ = state_dict[f'{prefix}.embeddings.LayerNorm.{w}'] lowerCamelCase_ = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}' ] lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}' ] lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}' ] lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}' ] lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}' ] lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}' ] lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}' ] lowerCamelCase_ = state_dict[ f'{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}' ] std_idx += 1 lowerCamelCase_ = state_dict['''cls.predictions.decoder.weight'''] lowerCamelCase_ = state_dict['''cls.predictions.bias'''] if args.vocab_transform: for w in ["weight", "bias"]: lowerCamelCase_ = state_dict[f'cls.predictions.transform.dense.{w}'] lowerCamelCase_ = state_dict[f'cls.predictions.transform.LayerNorm.{w}'] print(f'N layers selected for distillation: {std_idx}') print(f'Number of params transferred for distillation: {len(compressed_sd.keys())}') print(f'Save transferred checkpoint to {args.dump_checkpoint}.') torch.save(compressed_sd, args.dump_checkpoint)
718
from ..utils import DummyObject, requires_backends class __A( metaclass=__lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torch""", """torchsde"""] def __init__(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def UpperCAmelCase_ (cls , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): requires_backends(cls , ["""torch""", """torchsde"""] )
86
0