code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) a__ : Any = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '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 a__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=5 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=2_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Optional[Any]: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> str: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __UpperCamelCase = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = np.concatenate([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , decoder_attention_mask=lowercase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Any: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase , decoder_attention_mask=lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = np.not_equal(__A ,config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __UpperCamelCase = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape ,dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ).astype(np.inta ), ] ,axis=-1 ,) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __SCREAMING_SNAKE_CASE = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = FlaxPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> List[Any]: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = self._prepare_for_class(lowercase , lowercase ) __UpperCamelCase = model_class(lowercase ) @jax.jit def encode_jitted(lowercase , lowercase=None , **lowercase ): return model.encode(input_ids=lowercase , attention_mask=lowercase ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) __UpperCamelCase = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(lowercase , lowercase , lowercase ): return model.decode( decoder_input_ids=lowercase , decoder_attention_mask=lowercase , encoder_outputs=lowercase , ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __lowerCamelCase ( self ) -> Dict: for model_class_name in self.all_model_classes: __UpperCamelCase = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=lowercase ) __UpperCamelCase = np.ones((1, 1) ) __UpperCamelCase = model(lowercase ) self.assertIsNotNone(lowercase ) @slow def __lowerCamelCase ( self ) -> str: __UpperCamelCase = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] __UpperCamelCase = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] __UpperCamelCase = tokenizer(lowercase , return_tensors="""np""" , truncation=lowercase , max_length=5_1_2 , padding=lowercase ) __UpperCamelCase = model.generate(**lowercase , num_beams=2 ).sequences __UpperCamelCase = tokenizer.batch_decode(lowercase , skip_special_tokens=lowercase ) assert tgt_text == decoded
349
1
'''simple docstring''' from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _lowercase ( __A = "isbn/0140328726" ): '''simple docstring''' __UpperCamelCase = olid.strip().strip("""/""" ) # Remove leading/trailing whitespace & slashes if new_olid.count("""/""" ) != 1: __UpperCamelCase = f"{olid} is not a valid Open Library olid" raise ValueError(__A ) return requests.get(f"https://openlibrary.org/{new_olid}.json" ).json() def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = { """title""": """Title""", """publish_date""": """Publish date""", """authors""": """Authors""", """number_of_pages""": """Number of pages:""", """first_sentence""": """First sentence""", """isbn_10""": """ISBN (10)""", """isbn_13""": """ISBN (13)""", } __UpperCamelCase = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} __UpperCamelCase = [ get_openlibrary_data(author["""key"""] )["""name"""] for author in data["""Authors"""] ] __UpperCamelCase = data["""First sentence"""]["""value"""] for key, value in data.items(): if isinstance(__A ,__A ): __UpperCamelCase = """, """.join(__A ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: a__ : Tuple = input('\nEnter the ISBN code to search (or \'quit\' to stop): ').strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (1_0, 1_3) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: a__ : str = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print('\n'.join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
349
'''simple docstring''' import pytest a__ : List[str] = '__dummy_dataset1__' a__ : Optional[int] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dataset_loading_script_name __UpperCamelCase = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=__A ) __UpperCamelCase = script_dir / f"{script_name}.py" with open(__A ,"""w""" ) as f: f.write(__A ) return str(__A )
349
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() a__ : Optional[Any] = logging.get_logger(__name__) def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = SwinConfig( embed_dim=192 ,depths=(2, 2, 18, 2) ,num_heads=(6, 12, 24, 48) ,window_size=12 ,out_features=["""stage2""", """stage3""", """stage4"""] ,) __UpperCamelCase = DetaConfig( backbone_config=__A ,num_queries=900 ,encoder_ffn_dim=2_048 ,decoder_ffn_dim=2_048 ,num_feature_levels=5 ,assign_first_stage=__A ,with_box_refine=__A ,two_stage=__A ,) # set labels __UpperCamelCase = """huggingface/label-files""" if "o365" in model_name: __UpperCamelCase = 366 __UpperCamelCase = """object365-id2label.json""" else: __UpperCamelCase = 91 __UpperCamelCase = """coco-detection-id2label.json""" __UpperCamelCase = num_labels __UpperCamelCase = json.load(open(cached_download(hf_hub_url(__A ,__A ,repo_type="""dataset""" ) ) ,"""r""" ) ) __UpperCamelCase = {int(__A ): v for k, v in idalabel.items()} __UpperCamelCase = idalabel __UpperCamelCase = {v: k for k, v in idalabel.items()} return config def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = [] # stem # fmt: off rename_keys.append(("""backbone.0.body.patch_embed.proj.weight""", """model.backbone.model.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.0.body.patch_embed.proj.bias""", """model.backbone.model.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.0.body.patch_embed.norm.weight""", """model.backbone.model.embeddings.norm.weight""") ) rename_keys.append(("""backbone.0.body.patch_embed.norm.bias""", """model.backbone.model.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm1.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm1.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm2.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.norm2.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias", f"model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias") ) if i < 3: rename_keys.append((f"backbone.0.body.layers.{i}.downsample.reduction.weight", f"model.backbone.model.encoder.layers.{i}.downsample.reduction.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.downsample.norm.weight", f"model.backbone.model.encoder.layers.{i}.downsample.norm.weight") ) rename_keys.append((f"backbone.0.body.layers.{i}.downsample.norm.bias", f"model.backbone.model.encoder.layers.{i}.downsample.norm.bias") ) rename_keys.append(("""backbone.0.body.norm1.weight""", """model.backbone.model.hidden_states_norms.stage2.weight""") ) rename_keys.append(("""backbone.0.body.norm1.bias""", """model.backbone.model.hidden_states_norms.stage2.bias""") ) rename_keys.append(("""backbone.0.body.norm2.weight""", """model.backbone.model.hidden_states_norms.stage3.weight""") ) rename_keys.append(("""backbone.0.body.norm2.bias""", """model.backbone.model.hidden_states_norms.stage3.bias""") ) rename_keys.append(("""backbone.0.body.norm3.weight""", """model.backbone.model.hidden_states_norms.stage4.weight""") ) rename_keys.append(("""backbone.0.body.norm3.bias""", """model.backbone.model.hidden_states_norms.stage4.bias""") ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight", f"model.encoder.layers.{i}.self_attn.sampling_offsets.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias", f"model.encoder.layers.{i}.self_attn.sampling_offsets.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.weight", f"model.encoder.layers.{i}.self_attn.attention_weights.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.attention_weights.bias", f"model.encoder.layers.{i}.self_attn.attention_weights.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.weight", f"model.encoder.layers.{i}.self_attn.value_proj.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.value_proj.bias", f"model.encoder.layers.{i}.self_attn.value_proj.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.weight", f"model.encoder.layers.{i}.self_attn.output_proj.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.self_attn.output_proj.bias", f"model.encoder.layers.{i}.self_attn.output_proj.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm1.weight", f"model.encoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm1.bias", f"model.encoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"model.encoder.layers.{i}.fc1.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"model.encoder.layers.{i}.fc1.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"model.encoder.layers.{i}.fc2.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"model.encoder.layers.{i}.fc2.bias") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.weight", f"model.encoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"model.encoder.layers.{i}.final_layer_norm.bias") ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias", f"model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.weight", f"model.decoder.layers.{i}.encoder_attn.attention_weights.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.attention_weights.bias", f"model.decoder.layers.{i}.encoder_attn.attention_weights.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.weight", f"model.decoder.layers.{i}.encoder_attn.value_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.value_proj.bias", f"model.decoder.layers.{i}.encoder_attn.value_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.weight", f"model.decoder.layers.{i}.encoder_attn.output_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.cross_attn.output_proj.bias", f"model.decoder.layers.{i}.encoder_attn.output_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm1.weight", f"model.decoder.layers.{i}.encoder_attn_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm1.bias", f"model.decoder.layers.{i}.encoder_attn_layer_norm.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"model.decoder.layers.{i}.self_attn.out_proj.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"model.decoder.layers.{i}.self_attn.out_proj.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm2.weight", f"model.decoder.layers.{i}.self_attn_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm2.bias", f"model.decoder.layers.{i}.self_attn_layer_norm.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"model.decoder.layers.{i}.fc1.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"model.decoder.layers.{i}.fc1.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"model.decoder.layers.{i}.fc2.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"model.decoder.layers.{i}.fc2.bias") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.weight", f"model.decoder.layers.{i}.final_layer_norm.weight") ) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"model.decoder.layers.{i}.final_layer_norm.bias") ) # fmt: on return rename_keys def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dct.pop(__A ) __UpperCamelCase = val def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __UpperCamelCase = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) __UpperCamelCase = state_dict.pop(f"backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight" ) __UpperCamelCase = state_dict.pop(f"backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict __UpperCamelCase = in_proj_weight[:dim, :] __UpperCamelCase = in_proj_bias[: dim] __UpperCamelCase = in_proj_weight[ dim : dim * 2, : ] __UpperCamelCase = in_proj_bias[ dim : dim * 2 ] __UpperCamelCase = in_proj_weight[ -dim :, : ] __UpperCamelCase = in_proj_bias[-dim :] # fmt: on def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention __UpperCamelCase = state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_weight" ) __UpperCamelCase = state_dict.pop(f"transformer.decoder.layers.{i}.self_attn.in_proj_bias" ) # next, add query, keys and values (in that order) to the state dict __UpperCamelCase = in_proj_weight[:hidden_size, :] __UpperCamelCase = in_proj_bias[:hidden_size] __UpperCamelCase = in_proj_weight[ hidden_size : hidden_size * 2, : ] __UpperCamelCase = in_proj_bias[hidden_size : hidden_size * 2] __UpperCamelCase = in_proj_weight[-hidden_size:, :] __UpperCamelCase = in_proj_bias[-hidden_size:] def _lowercase ( ): '''simple docstring''' __UpperCamelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" __UpperCamelCase = Image.open(requests.get(__A ,stream=__A ).raw ) return im @torch.no_grad() def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = get_deta_config(__A ) # load original state dict if model_name == "deta-swin-large": __UpperCamelCase = hf_hub_download(repo_id="""nielsr/deta-checkpoints""" ,filename="""adet_swin_ft.pth""" ) elif model_name == "deta-swin-large-o365": __UpperCamelCase = hf_hub_download(repo_id="""jozhang97/deta-swin-l-o365""" ,filename="""deta_swin_pt_o365.pth""" ) else: raise ValueError(f"Model name {model_name} not supported" ) __UpperCamelCase = torch.load(__A ,map_location="""cpu""" )["""model"""] # original state dict for name, param in state_dict.items(): print(__A ,param.shape ) # rename keys __UpperCamelCase = create_rename_keys(__A ) for src, dest in rename_keys: rename_key(__A ,__A ,__A ) read_in_swin_q_k_v(__A ,config.backbone_config ) read_in_decoder_q_k_v(__A ,__A ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: __UpperCamelCase = state_dict.pop(__A ) __UpperCamelCase = val if "input_proj" in key: __UpperCamelCase = state_dict.pop(__A ) __UpperCamelCase = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: __UpperCamelCase = state_dict.pop(__A ) __UpperCamelCase = val # finally, create HuggingFace model and load state dict __UpperCamelCase = DetaForObjectDetection(__A ) model.load_state_dict(__A ) model.eval() __UpperCamelCase = """cuda""" if torch.cuda.is_available() else """cpu""" model.to(__A ) # load image processor __UpperCamelCase = DetaImageProcessor(format="""coco_detection""" ) # verify our conversion on image __UpperCamelCase = prepare_img() __UpperCamelCase = processor(images=__A ,return_tensors="""pt""" ) __UpperCamelCase = encoding["""pixel_values"""] __UpperCamelCase = model(pixel_values.to(__A ) ) # verify logits print("""Logits:""" ,outputs.logits[0, :3, :3] ) print("""Boxes:""" ,outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": __UpperCamelCase = torch.tensor( [[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]] ) __UpperCamelCase = torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]] ) elif model_name == "deta-swin-large-o365": __UpperCamelCase = torch.tensor( [[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]] ) __UpperCamelCase = torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]] ) assert torch.allclose(outputs.logits[0, :3, :3] ,expected_logits.to(__A ) ,atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] ,expected_boxes.to(__A ) ,atol=1E-4 ) print("""Everything ok!""" ) if pytorch_dump_folder_path: # Save model and processor logger.info(f"Saving PyTorch model and processor to {pytorch_dump_folder_path}..." ) Path(__A ).mkdir(exist_ok=__A ) model.save_pretrained(__A ) processor.save_pretrained(__A ) # Push to hub if push_to_hub: print("""Pushing model and processor to hub...""" ) model.push_to_hub(f"jozhang97/{model_name}" ) processor.push_to_hub(f"jozhang97/{model_name}" ) if __name__ == "__main__": a__ : List[Any] = argparse.ArgumentParser() parser.add_argument( '--model_name', type=str, default='deta-swin-large', choices=['deta-swin-large', 'deta-swin-large-o365'], help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) a__ : List[str] = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
349
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } a__ : List[str] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} with open(__A ,"""r""" ) as file: for line_number, line in enumerate(__A ): __UpperCamelCase = line.strip() if line: __UpperCamelCase = line.split() __UpperCamelCase = line_number __UpperCamelCase = words[0] __UpperCamelCase = value return result def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' for attribute in key.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = getattr(__A ,__A ).shape elif weight_type is not None and weight_type == "param": __UpperCamelCase = hf_pointer for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = shape_pointer.shape # let's reduce dimension __UpperCamelCase = value[0] 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 == "param": for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = value else: __UpperCamelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __UpperCamelCase = """.""".join([key, hf_param_name] ) else: __UpperCamelCase = key __UpperCamelCase = value if """lm_head""" in full_key else value[0] a__ : Dict = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _lowercase ( __A ,__A ,__A=None ,__A=None ): '''simple docstring''' __UpperCamelCase = False for key, mapped_key in MAPPING.items(): __UpperCamelCase = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __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: # TODO: don't match quantizer.weight_proj __UpperCamelCase = """weight""" else: __UpperCamelCase = None if hf_dict is not None: rename_dict(__A ,__A ,__A ,__A ,__A ) else: set_recursively(__A ,__A ,__A ,__A ,__A ) return is_used return is_used def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = [] __UpperCamelCase = fairseq_model.state_dict() __UpperCamelCase = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __A ,__A ,__A ,__A ,hf_model.config.feat_extract_norm == """group""" ,) __UpperCamelCase = True else: __UpperCamelCase = load_wavaveca_layer(__A ,__A ,__A ) if not is_used: unused_weights.append(__A ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''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 _lowercase ( __A ,__A ,__A=None ,__A=None ,__A=True ,__A=False ): '''simple docstring''' if config_path is not None: __UpperCamelCase = WavaVecaConfig.from_pretrained(__A ) else: __UpperCamelCase = WavaVecaConfig() if is_seq_class: __UpperCamelCase = read_txt_into_dict(__A ) __UpperCamelCase = idalabel __UpperCamelCase = WavaVecaForSequenceClassification(__A ) __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) feature_extractor.save_pretrained(__A ) elif is_finetuned: if dict_path: __UpperCamelCase = Dictionary.load(__A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase = target_dict.pad_index __UpperCamelCase = target_dict.bos_index __UpperCamelCase = target_dict.eos_index __UpperCamelCase = len(target_dict.symbols ) __UpperCamelCase = os.path.join(__A ,"""vocab.json""" ) if not os.path.isdir(__A ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__A ) ) return os.makedirs(__A ,exist_ok=__A ) __UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCamelCase = 0 __UpperCamelCase = 1 with open(__A ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(__A ,__A ) __UpperCamelCase = WavaVecaCTCTokenizer( __A ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=__A ,) __UpperCamelCase = True if config.feat_extract_norm == """layer""" else False __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) __UpperCamelCase = WavaVecaProcessor(feature_extractor=__A ,tokenizer=__A ) processor.save_pretrained(__A ) __UpperCamelCase = WavaVecaForCTC(__A ) else: __UpperCamelCase = WavaVecaForPreTraining(__A ) if is_finetuned or is_seq_class: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __UpperCamelCase = argparse.Namespace(task="""audio_pretraining""" ) __UpperCamelCase = fairseq.tasks.setup_task(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=__A ) __UpperCamelCase = model[0].eval() recursively_load_weights(__A ,__A ,not is_finetuned ) hf_wavavec.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) a__ : Optional[int] = parser.parse_args() a__ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
349
1
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast @require_vision class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = tempfile.mkdtemp() __UpperCamelCase = BlipImageProcessor() __UpperCamelCase = GPTaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-GPT2Model""" ) __UpperCamelCase = BlipaProcessor(lowercase , lowercase ) processor.save_pretrained(self.tmpdirname ) def __lowerCamelCase ( self , **lowercase ) -> List[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **lowercase ).tokenizer def __lowerCamelCase ( self , **lowercase ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **lowercase ).image_processor def __lowerCamelCase ( self ) -> Optional[Any]: shutil.rmtree(self.tmpdirname ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __UpperCamelCase = [Image.fromarray(np.moveaxis(lowercase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = BlipaProcessor(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=lowercase , padding_value=1.0 ) __UpperCamelCase = BlipaProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=lowercase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowercase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowercase ) def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.get_image_processor() __UpperCamelCase = self.get_tokenizer() __UpperCamelCase = BlipaProcessor(tokenizer=lowercase , image_processor=lowercase ) __UpperCamelCase = self.prepare_image_inputs() __UpperCamelCase = image_processor(lowercase , return_tensors="""np""" ) __UpperCamelCase = processor(images=lowercase , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.get_image_processor() __UpperCamelCase = self.get_tokenizer() __UpperCamelCase = BlipaProcessor(tokenizer=lowercase , image_processor=lowercase ) __UpperCamelCase = """lower newer""" __UpperCamelCase = processor(text=lowercase ) __UpperCamelCase = tokenizer(lowercase , return_token_type_ids=lowercase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.get_image_processor() __UpperCamelCase = self.get_tokenizer() __UpperCamelCase = BlipaProcessor(tokenizer=lowercase , image_processor=lowercase ) __UpperCamelCase = """lower newer""" __UpperCamelCase = self.prepare_image_inputs() __UpperCamelCase = processor(text=lowercase , images=lowercase ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] ) # test if it raises when no input is passed with pytest.raises(lowercase ): processor() def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.get_image_processor() __UpperCamelCase = self.get_tokenizer() __UpperCamelCase = BlipaProcessor(tokenizer=lowercase , image_processor=lowercase ) __UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __UpperCamelCase = processor.batch_decode(lowercase ) __UpperCamelCase = tokenizer.batch_decode(lowercase ) self.assertListEqual(lowercase , lowercase ) def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.get_image_processor() __UpperCamelCase = self.get_tokenizer() __UpperCamelCase = BlipaProcessor(tokenizer=lowercase , image_processor=lowercase ) __UpperCamelCase = """lower newer""" __UpperCamelCase = self.prepare_image_inputs() __UpperCamelCase = processor(text=lowercase , images=lowercase ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCAmelCase__ : def __init__( self , lowercase , ) -> Union[str, Any]: __UpperCamelCase = parent __UpperCamelCase = 1_3 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = 9_9 __UpperCamelCase = 3_2 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 3_7 __UpperCamelCase = """gelu""" __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 5_1_2 __UpperCamelCase = 1_6 __UpperCamelCase = 2 __UpperCamelCase = 0.02 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = None def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = None if self.use_input_mask: __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = TFDistilBertModel(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]: __UpperCamelCase = TFDistilBertForMaskedLM(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = TFDistilBertForQuestionAnswering(config=lowercase ) __UpperCamelCase = { """input_ids""": input_ids, """attention_mask""": input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForSequenceClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: __UpperCamelCase = self.num_choices __UpperCamelCase = TFDistilBertForMultipleChoice(lowercase ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForTokenClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.prepare_config_and_inputs() ((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFDistilBertModel, '''fill-mask''': TFDistilBertForMaskedLM, '''question-answering''': TFDistilBertForQuestionAnswering, '''text-classification''': TFDistilBertForSequenceClassification, '''token-classification''': TFDistilBertForTokenClassification, '''zero-shot''': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = TFDistilBertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , dim=3_7 ) def __lowerCamelCase ( self ) -> Any: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) @slow def __lowerCamelCase ( self ) -> Tuple: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): __UpperCamelCase = TFDistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_tf class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase = model(lowercase )[0] __UpperCamelCase = [1, 6, 7_6_8] self.assertEqual(output.shape , lowercase ) __UpperCamelCase = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-4 )
349
1
'''simple docstring''' from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def _lowercase ( ): '''simple docstring''' __UpperCamelCase = { """repo_name""": ["""test_repo1""", """test_repo2""", """test_repo3"""], """path""": ["""test_1.py""", """test_2.py""", """unit_test.py"""], """content""": ["""a """ * 20, """a """ * 30, """b """ * 7], } __UpperCamelCase = Dataset.from_dict(__A ) return dataset class UpperCAmelCase__ ( UpperCAmelCase_): def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = get_dataset() __UpperCamelCase = make_duplicate_clusters(lowercase , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = get_dataset() __UpperCamelCase , __UpperCamelCase = deduplicate_dataset(lowercase ) self.assertEqual(len(lowercase ) , 2 ) print(lowercase ) self.assertEqual(duplicate_clusters[0][0]["""copies"""] , 2 ) self.assertEqual(duplicate_clusters[0][0]["""is_extreme"""] , lowercase )
349
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _lowercase ( __A ,__A ): '''simple docstring''' return math.sqrt(sum(pow(a - b ,2 ) for a, b in zip(__A ,__A ) ) ) def _lowercase ( __A ,__A ): '''simple docstring''' if dataset.ndim != value_array.ndim: __UpperCamelCase = ( """Wrong input data's dimensions... """ f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(__A ) try: if dataset.shape[1] != value_array.shape[1]: __UpperCamelCase = ( """Wrong input data's shape... """ f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(__A ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: __UpperCamelCase = ( """Input data have different datatype... """ f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(__A ) __UpperCamelCase = [] for value in value_array: __UpperCamelCase = euclidean(__A ,dataset[0] ) __UpperCamelCase = dataset[0].tolist() for dataset_value in dataset[1:]: __UpperCamelCase = euclidean(__A ,__A ) if dist > temp_dist: __UpperCamelCase = temp_dist __UpperCamelCase = dataset_value.tolist() answer.append([vector, dist] ) return answer def _lowercase ( __A ,__A ): '''simple docstring''' return np.dot(__A ,__A ) / (norm(__A ) * norm(__A )) if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' from __future__ import annotations import bisect def _lowercase ( __A ,__A ,__A = 0 ,__A = -1 ): '''simple docstring''' if hi < 0: __UpperCamelCase = len(__A ) while lo < hi: __UpperCamelCase = lo + (hi - lo) // 2 if sorted_collection[mid] < item: __UpperCamelCase = mid + 1 else: __UpperCamelCase = mid return lo def _lowercase ( __A ,__A ,__A = 0 ,__A = -1 ): '''simple docstring''' if hi < 0: __UpperCamelCase = len(__A ) while lo < hi: __UpperCamelCase = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: __UpperCamelCase = mid + 1 else: __UpperCamelCase = mid return lo def _lowercase ( __A ,__A ,__A = 0 ,__A = -1 ): '''simple docstring''' sorted_collection.insert(bisect_left(__A ,__A ,__A ,__A ) ,__A ) def _lowercase ( __A ,__A ,__A = 0 ,__A = -1 ): '''simple docstring''' sorted_collection.insert(bisect_right(__A ,__A ,__A ,__A ) ,__A ) def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = 0 __UpperCamelCase = len(__A ) - 1 while left <= right: __UpperCamelCase = left + (right - left) // 2 __UpperCamelCase = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: __UpperCamelCase = midpoint - 1 else: __UpperCamelCase = midpoint + 1 return None def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = bisect.bisect_left(__A ,__A ) if index != len(__A ) and sorted_collection[index] == item: return index return None def _lowercase ( __A ,__A ,__A ,__A ): '''simple docstring''' if right < left: return None __UpperCamelCase = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(__A ,__A ,__A ,midpoint - 1 ) else: return binary_search_by_recursion(__A ,__A ,midpoint + 1 ,__A ) if __name__ == "__main__": a__ : Optional[Any] = input('Enter numbers separated by comma:\n').strip() a__ : Any = sorted(int(item) for item in user_input.split(',')) a__ : str = int(input('Enter a single number to be found in the list:\n')) a__ : Union[str, Any] = binary_search(collection, target) if result is None: print(f'''{target} was not found in {collection}.''') else: print(f'''{target} was found at position {result} in {collection}.''')
349
'''simple docstring''' from datetime import datetime import requests def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = """https://downloadgram.net/wp-json/wppress/video-downloader/video?url=""" __UpperCamelCase = requests.get(base_url + url ).json()[0]["""urls"""][0]["""src"""] return requests.get(__A ).content if __name__ == "__main__": a__ : int = input('Enter Video/IGTV url: ').strip() a__ : int = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4''' with open(file_name, 'wb') as fp: fp.write(download_video(url)) print(f'''Done. Video saved to disk as {file_name}.''')
349
1
'''simple docstring''' def _lowercase ( __A ): '''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() a__ : Dict = int(input('Enter a positive integer: ').strip()) print(prime_sieve_eratosthenes(user_num))
349
'''simple docstring''' import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowercase ( __A ,__A=False ): '''simple docstring''' try: __UpperCamelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __UpperCamelCase = default else: # KEY is set, convert it to True or False. try: __UpperCamelCase = strtobool(__A ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no." ) return _value a__ : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) a__ : Union[str, Any] = parse_flag_from_env('RUN_REMOTE', default=False) a__ : Any = parse_flag_from_env('RUN_LOCAL', default=True) a__ : List[Any] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a__ : Optional[int] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a__ : Optional[int] = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a__ : Optional[Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a__ : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a__ : str = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a__ : str = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a__ : Tuple = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowercase ( __A ): '''simple docstring''' try: import faiss # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires faiss""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import regex # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires regex""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import elasticsearch # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires elasticsearch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import sqlalchemy # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires sqlalchemy""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TORCH_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires PyTorch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TF_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires TensorFlow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.JAX_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires JAX""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.PIL_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires Pillow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import transformers # noqa F401 except ImportError: return unittest.skip("""test requires transformers""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import tiktoken # noqa F401 except ImportError: return unittest.skip("""test requires tiktoken""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import spacy # noqa F401 except ImportError: return unittest.skip("""test requires spacy""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' def _require_spacy_model(__A ): try: import spacy # noqa F401 spacy.load(__A ) except ImportError: return unittest.skip("""test requires spacy""" )(__A ) except OSError: return unittest.skip("""test requires spacy model '{}'""".format(__A ) )(__A ) else: return test_case return _require_spacy_model def _lowercase ( __A ): '''simple docstring''' try: import pyspark # noqa F401 except ImportError: return unittest.skip("""test requires pyspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import joblibspark # noqa F401 except ImportError: return unittest.skip("""test requires joblibspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_slow_tests or _run_slow_tests == 0: __UpperCamelCase = unittest.skip("""test is slow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_local_tests or _run_local_tests == 0: __UpperCamelCase = unittest.skip("""test is local""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_packaged_tests or _run_packaged_tests == 0: __UpperCamelCase = unittest.skip("""test is packaged""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_remote_tests or _run_remote_tests == 0: __UpperCamelCase = unittest.skip("""test requires remote""" )(__A ) return test_case def _lowercase ( *__A ): '''simple docstring''' def decorate(cls ): for name, fn in cls.__dict__.items(): if callable(__A ) and name.startswith("""test""" ): for decorator in decorators: __UpperCamelCase = decorator(__A ) setattr(cls ,__A ,__A ) return cls return decorate class UpperCAmelCase__ ( UpperCAmelCase_): pass class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 @contextmanager def _lowercase ( __A=OfflineSimulationMode.CONNECTION_FAILS ,__A=1E-16 ): '''simple docstring''' __UpperCamelCase = requests.Session().request def timeout_request(__A ,__A ,__A ,**__A ): # Change the url to an invalid url so that the connection hangs __UpperCamelCase = """https://10.255.255.1""" if kwargs.get("""timeout""" ) is None: raise RequestWouldHangIndefinitelyError( f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) __UpperCamelCase = timeout try: return online_request(__A ,__A ,**__A ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __UpperCamelCase = url __UpperCamelCase = e.args[0] __UpperCamelCase = (max_retry_error.args[0].replace("""10.255.255.1""" ,f"OfflineMock[{url}]" ),) __UpperCamelCase = (max_retry_error,) raise def raise_connection_error(__A ,__A ,**__A ): raise requests.ConnectionError("""Offline mode is enabled.""" ,request=__A ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("""requests.Session.send""" ,__A ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("""requests.Session.request""" ,__A ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,__A ): yield else: raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" ) @contextmanager def _lowercase ( *__A ,**__A ): '''simple docstring''' __UpperCamelCase = str(Path().resolve() ) with tempfile.TemporaryDirectory(*__A ,**__A ) as tmp_dir: try: os.chdir(__A ) yield finally: os.chdir(__A ) @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowercase ( __A ,__A ): '''simple docstring''' return deepcopy(__A ).integers(0 ,100 ,10 ).tolist() == deepcopy(__A ).integers(0 ,100 ,10 ).tolist() def _lowercase ( __A ): '''simple docstring''' import decorator from requests.exceptions import HTTPError def _wrapper(__A ,*__A ,**__A ): try: return func(*__A ,**__A ) except HTTPError as err: if str(__A ).startswith("""500""" ) or str(__A ).startswith("""502""" ): pytest.xfail(str(__A ) ) raise err return decorator.decorator(_wrapper ,__A ) class UpperCAmelCase__ : def __init__( self , lowercase , lowercase , lowercase ) -> str: __UpperCamelCase = returncode __UpperCamelCase = stdout __UpperCamelCase = stderr async def _lowercase ( __A ,__A ): '''simple docstring''' while True: __UpperCamelCase = await stream.readline() if line: callback(__A ) else: break async def _lowercase ( __A ,__A=None ,__A=None ,__A=None ,__A=False ,__A=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(__A ) ) __UpperCamelCase = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=__A ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=__A ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __UpperCamelCase = [] __UpperCamelCase = [] def tee(__A ,__A ,__A ,__A="" ): __UpperCamelCase = line.decode("""utf-8""" ).rstrip() sink.append(__A ) if not quiet: print(__A ,__A ,file=__A ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __A : tee(__A ,__A ,sys.stdout ,label="""stdout:""" ) ), _read_stream(p.stderr ,lambda __A : tee(__A ,__A ,sys.stderr ,label="""stderr:""" ) ), ] ,timeout=__A ,) return _RunOutput(await p.wait() ,__A ,__A ) def _lowercase ( __A ,__A=None ,__A=None ,__A=180 ,__A=False ,__A=True ): '''simple docstring''' __UpperCamelCase = asyncio.get_event_loop() __UpperCamelCase = loop.run_until_complete( _stream_subprocess(__A ,env=__A ,stdin=__A ,timeout=__A ,quiet=__A ,echo=__A ) ) __UpperCamelCase = """ """.join(__A ) if result.returncode > 0: __UpperCamelCase = """\n""".join(result.stderr ) raise RuntimeError( f"'{cmd_str}' failed with returncode {result.returncode}\n\n" f"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f"'{cmd_str}' produced no output." ) return result def _lowercase ( ): '''simple docstring''' __UpperCamelCase = os.environ.get("""PYTEST_XDIST_WORKER""" ,"""gw0""" ) __UpperCamelCase = re.sub(R"""^gw""" ,"""""" ,__A ,0 ,re.M ) return int(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = 29_500 __UpperCamelCase = pytest_xdist_worker_id() return port + uniq_delta
349
1
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available a__ : int = logging.getLogger(__name__) @dataclass class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 @dataclass class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''train''' __SCREAMING_SNAKE_CASE = '''dev''' __SCREAMING_SNAKE_CASE = '''test''' class UpperCAmelCase__ : @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> List[InputExample]: raise NotImplementedError @staticmethod def __lowerCamelCase ( lowercase ) -> List[str]: raise NotImplementedError @staticmethod def __lowerCamelCase ( lowercase , lowercase , lowercase , lowercase , lowercase=False , lowercase="[CLS]" , lowercase=1 , lowercase="[SEP]" , lowercase=False , lowercase=False , lowercase=0 , lowercase=0 , lowercase=-1_0_0 , lowercase=0 , lowercase=True , ) -> List[InputFeatures]: __UpperCamelCase = {label: i for i, label in enumerate(lowercase )} __UpperCamelCase = [] for ex_index, example in enumerate(lowercase ): if ex_index % 1_0_0_0_0 == 0: logger.info("""Writing example %d of %d""" , lowercase , len(lowercase ) ) __UpperCamelCase = [] __UpperCamelCase = [] for word, label in zip(example.words , example.labels ): __UpperCamelCase = tokenizer.tokenize(lowercase ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(lowercase ) > 0: tokens.extend(lowercase ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(lowercase ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __UpperCamelCase = tokenizer.num_special_tokens_to_add() if len(lowercase ) > max_seq_length - special_tokens_count: __UpperCamelCase = tokens[: (max_seq_length - special_tokens_count)] __UpperCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __UpperCamelCase = [sequence_a_segment_id] * len(lowercase ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __UpperCamelCase = [cls_token] + tokens __UpperCamelCase = [pad_token_label_id] + label_ids __UpperCamelCase = [cls_token_segment_id] + segment_ids __UpperCamelCase = tokenizer.convert_tokens_to_ids(lowercase ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __UpperCamelCase = [1 if mask_padding_with_zero else 0] * len(lowercase ) # Zero-pad up to the sequence length. __UpperCamelCase = max_seq_length - len(lowercase ) if pad_on_left: __UpperCamelCase = ([pad_token] * padding_length) + input_ids __UpperCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __UpperCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __UpperCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(lowercase ) == max_seq_length assert len(lowercase ) == max_seq_length assert len(lowercase ) == max_seq_length assert len(lowercase ) == max_seq_length if ex_index < 5: logger.info("""*** Example ***""" ) logger.info("""guid: %s""" , example.guid ) logger.info("""tokens: %s""" , """ """.join([str(lowercase ) for x in tokens] ) ) logger.info("""input_ids: %s""" , """ """.join([str(lowercase ) for x in input_ids] ) ) logger.info("""input_mask: %s""" , """ """.join([str(lowercase ) for x in input_mask] ) ) logger.info("""segment_ids: %s""" , """ """.join([str(lowercase ) for x in segment_ids] ) ) logger.info("""label_ids: %s""" , """ """.join([str(lowercase ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __UpperCamelCase = None features.append( InputFeatures( input_ids=lowercase , attention_mask=lowercase , token_type_ids=lowercase , label_ids=lowercase ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = nn.CrossEntropyLoss().ignore_index def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase = None , lowercase=False , lowercase = Split.train , ) -> str: # Load data features from cache or dataset file __UpperCamelCase = os.path.join( lowercase , """cached_{}_{}_{}""".format(mode.value , tokenizer.__class__.__name__ , str(lowercase ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __UpperCamelCase = cached_features_file + """.lock""" with FileLock(lowercase ): if os.path.exists(lowercase ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) __UpperCamelCase = torch.load(lowercase ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) __UpperCamelCase = token_classification_task.read_examples_from_file(lowercase , lowercase ) # TODO clean up all this to leverage built-in features of tokenizers __UpperCamelCase = token_classification_task.convert_examples_to_features( lowercase , lowercase , lowercase , lowercase , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=lowercase , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , lowercase ) def __len__( self ) -> List[Any]: return len(self.features ) def __getitem__( self , lowercase ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = -1_0_0 def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase = None , lowercase=False , lowercase = Split.train , ) -> List[Any]: __UpperCamelCase = token_classification_task.read_examples_from_file(lowercase , lowercase ) # TODO clean up all this to leverage built-in features of tokenizers __UpperCamelCase = token_classification_task.convert_examples_to_features( lowercase , lowercase , lowercase , lowercase , cls_token_at_end=bool(model_type in ["""xlnet"""] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ["""xlnet"""] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=lowercase , pad_on_left=bool(tokenizer.padding_side == """left""" ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __UpperCamelCase = tf.data.Dataset.from_generator( lowercase , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa}, tf.intaa) , ( {"""input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __UpperCamelCase = tf.data.Dataset.from_generator( lowercase , ({"""input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa}, tf.intaa) , ( { """input_ids""": tf.TensorShape([None] ), """attention_mask""": tf.TensorShape([None] ), """token_type_ids""": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self ) -> str: return len(self.features ) def __getitem__( self , lowercase ) -> InputFeatures: return self.features[i]
349
'''simple docstring''' import re def _lowercase ( __A ): '''simple docstring''' return [char.split() for char in re.split(R"""[^ a-z A-Z 0-9 \s]""" ,str_ )] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = split_input(str_ ) return "".join( ["""""".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' try: __UpperCamelCase = split_input(__A ) if upper: __UpperCamelCase = """""".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __UpperCamelCase = """""".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _lowercase ( __A ): '''simple docstring''' return to_simple_case(__A ) def _lowercase ( __A ): '''simple docstring''' try: __UpperCamelCase = to_simple_case(__A ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""_""" ) def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""-""" ) if __name__ == "__main__": __import__('doctest').testmod()
349
1
'''simple docstring''' def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = len(__A ) print("""The following activities are selected:""" ) # The first activity is always selected __UpperCamelCase = 0 print(__A ,end=""",""" ) # Consider rest of the activities for j in range(__A ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(__A ,end=""",""" ) __UpperCamelCase = j if __name__ == "__main__": import doctest doctest.testmod() a__ : Union[str, Any] = [1, 3, 0, 5, 8, 5] a__ : Union[str, Any] = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
349
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCamelCase ( self ) -> int: __UpperCamelCase = 1 __UpperCamelCase = 3 __UpperCamelCase = (3_2, 3_2) __UpperCamelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowercase ) return image @property def __lowerCamelCase ( self ) -> Dict: torch.manual_seed(0 ) __UpperCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) return model @property def __lowerCamelCase ( self ) -> List[str]: torch.manual_seed(0 ) __UpperCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def __lowerCamelCase ( self ) -> Optional[int]: torch.manual_seed(0 ) __UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(lowercase ) @property def __lowerCamelCase ( self ) -> Tuple: def extract(*lowercase , **lowercase ): class UpperCAmelCase__ : def __init__( self ) -> Tuple: __UpperCamelCase = torch.ones([0] ) def __lowerCamelCase ( self , lowercase ) -> List[str]: self.pixel_values.to(lowercase ) return self return Out() return extract def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=lowercase ) assert isinstance(lowercase , lowercase ) assert isinstance(pipe.scheduler , lowercase ) assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowercase ) __UpperCamelCase = StableDiffusionPipeline.from_pretrained(lowercase ) # sanity check that the pipeline still works assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 __UpperCamelCase = unet.half() __UpperCamelCase = vae.half() __UpperCamelCase = bert.half() # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 6_4, 6_4, 3) @nightly @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) __UpperCamelCase = 4_0_0_3_6_6_0_3_4_6 __UpperCamelCase = 7 # without safety guidance (sld_guidance_scale = 0) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """padme amidala taking a bath artwork, safe for work, no nudity""" __UpperCamelCase = 2_7_3_4_9_7_1_7_5_5 __UpperCamelCase = 7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) __UpperCamelCase = 1_0_4_4_3_5_5_2_3_4 __UpperCamelCase = 1_2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
349
1
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 class UpperCAmelCase__ : def __init__( self , lowercase ) -> int: __UpperCamelCase = [[] for _ in range(lowercase )] __UpperCamelCase = size def __getitem__( self , lowercase ) -> Iterator[Edge]: return iter(self._graph[vertex] ) @property def __lowerCamelCase ( self ) -> Union[str, Any]: return self._size def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Tuple: if weight not in (0, 1): raise ValueError("""Edge weight must be either 0 or 1.""" ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("""Vertex indexes must be in [0; size).""" ) self._graph[from_vertex].append(Edge(lowercase , lowercase ) ) def __lowerCamelCase ( self , lowercase , lowercase ) -> int | None: __UpperCamelCase = deque([start_vertex] ) __UpperCamelCase = [None] * self.size __UpperCamelCase = 0 while queue: __UpperCamelCase = queue.popleft() __UpperCamelCase = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: __UpperCamelCase = current_distance + edge.weight __UpperCamelCase = distances[edge.destination_vertex] if ( isinstance(lowercase , lowercase ) and new_distance >= dest_vertex_distance ): continue __UpperCamelCase = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("""No path from start_vertex to finish_vertex.""" ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
349
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> str: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Any: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] )
349
1
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler a__ : int = 1_6 a__ : Any = 3_2 def _lowercase ( __A ,__A = 16 ,__A = "bert-base-cased" ): '''simple docstring''' __UpperCamelCase = AutoTokenizer.from_pretrained(__A ) __UpperCamelCase = load_dataset("""glue""" ,"""mrpc""" ) def tokenize_function(__A ): # max_length=None => use the model max length (it's actually the default) __UpperCamelCase = tokenizer(examples["""sentence1"""] ,examples["""sentence2"""] ,truncation=__A ,max_length=__A ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __UpperCamelCase = datasets.map( __A ,batched=__A ,remove_columns=["""idx""", """sentence1""", """sentence2"""] ,load_from_cache_file=__A ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __UpperCamelCase = tokenized_datasets.rename_column("""label""" ,"""labels""" ) def collate_fn(__A ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__A ,padding="""max_length""" ,max_length=128 ,return_tensors="""pt""" ) return tokenizer.pad(__A ,padding="""longest""" ,return_tensors="""pt""" ) # Instantiate dataloaders. __UpperCamelCase = DataLoader( tokenized_datasets["""train"""] ,shuffle=__A ,collate_fn=__A ,batch_size=__A ) __UpperCamelCase = DataLoader( tokenized_datasets["""validation"""] ,shuffle=__A ,collate_fn=__A ,batch_size=__A ) return train_dataloader, eval_dataloader def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __UpperCamelCase = config["""lr"""] __UpperCamelCase = int(config["""num_epochs"""] ) __UpperCamelCase = int(config["""seed"""] ) __UpperCamelCase = int(config["""batch_size"""] ) __UpperCamelCase = args.model_name_or_path set_seed(__A ) __UpperCamelCase , __UpperCamelCase = get_dataloaders(__A ,__A ,__A ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __UpperCamelCase = AutoModelForSequenceClassification.from_pretrained(__A ,return_dict=__A ) # Instantiate optimizer __UpperCamelCase = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __UpperCamelCase = optimizer_cls(params=model.parameters() ,lr=__A ) if accelerator.state.deepspeed_plugin is not None: __UpperCamelCase = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: __UpperCamelCase = 1 __UpperCamelCase = (len(__A ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): __UpperCamelCase = get_linear_schedule_with_warmup( optimizer=__A ,num_warmup_steps=0 ,num_training_steps=__A ,) else: __UpperCamelCase = DummyScheduler(__A ,total_num_steps=__A ,warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = accelerator.prepare( __A ,__A ,__A ,__A ,__A ) # We need to keep track of how many total steps we have iterated over __UpperCamelCase = 0 # We also need to keep track of the stating epoch so files are named properly __UpperCamelCase = 0 # Now we train the model __UpperCamelCase = evaluate.load("""glue""" ,"""mrpc""" ) __UpperCamelCase = 0 __UpperCamelCase = {} for epoch in range(__A ,__A ): model.train() for step, batch in enumerate(__A ): __UpperCamelCase = model(**__A ) __UpperCamelCase = outputs.loss __UpperCamelCase = loss / gradient_accumulation_steps accelerator.backward(__A ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() __UpperCamelCase = 0 for step, batch in enumerate(__A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __UpperCamelCase = model(**__A ) __UpperCamelCase = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times __UpperCamelCase , __UpperCamelCase = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__A ) - 1: __UpperCamelCase = predictions[: len(eval_dataloader.dataset ) - samples_seen] __UpperCamelCase = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__A ,references=__A ,) __UpperCamelCase = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" ,__A ) __UpperCamelCase = eval_metric["""accuracy"""] if best_performance < eval_metric["accuracy"]: __UpperCamelCase = eval_metric["""accuracy"""] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f"Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir ,"""all_results.json""" ) ,"""w""" ) as f: json.dump(__A ,__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" ,type=__A ,default="""bert-base-cased""" ,help="""Path to pretrained model or model identifier from huggingface.co/models.""" ,required=__A ,) parser.add_argument( """--output_dir""" ,type=__A ,default=""".""" ,help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" ,) parser.add_argument( """--performance_lower_bound""" ,type=__A ,default=__A ,help="""Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.""" ,) parser.add_argument( """--num_epochs""" ,type=__A ,default=3 ,help="""Number of train epochs.""" ,) __UpperCamelCase = parser.parse_args() __UpperCamelCase = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16} training_function(__A ,__A ) if __name__ == "__main__": main()
349
'''simple docstring''' import logging import os from .state import PartialState class UpperCAmelCase__ ( logging.LoggerAdapter): @staticmethod def __lowerCamelCase ( lowercase ) -> Dict: __UpperCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __lowerCamelCase ( self , lowercase , lowercase , *lowercase , **lowercase ) -> List[str]: if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) __UpperCamelCase = kwargs.pop("""main_process_only""" , lowercase ) __UpperCamelCase = kwargs.pop("""in_order""" , lowercase ) if self.isEnabledFor(lowercase ): if self._should_log(lowercase ): __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) elif in_order: __UpperCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) state.wait_for_everyone() def _lowercase ( __A ,__A = None ): '''simple docstring''' if log_level is None: __UpperCamelCase = os.environ.get("""ACCELERATE_LOG_LEVEL""" ,__A ) __UpperCamelCase = logging.getLogger(__A ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__A ,{} )
349
1
'''simple docstring''' import random def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = a[left_index] __UpperCamelCase = left_index + 1 for j in range(left_index + 1 ,__A ): if a[j] < pivot: __UpperCamelCase , __UpperCamelCase = a[i], a[j] i += 1 __UpperCamelCase , __UpperCamelCase = a[i - 1], a[left_index] return i - 1 def _lowercase ( __A ,__A ,__A ): '''simple docstring''' if left < right: __UpperCamelCase = random.randint(__A ,right - 1 ) __UpperCamelCase , __UpperCamelCase = ( a[left], a[pivot], ) # switches the pivot with the left most bound __UpperCamelCase = partition(__A ,__A ,__A ) quick_sort_random( __A ,__A ,__A ) # recursive quicksort to the left of the pivot point quick_sort_random( __A ,pivot_index + 1 ,__A ) # recursive quicksort to the right of the pivot point def _lowercase ( ): '''simple docstring''' __UpperCamelCase = input("""Enter numbers separated by a comma:\n""" ).strip() __UpperCamelCase = [int(__A ) for item in user_input.split(""",""" )] quick_sort_random(__A ,0 ,len(__A ) ) print(__A ) if __name__ == "__main__": main()
349
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase__ : def __init__( self ) -> Any: __UpperCamelCase = False def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase ) -> str: if not self.initialized: __UpperCamelCase = RagRetriever( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = True def __lowerCamelCase ( self ) -> Optional[Any]: self.retriever.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.retriever._main_retrieve(lowercase , lowercase ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase=None ) -> List[Any]: if index is not None and index.is_initialized() and len(lowercase ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowercase , lowercase , lowercase , lowercase ) for worker in self.retrieval_workers ] ) def __lowerCamelCase ( self ) -> Dict: logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> List[str]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCamelCase = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCamelCase , __UpperCamelCase = ray.get(random_worker.retrieve.remote(lowercase , lowercase ) ) else: __UpperCamelCase , __UpperCamelCase = self._main_retrieve(lowercase , lowercase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase=None , **lowercase ) -> Any: return super(lowercase , cls ).get_tokenizers(lowercase , lowercase , **lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase=None , **lowercase ) -> int: __UpperCamelCase = kwargs.pop("""config""" , lowercase ) or RagConfig.from_pretrained(lowercase , **lowercase ) __UpperCamelCase = RagTokenizer.from_pretrained(lowercase , config=lowercase ) __UpperCamelCase = rag_tokenizer.question_encoder __UpperCamelCase = rag_tokenizer.generator if indexed_dataset is not None: __UpperCamelCase = """custom""" __UpperCamelCase = CustomHFIndex(config.retrieval_vector_size , lowercase ) else: __UpperCamelCase = cls._build_index(lowercase ) return cls( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , retrieval_workers=lowercase , index=lowercase , )
349
1
'''simple docstring''' import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class UpperCAmelCase__ ( nn.Module): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 0.0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = jnp.floataa def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = [] __UpperCamelCase = [] for i in range(self.num_layers ): __UpperCamelCase = self.in_channels if i == 0 else self.out_channels __UpperCamelCase = FlaxResnetBlockaD( in_channels=lowercase , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowercase ) __UpperCamelCase = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowercase ) __UpperCamelCase = resnets __UpperCamelCase = attentions if self.add_downsample: __UpperCamelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , lowercase , lowercase , lowercase , lowercase=True ) -> Dict: __UpperCamelCase = () for resnet, attn in zip(self.resnets , self.attentions ): __UpperCamelCase = resnet(lowercase , lowercase , deterministic=lowercase ) __UpperCamelCase = attn(lowercase , lowercase , deterministic=lowercase ) output_states += (hidden_states,) if self.add_downsample: __UpperCamelCase = self.downsamplers_a(lowercase ) output_states += (hidden_states,) return hidden_states, output_states class UpperCAmelCase__ ( nn.Module): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 0.0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = jnp.floataa def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = [] for i in range(self.num_layers ): __UpperCamelCase = self.in_channels if i == 0 else self.out_channels __UpperCamelCase = FlaxResnetBlockaD( in_channels=lowercase , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowercase ) __UpperCamelCase = resnets if self.add_downsample: __UpperCamelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , lowercase , lowercase , lowercase=True ) -> Any: __UpperCamelCase = () for resnet in self.resnets: __UpperCamelCase = resnet(lowercase , lowercase , deterministic=lowercase ) output_states += (hidden_states,) if self.add_downsample: __UpperCamelCase = self.downsamplers_a(lowercase ) output_states += (hidden_states,) return hidden_states, output_states class UpperCAmelCase__ ( nn.Module): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 0.0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = jnp.floataa def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = [] __UpperCamelCase = [] for i in range(self.num_layers ): __UpperCamelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels __UpperCamelCase = self.prev_output_channel if i == 0 else self.out_channels __UpperCamelCase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowercase ) __UpperCamelCase = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowercase ) __UpperCamelCase = resnets __UpperCamelCase = attentions if self.add_upsample: __UpperCamelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , lowercase , lowercase , lowercase , lowercase , lowercase=True ) -> Any: for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states __UpperCamelCase = res_hidden_states_tuple[-1] __UpperCamelCase = res_hidden_states_tuple[:-1] __UpperCamelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) __UpperCamelCase = resnet(lowercase , lowercase , deterministic=lowercase ) __UpperCamelCase = attn(lowercase , lowercase , deterministic=lowercase ) if self.add_upsample: __UpperCamelCase = self.upsamplers_a(lowercase ) return hidden_states class UpperCAmelCase__ ( nn.Module): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 0.0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = jnp.floataa def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = [] for i in range(self.num_layers ): __UpperCamelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels __UpperCamelCase = self.prev_output_channel if i == 0 else self.out_channels __UpperCamelCase = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowercase ) __UpperCamelCase = resnets if self.add_upsample: __UpperCamelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self , lowercase , lowercase , lowercase , lowercase=True ) -> Tuple: for resnet in self.resnets: # pop res hidden states __UpperCamelCase = res_hidden_states_tuple[-1] __UpperCamelCase = res_hidden_states_tuple[:-1] __UpperCamelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) __UpperCamelCase = resnet(lowercase , lowercase , deterministic=lowercase ) if self.add_upsample: __UpperCamelCase = self.upsamplers_a(lowercase ) return hidden_states class UpperCAmelCase__ ( nn.Module): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = 0.0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = jnp.floataa def __lowerCamelCase ( self ) -> Optional[Any]: # there is always at least one resnet __UpperCamelCase = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] __UpperCamelCase = [] for _ in range(self.num_layers ): __UpperCamelCase = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(lowercase ) __UpperCamelCase = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(lowercase ) __UpperCamelCase = resnets __UpperCamelCase = attentions def __call__( self , lowercase , lowercase , lowercase , lowercase=True ) -> Dict: __UpperCamelCase = self.resnets[0](lowercase , lowercase ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): __UpperCamelCase = attn(lowercase , lowercase , deterministic=lowercase ) __UpperCamelCase = resnet(lowercase , lowercase , deterministic=lowercase ) return hidden_states
349
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : Any = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': 5_1_2, 'squeezebert/squeezebert-mnli': 5_1_2, 'squeezebert/squeezebert-mnli-headless': 5_1_2, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class UpperCAmelCase__ ( UpperCAmelCase_): __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 = SqueezeBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> Tuple: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) __UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowercase ) != tokenize_chinese_chars ): __UpperCamelCase = getattr(lowercase , normalizer_state.pop("""type""" ) ) __UpperCamelCase = do_lower_case __UpperCamelCase = strip_accents __UpperCamelCase = tokenize_chinese_chars __UpperCamelCase = normalizer_class(**lowercase ) __UpperCamelCase = do_lower_case def __lowerCamelCase ( self , lowercase , lowercase=None ) -> Tuple: __UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __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 __lowerCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: __UpperCamelCase = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
349
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() a__ : Tuple = logging.get_logger(__name__) def _lowercase ( __A ,__A=False ,__A=False ,__A=False ): '''simple docstring''' __UpperCamelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"transformer.blocks.{i}.norm1.weight", f"vilt.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"transformer.blocks.{i}.norm1.bias", f"vilt.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (f"transformer.blocks.{i}.attn.proj.weight", f"vilt.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append( (f"transformer.blocks.{i}.attn.proj.bias", f"vilt.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"transformer.blocks.{i}.norm2.weight", f"vilt.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"transformer.blocks.{i}.norm2.bias", f"vilt.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append( (f"transformer.blocks.{i}.mlp.fc1.weight", f"vilt.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"transformer.blocks.{i}.mlp.fc1.bias", f"vilt.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"transformer.blocks.{i}.mlp.fc2.weight", f"vilt.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"transformer.blocks.{i}.mlp.fc2.bias", f"vilt.encoder.layer.{i}.output.dense.bias") ) # embeddings rename_keys.extend( [ # text embeddings ("""text_embeddings.word_embeddings.weight""", """vilt.embeddings.text_embeddings.word_embeddings.weight"""), ( """text_embeddings.position_embeddings.weight""", """vilt.embeddings.text_embeddings.position_embeddings.weight""", ), ("""text_embeddings.position_ids""", """vilt.embeddings.text_embeddings.position_ids"""), ( """text_embeddings.token_type_embeddings.weight""", """vilt.embeddings.text_embeddings.token_type_embeddings.weight""", ), ("""text_embeddings.LayerNorm.weight""", """vilt.embeddings.text_embeddings.LayerNorm.weight"""), ("""text_embeddings.LayerNorm.bias""", """vilt.embeddings.text_embeddings.LayerNorm.bias"""), # patch embeddings ("""transformer.cls_token""", """vilt.embeddings.cls_token"""), ("""transformer.patch_embed.proj.weight""", """vilt.embeddings.patch_embeddings.projection.weight"""), ("""transformer.patch_embed.proj.bias""", """vilt.embeddings.patch_embeddings.projection.bias"""), ("""transformer.pos_embed""", """vilt.embeddings.position_embeddings"""), # token type embeddings ("""token_type_embeddings.weight""", """vilt.embeddings.token_type_embeddings.weight"""), ] ) # final layernorm + pooler rename_keys.extend( [ ("""transformer.norm.weight""", """vilt.layernorm.weight"""), ("""transformer.norm.bias""", """vilt.layernorm.bias"""), ("""pooler.dense.weight""", """vilt.pooler.dense.weight"""), ("""pooler.dense.bias""", """vilt.pooler.dense.bias"""), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ("""vqa_classifier.0.weight""", """classifier.0.weight"""), ("""vqa_classifier.0.bias""", """classifier.0.bias"""), ("""vqa_classifier.1.weight""", """classifier.1.weight"""), ("""vqa_classifier.1.bias""", """classifier.1.bias"""), ("""vqa_classifier.3.weight""", """classifier.3.weight"""), ("""vqa_classifier.3.bias""", """classifier.3.bias"""), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ("""nlvr2_classifier.0.weight""", """classifier.0.weight"""), ("""nlvr2_classifier.0.bias""", """classifier.0.bias"""), ("""nlvr2_classifier.1.weight""", """classifier.1.weight"""), ("""nlvr2_classifier.1.bias""", """classifier.1.bias"""), ("""nlvr2_classifier.3.weight""", """classifier.3.weight"""), ("""nlvr2_classifier.3.bias""", """classifier.3.bias"""), ] ) else: pass return rename_keys def _lowercase ( __A ,__A ): '''simple docstring''' for i in range(config.num_hidden_layers ): __UpperCamelCase = """vilt.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __UpperCamelCase = state_dict.pop(f"transformer.blocks.{i}.attn.qkv.weight" ) __UpperCamelCase = state_dict.pop(f"transformer.blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict __UpperCamelCase = in_proj_weight[ : config.hidden_size, : ] __UpperCamelCase = in_proj_bias[: config.hidden_size] __UpperCamelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __UpperCamelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __UpperCamelCase = in_proj_weight[ -config.hidden_size :, : ] __UpperCamelCase = in_proj_bias[-config.hidden_size :] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__A ,__A ) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dct.pop(__A ) __UpperCamelCase = val @torch.no_grad() def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = ViltConfig(image_size=384 ,patch_size=32 ,tie_word_embeddings=__A ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False if "vqa" in checkpoint_url: __UpperCamelCase = True __UpperCamelCase = 3_129 __UpperCamelCase = """huggingface/label-files""" __UpperCamelCase = """vqa2-id2label.json""" __UpperCamelCase = json.load(open(hf_hub_download(__A ,__A ,repo_type="""dataset""" ) ,"""r""" ) ) __UpperCamelCase = {int(__A ): v for k, v in idalabel.items()} __UpperCamelCase = idalabel __UpperCamelCase = {v: k for k, v in idalabel.items()} __UpperCamelCase = ViltForQuestionAnswering(__A ) elif "nlvr" in checkpoint_url: __UpperCamelCase = True __UpperCamelCase = 2 __UpperCamelCase = {0: """False""", 1: """True"""} __UpperCamelCase = {v: k for k, v in config.idalabel.items()} __UpperCamelCase = 3 __UpperCamelCase = ViltForImagesAndTextClassification(__A ) elif "irtr" in checkpoint_url: __UpperCamelCase = True __UpperCamelCase = ViltForImageAndTextRetrieval(__A ) elif "mlm_itm" in checkpoint_url: __UpperCamelCase = True __UpperCamelCase = ViltForMaskedLM(__A ) else: raise ValueError("""Unknown model type""" ) # load state_dict of original model, remove and rename some keys __UpperCamelCase = torch.hub.load_state_dict_from_url(__A ,map_location="""cpu""" )["""state_dict"""] __UpperCamelCase = create_rename_keys(__A ,__A ,__A ,__A ) for src, dest in rename_keys: rename_key(__A ,__A ,__A ) read_in_q_k_v(__A ,__A ) if mlm_model or irtr_model: __UpperCamelCase = ["""itm_score.fc.weight""", """itm_score.fc.bias"""] for k in ignore_keys: state_dict.pop(__A ,__A ) # load state dict into HuggingFace model model.eval() if mlm_model: __UpperCamelCase , __UpperCamelCase = model.load_state_dict(__A ,strict=__A ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(__A ) # Define processor __UpperCamelCase = ViltImageProcessor(size=384 ) __UpperCamelCase = BertTokenizer.from_pretrained("""bert-base-uncased""" ) __UpperCamelCase = ViltProcessor(__A ,__A ) # Forward pass on example inputs (image + text) if nlvr_model: __UpperCamelCase = Image.open(requests.get("""https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg""" ,stream=__A ).raw ) __UpperCamelCase = Image.open(requests.get("""https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg""" ,stream=__A ).raw ) __UpperCamelCase = ( """The left image contains twice the number of dogs as the right image, and at least two dogs in total are""" """ standing.""" ) __UpperCamelCase = processor(__A ,__A ,return_tensors="""pt""" ) __UpperCamelCase = processor(__A ,__A ,return_tensors="""pt""" ) __UpperCamelCase = model( input_ids=encoding_a.input_ids ,pixel_values=encoding_a.pixel_values ,pixel_values_a=encoding_a.pixel_values ,) else: __UpperCamelCase = Image.open(requests.get("""http://images.cocodataset.org/val2017/000000039769.jpg""" ,stream=__A ).raw ) if mlm_model: __UpperCamelCase = """a bunch of [MASK] laying on a [MASK].""" else: __UpperCamelCase = """How many cats are there?""" __UpperCamelCase = processor(__A ,__A ,return_tensors="""pt""" ) __UpperCamelCase = model(**__A ) # Verify outputs if mlm_model: __UpperCamelCase = torch.Size([1, 11, 30_522] ) __UpperCamelCase = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,__A ,atol=1E-4 ) # verify masked token prediction equals "cats" __UpperCamelCase = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: __UpperCamelCase = torch.Size([1, 3_129] ) __UpperCamelCase = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] ,__A ,atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,__A ,atol=1E-4 ) # verify vqa prediction equals "2" __UpperCamelCase = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: __UpperCamelCase = torch.Size([1, 2] ) __UpperCamelCase = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] ,__A ,atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(__A ).mkdir(exist_ok=__A ) print(f"Saving model and processor to {pytorch_dump_folder_path}" ) model.save_pretrained(__A ) processor.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) a__ : int = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a__ : str = { 'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'], 'processing_trocr': ['TrOCRProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ 'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrOCRForCausalLM', 'TrOCRPreTrainedModel', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor from torchvision.transforms.functional import InterpolationMode import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, ViTImageProcessor, ViTMAEConfig, ViTMAEForPreTraining, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version a__ : Union[str, Any] = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt') @dataclass class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''}) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={'''help''': '''The column name of the images in the files.'''}) __SCREAMING_SNAKE_CASE = field(default=UpperCAmelCase_ , metadata={'''help''': '''A folder containing the training data.'''}) __SCREAMING_SNAKE_CASE = field(default=UpperCAmelCase_ , metadata={'''help''': '''A folder containing the validation data.'''}) __SCREAMING_SNAKE_CASE = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''}) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = {} if self.train_dir is not None: __UpperCamelCase = self.train_dir if self.validation_dir is not None: __UpperCamelCase = self.validation_dir __UpperCamelCase = data_files if data_files else None @dataclass class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''}) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}) __SCREAMING_SNAKE_CASE = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) __SCREAMING_SNAKE_CASE = field(default=UpperCAmelCase_ , metadata={'''help''': '''Name or path of preprocessor config.'''}) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) __SCREAMING_SNAKE_CASE = field( default=0.75 , metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''}) __SCREAMING_SNAKE_CASE = field( default=UpperCAmelCase_ , metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''}) @dataclass class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = field( default=1E-3 , metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''}) def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = torch.stack([example["""pixel_values"""] for example in examples] ) return {"pixel_values": pixel_values} def _lowercase ( ): '''simple docstring''' __UpperCamelCase = HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("""run_mae""" ,__A ,__A ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,datefmt="""%m/%d/%Y %H:%M:%S""" ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __UpperCamelCase = training_args.get_process_log_level() logger.setLevel(__A ) transformers.utils.logging.set_verbosity(__A ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. __UpperCamelCase = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __UpperCamelCase = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Initialize our dataset. __UpperCamelCase = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,data_files=data_args.data_files ,cache_dir=model_args.cache_dir ,use_auth_token=True if model_args.use_auth_token else None ,) # If we don't have a validation split, split off a percentage of train as validation. __UpperCamelCase = None if """validation""" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split ,__A ) and data_args.train_val_split > 0.0: __UpperCamelCase = ds["""train"""].train_test_split(data_args.train_val_split ) __UpperCamelCase = split["""train"""] __UpperCamelCase = split["""test"""] # Load pretrained model and image processor # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __UpperCamelCase = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: __UpperCamelCase = ViTMAEConfig.from_pretrained(model_args.config_name ,**__A ) elif model_args.model_name_or_path: __UpperCamelCase = ViTMAEConfig.from_pretrained(model_args.model_name_or_path ,**__A ) else: __UpperCamelCase = ViTMAEConfig() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(f"Overriding config: {model_args.config_overrides}" ) config.update_from_string(model_args.config_overrides ) logger.info(f"New config: {config}" ) # adapt config config.update( { """mask_ratio""": model_args.mask_ratio, """norm_pix_loss""": model_args.norm_pix_loss, } ) # create image processor if model_args.image_processor_name: __UpperCamelCase = ViTImageProcessor.from_pretrained(model_args.image_processor_name ,**__A ) elif model_args.model_name_or_path: __UpperCamelCase = ViTImageProcessor.from_pretrained(model_args.model_name_or_path ,**__A ) else: __UpperCamelCase = ViTImageProcessor() # create model if model_args.model_name_or_path: __UpperCamelCase = ViTMAEForPreTraining.from_pretrained( model_args.model_name_or_path ,from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) ,config=__A ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) else: logger.info("""Training new model from scratch""" ) __UpperCamelCase = ViTMAEForPreTraining(__A ) if training_args.do_train: __UpperCamelCase = ds["""train"""].column_names else: __UpperCamelCase = ds["""validation"""].column_names if data_args.image_column_name is not None: __UpperCamelCase = data_args.image_column_name elif "image" in column_names: __UpperCamelCase = """image""" elif "img" in column_names: __UpperCamelCase = """img""" else: __UpperCamelCase = column_names[0] # transformations as done in original MAE paper # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py if "shortest_edge" in image_processor.size: __UpperCamelCase = image_processor.size["""shortest_edge"""] else: __UpperCamelCase = (image_processor.size["""height"""], image_processor.size["""width"""]) __UpperCamelCase = Compose( [ Lambda(lambda __A : img.convert("""RGB""" ) if img.mode != "RGB" else img ), RandomResizedCrop(__A ,scale=(0.2, 1.0) ,interpolation=InterpolationMode.BICUBIC ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean ,std=image_processor.image_std ), ] ) def preprocess_images(__A ): __UpperCamelCase = [transforms(__A ) for image in examples[image_column_name]] return examples if training_args.do_train: if "train" not in ds: raise ValueError("""--do_train requires a train dataset""" ) if data_args.max_train_samples is not None: __UpperCamelCase = ds["""train"""].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__A ) if training_args.do_eval: if "validation" not in ds: raise ValueError("""--do_eval requires a validation dataset""" ) if data_args.max_eval_samples is not None: __UpperCamelCase = ( ds["""validation"""].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__A ) # Compute absolute learning rate __UpperCamelCase = ( training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size ) if training_args.base_learning_rate is not None: __UpperCamelCase = training_args.base_learning_rate * total_train_batch_size / 256 # Initialize our trainer __UpperCamelCase = Trainer( model=__A ,args=__A ,train_dataset=ds["""train"""] if training_args.do_train else None ,eval_dataset=ds["""validation"""] if training_args.do_eval else None ,tokenizer=__A ,data_collator=__A ,) # Training if training_args.do_train: __UpperCamelCase = None if training_args.resume_from_checkpoint is not None: __UpperCamelCase = training_args.resume_from_checkpoint elif last_checkpoint is not None: __UpperCamelCase = last_checkpoint __UpperCamelCase = trainer.train(resume_from_checkpoint=__A ) trainer.save_model() trainer.log_metrics("""train""" ,train_result.metrics ) trainer.save_metrics("""train""" ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __UpperCamelCase = trainer.evaluate() trainer.log_metrics("""eval""" ,__A ) trainer.save_metrics("""eval""" ,__A ) # Write model card and (optionally) push to hub __UpperCamelCase = { """tasks""": """masked-auto-encoding""", """dataset""": data_args.dataset_name, """tags""": ["""masked-auto-encoding"""], } if training_args.push_to_hub: trainer.push_to_hub(**__A ) else: trainer.create_model_card(**__A ) def _lowercase ( __A ): '''simple docstring''' main() if __name__ == "__main__": main()
349
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig a__ : Union[str, Any] = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''albert''' def __init__( self , lowercase=3_0_0_0_0 , lowercase=1_2_8 , lowercase=4_0_9_6 , lowercase=1_2 , lowercase=1 , lowercase=6_4 , lowercase=1_6_3_8_4 , lowercase=1 , lowercase="gelu_new" , lowercase=0 , lowercase=0 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=0.1 , lowercase="absolute" , lowercase=0 , lowercase=2 , lowercase=3 , **lowercase , ) -> Any: super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) __UpperCamelCase = vocab_size __UpperCamelCase = embedding_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_hidden_groups __UpperCamelCase = num_attention_heads __UpperCamelCase = inner_group_num __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 = classifier_dropout_prob __UpperCamelCase = position_embedding_type class UpperCAmelCase__ ( UpperCAmelCase_): @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
349
1
'''simple docstring''' import argparse import copy def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} with open(__A ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: __UpperCamelCase = [] _list.append([line.split()[1], line.split()[2]] ) __UpperCamelCase = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: __UpperCamelCase = [] _list.append([line.split()[0], line.split()[2]] ) __UpperCamelCase = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def _lowercase ( __A ,__A ): '''simple docstring''' with open(__A ) as f: __UpperCamelCase = f.read(1 ) __UpperCamelCase = start_node __UpperCamelCase = [] __UpperCamelCase = start_node __UpperCamelCase = 0 while visiting not in first_solution: __UpperCamelCase = 10_000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__A ) and k[0] not in first_solution: __UpperCamelCase = k[1] __UpperCamelCase = k[0] first_solution.append(__A ) __UpperCamelCase = distance_of_first_solution + int(__A ) __UpperCamelCase = best_node first_solution.append(__A ) __UpperCamelCase = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 __UpperCamelCase = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 10_000 ) return first_solution, distance_of_first_solution def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = [] for n in solution[1:-1]: __UpperCamelCase = solution.index(__A ) for kn in solution[1:-1]: __UpperCamelCase = solution.index(__A ) if n == kn: continue __UpperCamelCase = copy.deepcopy(__A ) __UpperCamelCase = kn __UpperCamelCase = n __UpperCamelCase = 0 for k in _tmp[:-1]: __UpperCamelCase = _tmp[_tmp.index(__A ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: __UpperCamelCase = distance + int(i[1] ) _tmp.append(__A ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) __UpperCamelCase = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __A : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = 1 __UpperCamelCase = first_solution __UpperCamelCase = [] __UpperCamelCase = distance_of_first_solution __UpperCamelCase = solution while count <= iters: __UpperCamelCase = find_neighborhood(__A ,__A ) __UpperCamelCase = 0 __UpperCamelCase = neighborhood[index_of_best_solution] __UpperCamelCase = len(__A ) - 1 __UpperCamelCase = False while not found: __UpperCamelCase = 0 while i < len(__A ): if best_solution[i] != solution[i]: __UpperCamelCase = best_solution[i] __UpperCamelCase = solution[i] break __UpperCamelCase = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) __UpperCamelCase = True __UpperCamelCase = best_solution[:-1] __UpperCamelCase = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: __UpperCamelCase = cost __UpperCamelCase = solution else: __UpperCamelCase = index_of_best_solution + 1 __UpperCamelCase = neighborhood[index_of_best_solution] if len(__A ) >= size: tabu_list.pop(0 ) __UpperCamelCase = count + 1 return best_solution_ever, best_cost def _lowercase ( __A=None ): '''simple docstring''' __UpperCamelCase = generate_neighbours(args.File ) __UpperCamelCase , __UpperCamelCase = generate_first_solution( args.File ,__A ) __UpperCamelCase , __UpperCamelCase = tabu_search( __A ,__A ,__A ,args.Iterations ,args.Size ,) print(f"Best solution: {best_sol}, with total distance: {best_cost}." ) if __name__ == "__main__": a__ : str = argparse.ArgumentParser(description='Tabu Search') parser.add_argument( '-f', '--File', type=str, help='Path to the file containing the data', required=True, ) parser.add_argument( '-i', '--Iterations', type=int, help='How many iterations the algorithm should perform', required=True, ) parser.add_argument( '-s', '--Size', type=int, help='Size of the tabu list', required=True ) # Pass the arguments to main method main(parser.parse_args())
349
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _lowercase ( __A ): '''simple docstring''' return (data["data"], data["target"]) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = XGBRegressor(verbosity=0 ,random_state=42 ) xgb.fit(__A ,__A ) # Predict target for test data __UpperCamelCase = xgb.predict(__A ) __UpperCamelCase = predictions.reshape(len(__A ) ,1 ) return predictions def _lowercase ( ): '''simple docstring''' __UpperCamelCase = fetch_california_housing() __UpperCamelCase , __UpperCamelCase = data_handling(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = train_test_split( __A ,__A ,test_size=0.25 ,random_state=1 ) __UpperCamelCase = xgboost(__A ,__A ,__A ) # Error printing print(f"Mean Absolute Error : {mean_absolute_error(__A ,__A )}" ) print(f"Mean Square Error : {mean_squared_error(__A ,__A )}" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
349
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : str = { 'configuration_lilt': ['LILT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LiltConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'LILT_PRETRAINED_MODEL_ARCHIVE_LIST', 'LiltForQuestionAnswering', 'LiltForSequenceClassification', 'LiltForTokenClassification', 'LiltModel', 'LiltPreTrainedModel', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys a__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=2 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=4_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: __UpperCamelCase = TFPegasusModel(config=lowercase ).get_decoder() __UpperCamelCase = inputs_dict["""input_ids"""] __UpperCamelCase = input_ids[:1, :] __UpperCamelCase = inputs_dict["""attention_mask"""][:1, :] __UpperCamelCase = inputs_dict["""head_mask"""] __UpperCamelCase = 1 # first forward pass __UpperCamelCase = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) __UpperCamelCase , __UpperCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __UpperCamelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) __UpperCamelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __UpperCamelCase = model(lowercase , attention_mask=lowercase )[0] __UpperCamelCase = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __UpperCamelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx] __UpperCamelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1E-3 ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,__A=None ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = tf.cast(tf.math.not_equal(__A ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: __UpperCamelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: __UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration,) if is_tf_available() else () __SCREAMING_SNAKE_CASE = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> str: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase__ ( unittest.TestCase): __SCREAMING_SNAKE_CASE = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] __SCREAMING_SNAKE_CASE = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers __SCREAMING_SNAKE_CASE = '''google/pegasus-xsum''' @cached_property def __lowerCamelCase ( self ) -> int: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __lowerCamelCase ( self , **lowercase ) -> Optional[int]: __UpperCamelCase = self.translate_src_text(**lowercase ) assert self.expected_text == generated_words def __lowerCamelCase ( self , **lowercase ) -> Optional[Any]: __UpperCamelCase = self.tokenizer(self.src_text , **lowercase , padding=lowercase , return_tensors="""tf""" ) __UpperCamelCase = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) __UpperCamelCase = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase ) return generated_words @slow def __lowerCamelCase ( self ) -> Dict: self._assert_generated_batch_equal_expected()
349
1
'''simple docstring''' from decimal import Decimal, getcontext from math import ceil, factorial def _lowercase ( __A ): '''simple docstring''' if not isinstance(__A ,__A ): raise TypeError("""Undefined for non-integers""" ) elif precision < 1: raise ValueError("""Undefined for non-natural numbers""" ) __UpperCamelCase = precision __UpperCamelCase = ceil(precision / 14 ) __UpperCamelCase = 426_880 * Decimal(10_005 ).sqrt() __UpperCamelCase = 1 __UpperCamelCase = 13_591_409 __UpperCamelCase = Decimal(__A ) for k in range(1 ,__A ): __UpperCamelCase = factorial(6 * k ) // (factorial(3 * k ) * factorial(__A ) ** 3) linear_term += 545_140_134 exponential_term *= -262_537_412_640_768_000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a__ : Union[str, Any] = 5_0 print(f'''The first {n} digits of pi is: {pi(n)}''')
349
'''simple docstring''' import string def _lowercase ( __A ): '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): __UpperCamelCase = """""" for symbol in message: if symbol in string.ascii_uppercase: __UpperCamelCase = string.ascii_uppercase.find(__A ) __UpperCamelCase = num - key if num < 0: __UpperCamelCase = num + len(string.ascii_uppercase ) __UpperCamelCase = translated + string.ascii_uppercase[num] else: __UpperCamelCase = translated + symbol print(f"Decryption using Key #{key}: {translated}" ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = input("""Encrypted message: """ ) __UpperCamelCase = message.upper() decrypt(__A ) if __name__ == "__main__": import doctest doctest.testmod() main()
349
1
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black a__ : Optional[int] = 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 DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. a__ : Dict = ' \"""\n Output class for the scheduler\'s step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"""\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n' class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , """schedulers/""" ) ) __UpperCamelCase = self.diffusers_dir shutil.copy( os.path.join(lowercase , """src/diffusers/schedulers/scheduling_ddpm.py""" ) , os.path.join(self.diffusers_dir , """schedulers/scheduling_ddpm.py""" ) , ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = """src/diffusers""" shutil.rmtree(self.diffusers_dir ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase=None ) -> Optional[Any]: __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_1_9 ) __UpperCamelCase = black.format_str(lowercase , mode=lowercase ) __UpperCamelCase = os.path.join(self.diffusers_dir , """new_code.py""" ) with open(lowercase , """w""" , newline="""\n""" ) as f: f.write(lowercase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(lowercase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=lowercase ) with open(lowercase , """r""" ) as f: self.assertTrue(f.read() , lowercase ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = check_copies.find_code_in_diffusers("""schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ) self.assertEqual(lowercase , lowercase ) def __lowerCamelCase ( self ) -> str: # Base copy consistency self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , lowercase , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , re.sub("""DDPM""" , """Test""" , lowercase ) , ) # Copy consistency with a really long name __UpperCamelCase = """TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f"# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}" , f"{long_class_name}SchedulerOutput" , re.sub("""Bert""" , lowercase , lowercase ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , lowercase , overwrite_result=re.sub("""DDPM""" , """Test""" , lowercase ) , )
349
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : Dict = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''gptj''' __SCREAMING_SNAKE_CASE = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , lowercase=5_0_4_0_0 , lowercase=2_0_4_8 , lowercase=4_0_9_6 , lowercase=2_8 , lowercase=1_6 , lowercase=6_4 , lowercase=None , lowercase="gelu_new" , lowercase=0.0 , lowercase=0.0 , lowercase=0.0 , lowercase=1E-5 , lowercase=0.02 , lowercase=True , lowercase=5_0_2_5_6 , lowercase=5_0_2_5_6 , lowercase=False , **lowercase , ) -> Tuple: __UpperCamelCase = vocab_size __UpperCamelCase = n_positions __UpperCamelCase = n_embd __UpperCamelCase = n_layer __UpperCamelCase = n_head __UpperCamelCase = n_inner __UpperCamelCase = rotary_dim __UpperCamelCase = activation_function __UpperCamelCase = resid_pdrop __UpperCamelCase = embd_pdrop __UpperCamelCase = attn_pdrop __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = initializer_range __UpperCamelCase = use_cache __UpperCamelCase = bos_token_id __UpperCamelCase = eos_token_id super().__init__( bos_token_id=lowercase , eos_token_id=lowercase , tie_word_embeddings=lowercase , **lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase = "default" , lowercase = None , lowercase = False , ) -> List[str]: super().__init__(lowercase , task=lowercase , patching_specs=lowercase , use_past=lowercase ) if not getattr(self._config , """pad_token_id""" , lowercase ): # TODO: how to do that better? __UpperCamelCase = 0 @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: __UpperCamelCase = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(lowercase , direction="""inputs""" ) __UpperCamelCase = {0: """batch""", 1: """past_sequence + sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return common_inputs @property def __lowerCamelCase ( self ) -> int: return self._config.n_layer @property def __lowerCamelCase ( self ) -> int: return self._config.n_head def __lowerCamelCase ( self , lowercase , lowercase = -1 , lowercase = -1 , lowercase = False , lowercase = None , ) -> Mapping[str, Any]: __UpperCamelCase = super(lowercase , self ).generate_dummy_inputs( lowercase , batch_size=lowercase , seq_length=lowercase , is_pair=lowercase , framework=lowercase ) # We need to order the input in the way they appears in the forward() __UpperCamelCase = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __UpperCamelCase , __UpperCamelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __UpperCamelCase = seqlen + 2 __UpperCamelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __UpperCamelCase = [ (torch.zeros(lowercase ), torch.zeros(lowercase )) for _ in range(self.num_layers ) ] __UpperCamelCase = common_inputs["""attention_mask"""] if self.use_past: __UpperCamelCase = ordered_inputs["""attention_mask"""].dtype __UpperCamelCase = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(lowercase , lowercase , dtype=lowercase )] , dim=1 ) return ordered_inputs @property def __lowerCamelCase ( self ) -> int: return 1_3
349
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = SwinvaConfig() __UpperCamelCase = swinva_name.split("""_""" ) __UpperCamelCase = name_split[1] if "to" in name_split[3]: __UpperCamelCase = int(name_split[3][-3:] ) else: __UpperCamelCase = int(name_split[3] ) if "to" in name_split[2]: __UpperCamelCase = int(name_split[2][-2:] ) else: __UpperCamelCase = int(name_split[2][6:] ) if model_size == "tiny": __UpperCamelCase = 96 __UpperCamelCase = (2, 2, 6, 2) __UpperCamelCase = (3, 6, 12, 24) elif model_size == "small": __UpperCamelCase = 96 __UpperCamelCase = (2, 2, 18, 2) __UpperCamelCase = (3, 6, 12, 24) elif model_size == "base": __UpperCamelCase = 128 __UpperCamelCase = (2, 2, 18, 2) __UpperCamelCase = (4, 8, 16, 32) else: __UpperCamelCase = 192 __UpperCamelCase = (2, 2, 18, 2) __UpperCamelCase = (6, 12, 24, 48) if "to" in swinva_name: __UpperCamelCase = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): __UpperCamelCase = 21_841 __UpperCamelCase = """huggingface/label-files""" __UpperCamelCase = """imagenet-22k-id2label.json""" __UpperCamelCase = json.load(open(hf_hub_download(__A ,__A ,repo_type="""dataset""" ) ,"""r""" ) ) __UpperCamelCase = {int(__A ): v for k, v in idalabel.items()} __UpperCamelCase = idalabel __UpperCamelCase = {v: k for k, v in idalabel.items()} else: __UpperCamelCase = 1_000 __UpperCamelCase = """huggingface/label-files""" __UpperCamelCase = """imagenet-1k-id2label.json""" __UpperCamelCase = json.load(open(hf_hub_download(__A ,__A ,repo_type="""dataset""" ) ,"""r""" ) ) __UpperCamelCase = {int(__A ): v for k, v in idalabel.items()} __UpperCamelCase = idalabel __UpperCamelCase = {v: k for k, v in idalabel.items()} __UpperCamelCase = img_size __UpperCamelCase = num_classes __UpperCamelCase = embed_dim __UpperCamelCase = depths __UpperCamelCase = num_heads __UpperCamelCase = window_size return config def _lowercase ( __A ): '''simple docstring''' if "patch_embed.proj" in name: __UpperCamelCase = name.replace("""patch_embed.proj""" ,"""embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: __UpperCamelCase = name.replace("""patch_embed.norm""" ,"""embeddings.norm""" ) if "layers" in name: __UpperCamelCase = """encoder.""" + name if "attn.proj" in name: __UpperCamelCase = name.replace("""attn.proj""" ,"""attention.output.dense""" ) if "attn" in name: __UpperCamelCase = name.replace("""attn""" ,"""attention.self""" ) if "norm1" in name: __UpperCamelCase = name.replace("""norm1""" ,"""layernorm_before""" ) if "norm2" in name: __UpperCamelCase = name.replace("""norm2""" ,"""layernorm_after""" ) if "mlp.fc1" in name: __UpperCamelCase = name.replace("""mlp.fc1""" ,"""intermediate.dense""" ) if "mlp.fc2" in name: __UpperCamelCase = name.replace("""mlp.fc2""" ,"""output.dense""" ) if "q_bias" in name: __UpperCamelCase = name.replace("""q_bias""" ,"""query.bias""" ) if "k_bias" in name: __UpperCamelCase = name.replace("""k_bias""" ,"""key.bias""" ) if "v_bias" in name: __UpperCamelCase = name.replace("""v_bias""" ,"""value.bias""" ) if "cpb_mlp" in name: __UpperCamelCase = name.replace("""cpb_mlp""" ,"""continuous_position_bias_mlp""" ) if name == "norm.weight": __UpperCamelCase = """layernorm.weight""" if name == "norm.bias": __UpperCamelCase = """layernorm.bias""" if "head" in name: __UpperCamelCase = name.replace("""head""" ,"""classifier""" ) else: __UpperCamelCase = """swinv2.""" + name return name def _lowercase ( __A ,__A ): '''simple docstring''' for key in orig_state_dict.copy().keys(): __UpperCamelCase = orig_state_dict.pop(__A ) if "mask" in key: continue elif "qkv" in key: __UpperCamelCase = key.split(""".""" ) __UpperCamelCase = int(key_split[1] ) __UpperCamelCase = int(key_split[3] ) __UpperCamelCase = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: __UpperCamelCase = val[:dim, :] __UpperCamelCase = val[dim : dim * 2, :] __UpperCamelCase = val[-dim:, :] else: __UpperCamelCase = val[:dim] __UpperCamelCase = val[ dim : dim * 2 ] __UpperCamelCase = val[-dim:] else: __UpperCamelCase = val return orig_state_dict def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = timm.create_model(__A ,pretrained=__A ) timm_model.eval() __UpperCamelCase = get_swinva_config(__A ) __UpperCamelCase = SwinvaForImageClassification(__A ) model.eval() __UpperCamelCase = convert_state_dict(timm_model.state_dict() ,__A ) model.load_state_dict(__A ) __UpperCamelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" __UpperCamelCase = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swinva_name.replace("""_""" ,"""-""" ) ) ) __UpperCamelCase = Image.open(requests.get(__A ,stream=__A ).raw ) __UpperCamelCase = image_processor(images=__A ,return_tensors="""pt""" ) __UpperCamelCase = timm_model(inputs["""pixel_values"""] ) __UpperCamelCase = model(**__A ).logits assert torch.allclose(__A ,__A ,atol=1E-3 ) print(f"Saving model {swinva_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__A ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__A ) model.push_to_hub( repo_path_or_name=Path(__A ,__A ) ,organization="""nandwalritik""" ,commit_message="""Add model""" ,) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swinv2_name', default='swinv2_tiny_patch4_window8_256', type=str, help='Name of the Swinv2 timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) a__ : str = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a__ : int = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['LayoutLMv3FeatureExtractor'] a__ : str = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' import pytest a__ : List[str] = '__dummy_dataset1__' a__ : Optional[int] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dataset_loading_script_name __UpperCamelCase = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=__A ) __UpperCamelCase = script_dir / f"{script_name}.py" with open(__A ,"""w""" ) as f: f.write(__A ) return str(__A )
349
'''simple docstring''' def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = len(__A ) __UpperCamelCase = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __UpperCamelCase = True # sum is not zero and set is empty then false for i in range(1 ,required_sum + 1 ): __UpperCamelCase = False for i in range(1 ,arr_len + 1 ): for j in range(1 ,required_sum + 1 ): if arr[i - 1] > j: __UpperCamelCase = subset[i - 1][j] if arr[i - 1] <= j: __UpperCamelCase = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' import math import qiskit def _lowercase ( __A = 1 ,__A = 1 ,__A = 1 ): '''simple docstring''' if ( isinstance(__A ,__A ) or isinstance(__A ,__A ) or isinstance(__A ,__A ) ): raise TypeError("""inputs must be integers.""" ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError("""inputs must be positive.""" ) if ( (math.floor(__A ) != input_a) or (math.floor(__A ) != input_a) or (math.floor(__A ) != carry_in) ): raise ValueError("""inputs must be exact integers.""" ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError("""inputs must be less or equal to 2.""" ) # build registers __UpperCamelCase = qiskit.QuantumRegister(4 ,"""qr""" ) __UpperCamelCase = qiskit.ClassicalRegister(2 ,"""cr""" ) # list the entries __UpperCamelCase = [input_a, input_a, carry_in] __UpperCamelCase = qiskit.QuantumCircuit(__A ,__A ) for i in range(0 ,3 ): if entry[i] == 2: quantum_circuit.h(__A ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(__A ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(__A ) # for 0 entries # build the circuit quantum_circuit.ccx(0 ,1 ,3 ) # ccx = toffoli gate quantum_circuit.cx(0 ,1 ) quantum_circuit.ccx(1 ,2 ,3 ) quantum_circuit.cx(1 ,2 ) quantum_circuit.cx(0 ,1 ) quantum_circuit.measure([2, 3] ,__A ) # measure the last two qbits __UpperCamelCase = qiskit.Aer.get_backend("""aer_simulator""" ) __UpperCamelCase = qiskit.execute(__A ,__A ,shots=1_000 ) return job.result().get_counts(__A ) if __name__ == "__main__": print(f'''Total sum count for state is: {quantum_full_adder(1, 1, 1)}''')
349
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger a__ : Any = get_logger(__name__) class UpperCAmelCase__ : def __init__( self , lowercase = None ) -> List[str]: __UpperCamelCase = ( os.path.join(lowercase , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) __UpperCamelCase = Extractor def __lowerCamelCase ( self , lowercase ) -> str: from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" __UpperCamelCase = os.path.abspath(lowercase ) return os.path.join(self.extract_dir , hash_url_to_filename(lowercase ) ) def __lowerCamelCase ( self , lowercase , lowercase ) -> bool: return force_extract or ( not os.path.isfile(lowercase ) and not (os.path.isdir(lowercase ) and os.listdir(lowercase )) ) def __lowerCamelCase ( self , lowercase , lowercase = False ) -> str: __UpperCamelCase = self.extractor.infer_extractor_format(lowercase ) if not extractor_format: return input_path __UpperCamelCase = self._get_output_path(lowercase ) if self._do_extract(lowercase , lowercase ): self.extractor.extract(lowercase , lowercase , lowercase ) return output_path class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod @abstractmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: ... @staticmethod @abstractmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: ... class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> int: with open(lowercase , """rb""" ) as f: return f.read(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if not magic_number: __UpperCamelCase = max(len(lowercase ) for cls_magic_number in cls.magic_numbers ) try: __UpperCamelCase = cls.read_magic_number(lowercase , lowercase ) except OSError: return False return any(magic_number.startswith(lowercase ) for cls_magic_number in cls.magic_numbers ) class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: return tarfile.is_tarfile(lowercase ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: def resolved(lowercase ) -> str: return os.path.realpath(os.path.abspath(lowercase ) ) def badpath(lowercase , lowercase ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(lowercase , lowercase ) ).startswith(lowercase ) def badlink(lowercase , lowercase ) -> bool: # Links are interpreted relative to the directory containing the link __UpperCamelCase = resolved(os.path.join(lowercase , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=lowercase ) __UpperCamelCase = resolved(lowercase ) for finfo in members: if badpath(finfo.name , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked (illegal path)" ) elif finfo.issym() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}" ) elif finfo.islnk() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}" ) else: yield finfo @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = tarfile.open(lowercase ) tar_file.extractall(lowercase , members=TarExtractor.safemembers(lowercase , lowercase ) ) tar_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x1F\x8B'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with gzip.open(lowercase , """rb""" ) as gzip_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [ B'''PK\x03\x04''', B'''PK\x05\x06''', # empty archive B'''PK\x07\x08''', # spanned archive ] @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if super().is_extractable(lowercase , magic_number=lowercase ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(lowercase , """rb""" ) as fp: __UpperCamelCase = _EndRecData(lowercase ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: __UpperCamelCase = fp.read(lowercase ) # CD is where we expect it to be if len(lowercase ) == sizeCentralDir: __UpperCamelCase = struct.unpack(lowercase , lowercase ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) with zipfile.ZipFile(lowercase , """r""" ) as zip_file: zip_file.extractall(lowercase ) zip_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with lzma.open(lowercase ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = rarfile.RarFile(lowercase ) rf.extractall(lowercase ) rf.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x28\xb5\x2F\xFD'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd __UpperCamelCase = zstd.ZstdDecompressor() with open(lowercase , """rb""" ) as ifh, open(lowercase , """wb""" ) as ofh: dctx.copy_stream(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x42\x5A\x68'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with bza.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(lowercase , exist_ok=lowercase ) with pyazr.SevenZipFile(lowercase , """r""" ) as archive: archive.extractall(lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x04\x22\x4D\x18'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) __SCREAMING_SNAKE_CASE = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def __lowerCamelCase ( cls ) -> Union[str, Any]: return max( len(lowercase ) for extractor in cls.extractors.values() if issubclass(lowercase , lowercase ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: try: return MagicNumberBaseExtractor.read_magic_number(lowercase , magic_number_length=lowercase ) except OSError: return b"" @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = False ) -> bool: warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = cls.infer_extractor_format(lowercase ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def __lowerCamelCase ( cls , lowercase ) -> str: # <Added version="2.4.0"/> __UpperCamelCase = cls._get_magic_number_max_length() __UpperCamelCase = cls._read_magic_number(lowercase , lowercase ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(lowercase , magic_number=lowercase ): return extractor_format @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase = None , lowercase = "deprecated" , ) -> None: os.makedirs(os.path.dirname(lowercase ) , exist_ok=lowercase ) # Prevent parallel extractions __UpperCamelCase = str(Path(lowercase ).with_suffix(""".lock""" ) ) with FileLock(lowercase ): shutil.rmtree(lowercase , ignore_errors=lowercase ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(lowercase , lowercase ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = extractor if extractor != """deprecated""" else extractor_format else: __UpperCamelCase = cls.extractors[extractor_format] return extractor.extract(lowercase , lowercase ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=lowercase , ) for extractor in cls.extractors.values(): if extractor.is_extractable(lowercase ): return extractor.extract(lowercase , lowercase )
349
1
'''simple docstring''' import argparse import collections import os import re 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_table.py a__ : Union[str, Any] = 'src/transformers' a__ : str = 'docs/source/en' a__ : List[str] = '.' def _lowercase ( __A ,__A ,__A ): '''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 # Add here suffixes that are used to identify models, separated by | a__ : Tuple = 'Model|Encoder|Decoder|ForConditionalGeneration' # Regexes that match TF/Flax/PT model names. a__ : List[Any] = re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') a__ : Any = re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. a__ : Optional[int] = re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)') # This is to make sure the transformers module imported is the one in the repo. a__ : List[str] = direct_transformers_import(TRANSFORMERS_PATH) def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)""" ,__A ) return [m.group(0 ) for m in matches] def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = 2 if text == """✅""" or text == """❌""" else len(__A ) __UpperCamelCase = (width - text_length) // 2 __UpperCamelCase = width - text_length - left_indent return " " * left_indent + text + " " * right_indent def _lowercase ( ): '''simple docstring''' __UpperCamelCase = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES __UpperCamelCase = { name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } __UpperCamelCase = {name: config.replace("""Config""" ,"""""" ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. __UpperCamelCase = collections.defaultdict(__A ) __UpperCamelCase = collections.defaultdict(__A ) __UpperCamelCase = collections.defaultdict(__A ) __UpperCamelCase = collections.defaultdict(__A ) __UpperCamelCase = collections.defaultdict(__A ) # Let's lookup through all transformers object (once). for attr_name in dir(__A ): __UpperCamelCase = None if attr_name.endswith("""Tokenizer""" ): __UpperCamelCase = slow_tokenizers __UpperCamelCase = attr_name[:-9] elif attr_name.endswith("""TokenizerFast""" ): __UpperCamelCase = fast_tokenizers __UpperCamelCase = attr_name[:-13] elif _re_tf_models.match(__A ) is not None: __UpperCamelCase = tf_models __UpperCamelCase = _re_tf_models.match(__A ).groups()[0] elif _re_flax_models.match(__A ) is not None: __UpperCamelCase = flax_models __UpperCamelCase = _re_flax_models.match(__A ).groups()[0] elif _re_pt_models.match(__A ) is not None: __UpperCamelCase = pt_models __UpperCamelCase = _re_pt_models.match(__A ).groups()[0] if lookup_dict is not None: while len(__A ) > 0: if attr_name in model_name_to_prefix.values(): __UpperCamelCase = True break # Try again after removing the last word in the name __UpperCamelCase = """""".join(camel_case_split(__A )[:-1] ) # Let's build that table! __UpperCamelCase = list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) __UpperCamelCase = ["""Model""", """Tokenizer slow""", """Tokenizer fast""", """PyTorch support""", """TensorFlow support""", """Flax Support"""] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). __UpperCamelCase = [len(__A ) + 2 for c in columns] __UpperCamelCase = max([len(__A ) for name in model_names] ) + 2 # Build the table per se __UpperCamelCase = """|""" + """|""".join([_center_text(__A ,__A ) for c, w in zip(__A ,__A )] ) + """|\n""" # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([""":""" + """-""" * (w - 2) + """:""" for w in widths] ) + "|\n" __UpperCamelCase = {True: """✅""", False: """❌"""} for name in model_names: __UpperCamelCase = model_name_to_prefix[name] __UpperCamelCase = [ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(__A ,__A ) for l, w in zip(__A ,__A )] ) + "|\n" return table def _lowercase ( __A=False ): '''simple docstring''' __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = _find_text_in_file( filename=os.path.join(__A ,"""index.md""" ) ,start_prompt="""<!--This table is updated automatically from the auto modules""" ,end_prompt="""<!-- End table-->""" ,) __UpperCamelCase = get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(__A ,"""index.md""" ) ,"""w""" ,encoding="""utf-8""" ,newline="""\n""" ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( """The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.""" ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') a__ : List[str] = parser.parse_args() check_model_table(args.fix_and_overwrite)
349
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=5 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=2_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Optional[Any]: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> str: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __UpperCamelCase = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = np.concatenate([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , decoder_attention_mask=lowercase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Any: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase , decoder_attention_mask=lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = np.not_equal(__A ,config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __UpperCamelCase = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape ,dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ).astype(np.inta ), ] ,axis=-1 ,) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __SCREAMING_SNAKE_CASE = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = FlaxPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> List[Any]: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = self._prepare_for_class(lowercase , lowercase ) __UpperCamelCase = model_class(lowercase ) @jax.jit def encode_jitted(lowercase , lowercase=None , **lowercase ): return model.encode(input_ids=lowercase , attention_mask=lowercase ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) __UpperCamelCase = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(lowercase , lowercase , lowercase ): return model.decode( decoder_input_ids=lowercase , decoder_attention_mask=lowercase , encoder_outputs=lowercase , ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __lowerCamelCase ( self ) -> Dict: for model_class_name in self.all_model_classes: __UpperCamelCase = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=lowercase ) __UpperCamelCase = np.ones((1, 1) ) __UpperCamelCase = model(lowercase ) self.assertIsNotNone(lowercase ) @slow def __lowerCamelCase ( self ) -> str: __UpperCamelCase = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] __UpperCamelCase = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] __UpperCamelCase = tokenizer(lowercase , return_tensors="""np""" , truncation=lowercase , max_length=5_1_2 , padding=lowercase ) __UpperCamelCase = model.generate(**lowercase , num_beams=2 ).sequences __UpperCamelCase = tokenizer.batch_decode(lowercase , skip_special_tokens=lowercase ) assert tgt_text == decoded
349
1
'''simple docstring''' import math def _lowercase ( __A ): '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 ,int(math.sqrt(__A ) + 1 ) ,6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowercase ( __A = 10_001 ): '''simple docstring''' try: __UpperCamelCase = int(__A ) except (TypeError, ValueError): raise TypeError("""Parameter nth must be int or castable to int.""" ) from None if nth <= 0: raise ValueError("""Parameter nth must be greater than or equal to one.""" ) __UpperCamelCase = [] __UpperCamelCase = 2 while len(__A ) < nth: if is_prime(__A ): primes.append(__A ) num += 1 else: num += 1 return primes[len(__A ) - 1] if __name__ == "__main__": print(f'''{solution() = }''')
349
'''simple docstring''' import pytest a__ : List[str] = '__dummy_dataset1__' a__ : Optional[int] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dataset_loading_script_name __UpperCamelCase = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=__A ) __UpperCamelCase = script_dir / f"{script_name}.py" with open(__A ,"""w""" ) as f: f.write(__A ) return str(__A )
349
1
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : Dict = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''gptj''' __SCREAMING_SNAKE_CASE = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , lowercase=5_0_4_0_0 , lowercase=2_0_4_8 , lowercase=4_0_9_6 , lowercase=2_8 , lowercase=1_6 , lowercase=6_4 , lowercase=None , lowercase="gelu_new" , lowercase=0.0 , lowercase=0.0 , lowercase=0.0 , lowercase=1E-5 , lowercase=0.02 , lowercase=True , lowercase=5_0_2_5_6 , lowercase=5_0_2_5_6 , lowercase=False , **lowercase , ) -> Tuple: __UpperCamelCase = vocab_size __UpperCamelCase = n_positions __UpperCamelCase = n_embd __UpperCamelCase = n_layer __UpperCamelCase = n_head __UpperCamelCase = n_inner __UpperCamelCase = rotary_dim __UpperCamelCase = activation_function __UpperCamelCase = resid_pdrop __UpperCamelCase = embd_pdrop __UpperCamelCase = attn_pdrop __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = initializer_range __UpperCamelCase = use_cache __UpperCamelCase = bos_token_id __UpperCamelCase = eos_token_id super().__init__( bos_token_id=lowercase , eos_token_id=lowercase , tie_word_embeddings=lowercase , **lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase = "default" , lowercase = None , lowercase = False , ) -> List[str]: super().__init__(lowercase , task=lowercase , patching_specs=lowercase , use_past=lowercase ) if not getattr(self._config , """pad_token_id""" , lowercase ): # TODO: how to do that better? __UpperCamelCase = 0 @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: __UpperCamelCase = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(lowercase , direction="""inputs""" ) __UpperCamelCase = {0: """batch""", 1: """past_sequence + sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return common_inputs @property def __lowerCamelCase ( self ) -> int: return self._config.n_layer @property def __lowerCamelCase ( self ) -> int: return self._config.n_head def __lowerCamelCase ( self , lowercase , lowercase = -1 , lowercase = -1 , lowercase = False , lowercase = None , ) -> Mapping[str, Any]: __UpperCamelCase = super(lowercase , self ).generate_dummy_inputs( lowercase , batch_size=lowercase , seq_length=lowercase , is_pair=lowercase , framework=lowercase ) # We need to order the input in the way they appears in the forward() __UpperCamelCase = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __UpperCamelCase , __UpperCamelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __UpperCamelCase = seqlen + 2 __UpperCamelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __UpperCamelCase = [ (torch.zeros(lowercase ), torch.zeros(lowercase )) for _ in range(self.num_layers ) ] __UpperCamelCase = common_inputs["""attention_mask"""] if self.use_past: __UpperCamelCase = ordered_inputs["""attention_mask"""].dtype __UpperCamelCase = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(lowercase , lowercase , dtype=lowercase )] , dim=1 ) return ordered_inputs @property def __lowerCamelCase ( self ) -> int: return 1_3
349
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } a__ : List[str] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} with open(__A ,"""r""" ) as file: for line_number, line in enumerate(__A ): __UpperCamelCase = line.strip() if line: __UpperCamelCase = line.split() __UpperCamelCase = line_number __UpperCamelCase = words[0] __UpperCamelCase = value return result def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' for attribute in key.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = getattr(__A ,__A ).shape elif weight_type is not None and weight_type == "param": __UpperCamelCase = hf_pointer for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = shape_pointer.shape # let's reduce dimension __UpperCamelCase = value[0] 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 == "param": for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = value else: __UpperCamelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __UpperCamelCase = """.""".join([key, hf_param_name] ) else: __UpperCamelCase = key __UpperCamelCase = value if """lm_head""" in full_key else value[0] a__ : Dict = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _lowercase ( __A ,__A ,__A=None ,__A=None ): '''simple docstring''' __UpperCamelCase = False for key, mapped_key in MAPPING.items(): __UpperCamelCase = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __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: # TODO: don't match quantizer.weight_proj __UpperCamelCase = """weight""" else: __UpperCamelCase = None if hf_dict is not None: rename_dict(__A ,__A ,__A ,__A ,__A ) else: set_recursively(__A ,__A ,__A ,__A ,__A ) return is_used return is_used def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = [] __UpperCamelCase = fairseq_model.state_dict() __UpperCamelCase = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __A ,__A ,__A ,__A ,hf_model.config.feat_extract_norm == """group""" ,) __UpperCamelCase = True else: __UpperCamelCase = load_wavaveca_layer(__A ,__A ,__A ) if not is_used: unused_weights.append(__A ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''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 _lowercase ( __A ,__A ,__A=None ,__A=None ,__A=True ,__A=False ): '''simple docstring''' if config_path is not None: __UpperCamelCase = WavaVecaConfig.from_pretrained(__A ) else: __UpperCamelCase = WavaVecaConfig() if is_seq_class: __UpperCamelCase = read_txt_into_dict(__A ) __UpperCamelCase = idalabel __UpperCamelCase = WavaVecaForSequenceClassification(__A ) __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) feature_extractor.save_pretrained(__A ) elif is_finetuned: if dict_path: __UpperCamelCase = Dictionary.load(__A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase = target_dict.pad_index __UpperCamelCase = target_dict.bos_index __UpperCamelCase = target_dict.eos_index __UpperCamelCase = len(target_dict.symbols ) __UpperCamelCase = os.path.join(__A ,"""vocab.json""" ) if not os.path.isdir(__A ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__A ) ) return os.makedirs(__A ,exist_ok=__A ) __UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCamelCase = 0 __UpperCamelCase = 1 with open(__A ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(__A ,__A ) __UpperCamelCase = WavaVecaCTCTokenizer( __A ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=__A ,) __UpperCamelCase = True if config.feat_extract_norm == """layer""" else False __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) __UpperCamelCase = WavaVecaProcessor(feature_extractor=__A ,tokenizer=__A ) processor.save_pretrained(__A ) __UpperCamelCase = WavaVecaForCTC(__A ) else: __UpperCamelCase = WavaVecaForPreTraining(__A ) if is_finetuned or is_seq_class: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __UpperCamelCase = argparse.Namespace(task="""audio_pretraining""" ) __UpperCamelCase = fairseq.tasks.setup_task(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=__A ) __UpperCamelCase = model[0].eval() recursively_load_weights(__A ,__A ,not is_finetuned ) hf_wavavec.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) a__ : Optional[int] = parser.parse_args() a__ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
349
1
'''simple docstring''' def _lowercase ( __A ): '''simple docstring''' if not isinstance(__A ,__A ): raise TypeError("""only integers accepted as input""" ) else: __UpperCamelCase = str(abs(__A ) ) __UpperCamelCase = [list(__A ) for char in range(len(__A ) )] for index in range(len(__A ) ): num_transpositions[index].pop(__A ) return max( int("""""".join(list(__A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCAmelCase__ : def __init__( self , lowercase , ) -> Union[str, Any]: __UpperCamelCase = parent __UpperCamelCase = 1_3 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = 9_9 __UpperCamelCase = 3_2 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 3_7 __UpperCamelCase = """gelu""" __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 5_1_2 __UpperCamelCase = 1_6 __UpperCamelCase = 2 __UpperCamelCase = 0.02 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = None def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = None if self.use_input_mask: __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = TFDistilBertModel(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]: __UpperCamelCase = TFDistilBertForMaskedLM(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = TFDistilBertForQuestionAnswering(config=lowercase ) __UpperCamelCase = { """input_ids""": input_ids, """attention_mask""": input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForSequenceClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: __UpperCamelCase = self.num_choices __UpperCamelCase = TFDistilBertForMultipleChoice(lowercase ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForTokenClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.prepare_config_and_inputs() ((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFDistilBertModel, '''fill-mask''': TFDistilBertForMaskedLM, '''question-answering''': TFDistilBertForQuestionAnswering, '''text-classification''': TFDistilBertForSequenceClassification, '''token-classification''': TFDistilBertForTokenClassification, '''zero-shot''': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = TFDistilBertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , dim=3_7 ) def __lowerCamelCase ( self ) -> Any: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) @slow def __lowerCamelCase ( self ) -> Tuple: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): __UpperCamelCase = TFDistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_tf class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase = model(lowercase )[0] __UpperCamelCase = [1, 6, 7_6_8] self.assertEqual(output.shape , lowercase ) __UpperCamelCase = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-4 )
349
1
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase__ : def __init__( self ) -> Any: __UpperCamelCase = False def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase ) -> str: if not self.initialized: __UpperCamelCase = RagRetriever( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = True def __lowerCamelCase ( self ) -> Optional[Any]: self.retriever.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.retriever._main_retrieve(lowercase , lowercase ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase=None ) -> List[Any]: if index is not None and index.is_initialized() and len(lowercase ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowercase , lowercase , lowercase , lowercase ) for worker in self.retrieval_workers ] ) def __lowerCamelCase ( self ) -> Dict: logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> List[str]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCamelCase = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCamelCase , __UpperCamelCase = ray.get(random_worker.retrieve.remote(lowercase , lowercase ) ) else: __UpperCamelCase , __UpperCamelCase = self._main_retrieve(lowercase , lowercase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase=None , **lowercase ) -> Any: return super(lowercase , cls ).get_tokenizers(lowercase , lowercase , **lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase=None , **lowercase ) -> int: __UpperCamelCase = kwargs.pop("""config""" , lowercase ) or RagConfig.from_pretrained(lowercase , **lowercase ) __UpperCamelCase = RagTokenizer.from_pretrained(lowercase , config=lowercase ) __UpperCamelCase = rag_tokenizer.question_encoder __UpperCamelCase = rag_tokenizer.generator if indexed_dataset is not None: __UpperCamelCase = """custom""" __UpperCamelCase = CustomHFIndex(config.retrieval_vector_size , lowercase ) else: __UpperCamelCase = cls._build_index(lowercase ) return cls( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , retrieval_workers=lowercase , index=lowercase , )
349
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _lowercase ( __A ,__A ): '''simple docstring''' return math.sqrt(sum(pow(a - b ,2 ) for a, b in zip(__A ,__A ) ) ) def _lowercase ( __A ,__A ): '''simple docstring''' if dataset.ndim != value_array.ndim: __UpperCamelCase = ( """Wrong input data's dimensions... """ f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(__A ) try: if dataset.shape[1] != value_array.shape[1]: __UpperCamelCase = ( """Wrong input data's shape... """ f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(__A ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: __UpperCamelCase = ( """Input data have different datatype... """ f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(__A ) __UpperCamelCase = [] for value in value_array: __UpperCamelCase = euclidean(__A ,dataset[0] ) __UpperCamelCase = dataset[0].tolist() for dataset_value in dataset[1:]: __UpperCamelCase = euclidean(__A ,__A ) if dist > temp_dist: __UpperCamelCase = temp_dist __UpperCamelCase = dataset_value.tolist() answer.append([vector, dist] ) return answer def _lowercase ( __A ,__A ): '''simple docstring''' return np.dot(__A ,__A ) / (norm(__A ) * norm(__A )) if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig a__ : Union[str, Any] = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''albert''' def __init__( self , lowercase=3_0_0_0_0 , lowercase=1_2_8 , lowercase=4_0_9_6 , lowercase=1_2 , lowercase=1 , lowercase=6_4 , lowercase=1_6_3_8_4 , lowercase=1 , lowercase="gelu_new" , lowercase=0 , lowercase=0 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=0.1 , lowercase="absolute" , lowercase=0 , lowercase=2 , lowercase=3 , **lowercase , ) -> Any: super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) __UpperCamelCase = vocab_size __UpperCamelCase = embedding_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_hidden_groups __UpperCamelCase = num_attention_heads __UpperCamelCase = inner_group_num __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 = classifier_dropout_prob __UpperCamelCase = position_embedding_type class UpperCAmelCase__ ( UpperCAmelCase_): @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
349
'''simple docstring''' from datetime import datetime import requests def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = """https://downloadgram.net/wp-json/wppress/video-downloader/video?url=""" __UpperCamelCase = requests.get(base_url + url ).json()[0]["""urls"""][0]["""src"""] return requests.get(__A ).content if __name__ == "__main__": a__ : int = input('Enter Video/IGTV url: ').strip() a__ : int = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4''' with open(file_name, 'wb') as fp: fp.write(download_video(url)) print(f'''Done. Video saved to disk as {file_name}.''')
349
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : Any = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': 5_1_2, 'squeezebert/squeezebert-mnli': 5_1_2, 'squeezebert/squeezebert-mnli-headless': 5_1_2, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class UpperCAmelCase__ ( UpperCAmelCase_): __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 = SqueezeBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> Tuple: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) __UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowercase ) != tokenize_chinese_chars ): __UpperCamelCase = getattr(lowercase , normalizer_state.pop("""type""" ) ) __UpperCamelCase = do_lower_case __UpperCamelCase = strip_accents __UpperCamelCase = tokenize_chinese_chars __UpperCamelCase = normalizer_class(**lowercase ) __UpperCamelCase = do_lower_case def __lowerCamelCase ( self , lowercase , lowercase=None ) -> Tuple: __UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __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 __lowerCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: __UpperCamelCase = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
349
'''simple docstring''' import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowercase ( __A ,__A=False ): '''simple docstring''' try: __UpperCamelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __UpperCamelCase = default else: # KEY is set, convert it to True or False. try: __UpperCamelCase = strtobool(__A ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no." ) return _value a__ : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) a__ : Union[str, Any] = parse_flag_from_env('RUN_REMOTE', default=False) a__ : Any = parse_flag_from_env('RUN_LOCAL', default=True) a__ : List[Any] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a__ : Optional[int] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a__ : Optional[int] = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a__ : Optional[Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a__ : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a__ : str = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a__ : str = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a__ : Tuple = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowercase ( __A ): '''simple docstring''' try: import faiss # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires faiss""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import regex # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires regex""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import elasticsearch # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires elasticsearch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import sqlalchemy # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires sqlalchemy""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TORCH_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires PyTorch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TF_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires TensorFlow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.JAX_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires JAX""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.PIL_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires Pillow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import transformers # noqa F401 except ImportError: return unittest.skip("""test requires transformers""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import tiktoken # noqa F401 except ImportError: return unittest.skip("""test requires tiktoken""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import spacy # noqa F401 except ImportError: return unittest.skip("""test requires spacy""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' def _require_spacy_model(__A ): try: import spacy # noqa F401 spacy.load(__A ) except ImportError: return unittest.skip("""test requires spacy""" )(__A ) except OSError: return unittest.skip("""test requires spacy model '{}'""".format(__A ) )(__A ) else: return test_case return _require_spacy_model def _lowercase ( __A ): '''simple docstring''' try: import pyspark # noqa F401 except ImportError: return unittest.skip("""test requires pyspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import joblibspark # noqa F401 except ImportError: return unittest.skip("""test requires joblibspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_slow_tests or _run_slow_tests == 0: __UpperCamelCase = unittest.skip("""test is slow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_local_tests or _run_local_tests == 0: __UpperCamelCase = unittest.skip("""test is local""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_packaged_tests or _run_packaged_tests == 0: __UpperCamelCase = unittest.skip("""test is packaged""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_remote_tests or _run_remote_tests == 0: __UpperCamelCase = unittest.skip("""test requires remote""" )(__A ) return test_case def _lowercase ( *__A ): '''simple docstring''' def decorate(cls ): for name, fn in cls.__dict__.items(): if callable(__A ) and name.startswith("""test""" ): for decorator in decorators: __UpperCamelCase = decorator(__A ) setattr(cls ,__A ,__A ) return cls return decorate class UpperCAmelCase__ ( UpperCAmelCase_): pass class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 @contextmanager def _lowercase ( __A=OfflineSimulationMode.CONNECTION_FAILS ,__A=1E-16 ): '''simple docstring''' __UpperCamelCase = requests.Session().request def timeout_request(__A ,__A ,__A ,**__A ): # Change the url to an invalid url so that the connection hangs __UpperCamelCase = """https://10.255.255.1""" if kwargs.get("""timeout""" ) is None: raise RequestWouldHangIndefinitelyError( f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) __UpperCamelCase = timeout try: return online_request(__A ,__A ,**__A ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __UpperCamelCase = url __UpperCamelCase = e.args[0] __UpperCamelCase = (max_retry_error.args[0].replace("""10.255.255.1""" ,f"OfflineMock[{url}]" ),) __UpperCamelCase = (max_retry_error,) raise def raise_connection_error(__A ,__A ,**__A ): raise requests.ConnectionError("""Offline mode is enabled.""" ,request=__A ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("""requests.Session.send""" ,__A ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("""requests.Session.request""" ,__A ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,__A ): yield else: raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" ) @contextmanager def _lowercase ( *__A ,**__A ): '''simple docstring''' __UpperCamelCase = str(Path().resolve() ) with tempfile.TemporaryDirectory(*__A ,**__A ) as tmp_dir: try: os.chdir(__A ) yield finally: os.chdir(__A ) @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowercase ( __A ,__A ): '''simple docstring''' return deepcopy(__A ).integers(0 ,100 ,10 ).tolist() == deepcopy(__A ).integers(0 ,100 ,10 ).tolist() def _lowercase ( __A ): '''simple docstring''' import decorator from requests.exceptions import HTTPError def _wrapper(__A ,*__A ,**__A ): try: return func(*__A ,**__A ) except HTTPError as err: if str(__A ).startswith("""500""" ) or str(__A ).startswith("""502""" ): pytest.xfail(str(__A ) ) raise err return decorator.decorator(_wrapper ,__A ) class UpperCAmelCase__ : def __init__( self , lowercase , lowercase , lowercase ) -> str: __UpperCamelCase = returncode __UpperCamelCase = stdout __UpperCamelCase = stderr async def _lowercase ( __A ,__A ): '''simple docstring''' while True: __UpperCamelCase = await stream.readline() if line: callback(__A ) else: break async def _lowercase ( __A ,__A=None ,__A=None ,__A=None ,__A=False ,__A=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(__A ) ) __UpperCamelCase = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=__A ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=__A ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __UpperCamelCase = [] __UpperCamelCase = [] def tee(__A ,__A ,__A ,__A="" ): __UpperCamelCase = line.decode("""utf-8""" ).rstrip() sink.append(__A ) if not quiet: print(__A ,__A ,file=__A ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __A : tee(__A ,__A ,sys.stdout ,label="""stdout:""" ) ), _read_stream(p.stderr ,lambda __A : tee(__A ,__A ,sys.stderr ,label="""stderr:""" ) ), ] ,timeout=__A ,) return _RunOutput(await p.wait() ,__A ,__A ) def _lowercase ( __A ,__A=None ,__A=None ,__A=180 ,__A=False ,__A=True ): '''simple docstring''' __UpperCamelCase = asyncio.get_event_loop() __UpperCamelCase = loop.run_until_complete( _stream_subprocess(__A ,env=__A ,stdin=__A ,timeout=__A ,quiet=__A ,echo=__A ) ) __UpperCamelCase = """ """.join(__A ) if result.returncode > 0: __UpperCamelCase = """\n""".join(result.stderr ) raise RuntimeError( f"'{cmd_str}' failed with returncode {result.returncode}\n\n" f"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f"'{cmd_str}' produced no output." ) return result def _lowercase ( ): '''simple docstring''' __UpperCamelCase = os.environ.get("""PYTEST_XDIST_WORKER""" ,"""gw0""" ) __UpperCamelCase = re.sub(R"""^gw""" ,"""""" ,__A ,0 ,re.M ) return int(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = 29_500 __UpperCamelCase = pytest_xdist_worker_id() return port + uniq_delta
349
1
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification a__ : Optional[Any] = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co a__ : Optional[int] = 'main' # Default branch name a__ : Any = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) a__ : Tuple = 'aaaaaaa' # This commit does not exist, so we should 404. a__ : Any = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes a__ : Any = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def _lowercase ( ): '''simple docstring''' print("""Welcome!""" ) yield print("""Bye!""" ) @contextlib.contextmanager def _lowercase ( ): '''simple docstring''' print("""Bonjour!""" ) yield print("""Au revoir!""" ) class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Union[str, Any]: # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec("""transformers""" ) is not None class UpperCAmelCase__ ( unittest.TestCase): @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __lowerCamelCase ( self , lowercase ) -> int: with ContextManagers([] ): print("""Transformers are awesome!""" ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , """Transformers are awesome!\n""" ) @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __lowerCamelCase ( self , lowercase ) -> Tuple: with ContextManagers([context_en()] ): print("""Transformers are awesome!""" ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , """Welcome!\nTransformers are awesome!\nBye!\n""" ) @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __lowerCamelCase ( self , lowercase ) -> Dict: with ContextManagers([context_fr(), context_en()] ): print("""Transformers are awesome!""" ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , """Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n""" ) @require_torch def __lowerCamelCase ( self ) -> Optional[int]: self.assertEqual(find_labels(lowercase ) , ["""labels"""] ) self.assertEqual(find_labels(lowercase ) , ["""labels""", """next_sentence_label"""] ) self.assertEqual(find_labels(lowercase ) , ["""start_positions""", """end_positions"""] ) class UpperCAmelCase__ ( UpperCAmelCase_): pass self.assertEqual(find_labels(lowercase ) , ["""labels"""] ) @require_tf def __lowerCamelCase ( self ) -> str: self.assertEqual(find_labels(lowercase ) , ["""labels"""] ) self.assertEqual(find_labels(lowercase ) , ["""labels""", """next_sentence_label"""] ) self.assertEqual(find_labels(lowercase ) , ["""start_positions""", """end_positions"""] ) class UpperCAmelCase__ ( UpperCAmelCase_): pass self.assertEqual(find_labels(lowercase ) , ["""labels"""] ) @require_flax def __lowerCamelCase ( self ) -> Optional[int]: # Flax models don't have labels self.assertEqual(find_labels(lowercase ) , [] ) self.assertEqual(find_labels(lowercase ) , [] ) self.assertEqual(find_labels(lowercase ) , [] ) class UpperCAmelCase__ ( UpperCAmelCase_): pass self.assertEqual(find_labels(lowercase ) , [] )
349
'''simple docstring''' import re def _lowercase ( __A ): '''simple docstring''' return [char.split() for char in re.split(R"""[^ a-z A-Z 0-9 \s]""" ,str_ )] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = split_input(str_ ) return "".join( ["""""".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' try: __UpperCamelCase = split_input(__A ) if upper: __UpperCamelCase = """""".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __UpperCamelCase = """""".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _lowercase ( __A ): '''simple docstring''' return to_simple_case(__A ) def _lowercase ( __A ): '''simple docstring''' try: __UpperCamelCase = to_simple_case(__A ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""_""" ) def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""-""" ) if __name__ == "__main__": __import__('doctest').testmod()
349
1
'''simple docstring''' import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class UpperCAmelCase__ ( unittest.TestCase): def __init__( self , lowercase , lowercase=7 , lowercase=3 , lowercase=1_8 , lowercase=3_0 , lowercase=4_0_0 , lowercase=True , lowercase=None , lowercase=True , ) -> Any: __UpperCamelCase = size if size is not None else {"""height""": 1_8, """width""": 1_8} __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = num_channels __UpperCamelCase = image_size __UpperCamelCase = min_resolution __UpperCamelCase = max_resolution __UpperCamelCase = do_resize __UpperCamelCase = size __UpperCamelCase = do_normalize def __lowerCamelCase ( self ) -> str: return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8_866_443_634_033_203, 0.6_618_829_369_544_983, 0.3_891_746_401_786_804], [-0.6_042_559_146_881_104, -0.02_295_008_860_528_469, 0.5_423_797_369_003_296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ImageGPTImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = ImageGPTImageProcessingTester(self ) @property def __lowerCamelCase ( self ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase , """clusters""" ) ) self.assertTrue(hasattr(lowercase , """do_resize""" ) ) self.assertTrue(hasattr(lowercase , """size""" ) ) self.assertTrue(hasattr(lowercase , """do_normalize""" ) ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 1_8, """width""": 1_8} ) __UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {"""height""": 4_2, """width""": 4_2} ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) __UpperCamelCase = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(lowercase , obj[key] ) ) else: self.assertEqual(obj[key] , lowercase ) def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = os.path.join(lowercase , """image_processor.json""" ) image_processor_first.to_json_file(lowercase ) __UpperCamelCase = self.image_processing_class.from_json_file(lowercase ).to_dict() __UpperCamelCase = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(lowercase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , lowercase ) def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(lowercase ) __UpperCamelCase = self.image_processing_class.from_pretrained(lowercase ).to_dict() __UpperCamelCase = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(lowercase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , lowercase ) @unittest.skip("""ImageGPT requires clusters at initialization""" ) def __lowerCamelCase ( self ) -> Optional[int]: pass def _lowercase ( ): '''simple docstring''' __UpperCamelCase = load_dataset("""hf-internal-testing/fixtures_image_utils""" ,split="""test""" ) __UpperCamelCase = Image.open(dataset[4]["""file"""] ) __UpperCamelCase = Image.open(dataset[5]["""file"""] ) __UpperCamelCase = [imagea, imagea] return images @require_vision @require_torch class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = ImageGPTImageProcessor.from_pretrained("""openai/imagegpt-small""" ) __UpperCamelCase = prepare_images() # test non-batched __UpperCamelCase = image_processing(images[0] , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_0_2_4) ) __UpperCamelCase = [3_0_6, 1_9_1, 1_9_1] self.assertEqual(encoding.input_ids[0, :3].tolist() , lowercase ) # test batched __UpperCamelCase = image_processing(lowercase , return_tensors="""pt""" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_0_2_4) ) __UpperCamelCase = [3_0_3, 1_3, 1_3] self.assertEqual(encoding.input_ids[1, -3:].tolist() , lowercase )
349
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCamelCase ( self ) -> int: __UpperCamelCase = 1 __UpperCamelCase = 3 __UpperCamelCase = (3_2, 3_2) __UpperCamelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowercase ) return image @property def __lowerCamelCase ( self ) -> Dict: torch.manual_seed(0 ) __UpperCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) return model @property def __lowerCamelCase ( self ) -> List[str]: torch.manual_seed(0 ) __UpperCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def __lowerCamelCase ( self ) -> Optional[int]: torch.manual_seed(0 ) __UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(lowercase ) @property def __lowerCamelCase ( self ) -> Tuple: def extract(*lowercase , **lowercase ): class UpperCAmelCase__ : def __init__( self ) -> Tuple: __UpperCamelCase = torch.ones([0] ) def __lowerCamelCase ( self , lowercase ) -> List[str]: self.pixel_values.to(lowercase ) return self return Out() return extract def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=lowercase ) assert isinstance(lowercase , lowercase ) assert isinstance(pipe.scheduler , lowercase ) assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowercase ) __UpperCamelCase = StableDiffusionPipeline.from_pretrained(lowercase ) # sanity check that the pipeline still works assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 __UpperCamelCase = unet.half() __UpperCamelCase = vae.half() __UpperCamelCase = bert.half() # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 6_4, 6_4, 3) @nightly @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) __UpperCamelCase = 4_0_0_3_6_6_0_3_4_6 __UpperCamelCase = 7 # without safety guidance (sld_guidance_scale = 0) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """padme amidala taking a bath artwork, safe for work, no nudity""" __UpperCamelCase = 2_7_3_4_9_7_1_7_5_5 __UpperCamelCase = 7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) __UpperCamelCase = 1_0_4_4_3_5_5_2_3_4 __UpperCamelCase = 1_2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
349
1
'''simple docstring''' from collections import deque from math import floor from random import random from time import time class UpperCAmelCase__ : def __init__( self ) -> List[str]: __UpperCamelCase = {} def __lowerCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Optional[int]: if self.graph.get(lowercase ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: __UpperCamelCase = [[w, v]] if not self.graph.get(lowercase ): __UpperCamelCase = [] def __lowerCamelCase ( self ) -> Dict: return list(self.graph ) def __lowerCamelCase ( self , lowercase , lowercase ) -> Optional[Any]: if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) def __lowerCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Union[str, Any]: if s == d: return [] __UpperCamelCase = [] __UpperCamelCase = [] if s == -2: __UpperCamelCase = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) __UpperCamelCase = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __UpperCamelCase = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) __UpperCamelCase = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: __UpperCamelCase = stack[len(lowercase ) - 1] else: __UpperCamelCase = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def __lowerCamelCase ( self , lowercase=-1 ) -> Dict: if c == -1: __UpperCamelCase = floor(random() * 1_0_0_0_0 ) + 1_0 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 1_0_2 ) + 1 ): __UpperCamelCase = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def __lowerCamelCase ( self , lowercase=-2 ) -> Union[str, Any]: __UpperCamelCase = deque() __UpperCamelCase = [] if s == -2: __UpperCamelCase = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: __UpperCamelCase = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __lowerCamelCase ( self , lowercase ) -> str: __UpperCamelCase = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def __lowerCamelCase ( self , lowercase ) -> List[str]: return len(self.graph[u] ) def __lowerCamelCase ( self , lowercase=-2 ) -> List[str]: __UpperCamelCase = [] __UpperCamelCase = [] if s == -2: __UpperCamelCase = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) __UpperCamelCase = s __UpperCamelCase = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __UpperCamelCase = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __UpperCamelCase = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowercase ) != 0: __UpperCamelCase = stack[len(lowercase ) - 1] else: __UpperCamelCase = ss # check if se have reached the starting point if len(lowercase ) == 0: return sorted_nodes def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) __UpperCamelCase = -2 __UpperCamelCase = [] __UpperCamelCase = s __UpperCamelCase = False __UpperCamelCase = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __UpperCamelCase = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __UpperCamelCase = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __UpperCamelCase = node[1] break # check if all the children are visited if s == ss: stack.pop() __UpperCamelCase = True if len(lowercase ) != 0: __UpperCamelCase = stack[len(lowercase ) - 1] else: __UpperCamelCase = False indirect_parents.append(lowercase ) __UpperCamelCase = s __UpperCamelCase = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) __UpperCamelCase = -2 __UpperCamelCase = [] __UpperCamelCase = s __UpperCamelCase = False __UpperCamelCase = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __UpperCamelCase = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __UpperCamelCase = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __UpperCamelCase = node[1] break # check if all the children are visited if s == ss: stack.pop() __UpperCamelCase = True if len(lowercase ) != 0: __UpperCamelCase = stack[len(lowercase ) - 1] else: __UpperCamelCase = False indirect_parents.append(lowercase ) __UpperCamelCase = s __UpperCamelCase = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def __lowerCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Optional[Any]: __UpperCamelCase = time() self.dfs(lowercase , lowercase ) __UpperCamelCase = time() return end - begin def __lowerCamelCase ( self , lowercase=-2 ) -> Dict: __UpperCamelCase = time() self.bfs(lowercase ) __UpperCamelCase = time() return end - begin class UpperCAmelCase__ : def __init__( self ) -> Union[str, Any]: __UpperCamelCase = {} def __lowerCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Union[str, Any]: # check if the u exists if self.graph.get(lowercase ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist __UpperCamelCase = [[w, v]] # add the other way if self.graph.get(lowercase ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist __UpperCamelCase = [[w, u]] def __lowerCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) # the other way round if self.graph.get(lowercase ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowercase ) def __lowerCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> List[str]: if s == d: return [] __UpperCamelCase = [] __UpperCamelCase = [] if s == -2: __UpperCamelCase = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) __UpperCamelCase = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __UpperCamelCase = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) __UpperCamelCase = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: __UpperCamelCase = stack[len(lowercase ) - 1] else: __UpperCamelCase = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def __lowerCamelCase ( self , lowercase=-1 ) -> Dict: if c == -1: __UpperCamelCase = floor(random() * 1_0_0_0_0 ) + 1_0 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 1_0_2 ) + 1 ): __UpperCamelCase = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def __lowerCamelCase ( self , lowercase=-2 ) -> Any: __UpperCamelCase = deque() __UpperCamelCase = [] if s == -2: __UpperCamelCase = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: __UpperCamelCase = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def __lowerCamelCase ( self , lowercase ) -> Any: return len(self.graph[u] ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) __UpperCamelCase = -2 __UpperCamelCase = [] __UpperCamelCase = s __UpperCamelCase = False __UpperCamelCase = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __UpperCamelCase = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __UpperCamelCase = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __UpperCamelCase = node[1] break # check if all the children are visited if s == ss: stack.pop() __UpperCamelCase = True if len(lowercase ) != 0: __UpperCamelCase = stack[len(lowercase ) - 1] else: __UpperCamelCase = False indirect_parents.append(lowercase ) __UpperCamelCase = s __UpperCamelCase = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) __UpperCamelCase = -2 __UpperCamelCase = [] __UpperCamelCase = s __UpperCamelCase = False __UpperCamelCase = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: __UpperCamelCase = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): __UpperCamelCase = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) __UpperCamelCase = node[1] break # check if all the children are visited if s == ss: stack.pop() __UpperCamelCase = True if len(lowercase ) != 0: __UpperCamelCase = stack[len(lowercase ) - 1] else: __UpperCamelCase = False indirect_parents.append(lowercase ) __UpperCamelCase = s __UpperCamelCase = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def __lowerCamelCase ( self ) -> List[Any]: return list(self.graph ) def __lowerCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> List[Any]: __UpperCamelCase = time() self.dfs(lowercase , lowercase ) __UpperCamelCase = time() return end - begin def __lowerCamelCase ( self , lowercase=-2 ) -> List[str]: __UpperCamelCase = time() self.bfs(lowercase ) __UpperCamelCase = time() return end - begin
349
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> str: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Any: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] )
349
1
'''simple docstring''' from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING a__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase_) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , **lowercase ) -> Union[str, Any]: super().__init__(**lowercase ) requires_backends(self , """vision""" ) requires_backends(self , """torch""" ) if self.framework != "pt": raise ValueError(f"The {self.__class__} is only available in PyTorch." ) self.check_model_type(lowercase ) def __lowerCamelCase ( self , **lowercase ) -> Union[str, Any]: __UpperCamelCase = {} __UpperCamelCase = {} __UpperCamelCase = {} # preprocess args if "points_per_batch" in kwargs: __UpperCamelCase = kwargs["""points_per_batch"""] if "points_per_crop" in kwargs: __UpperCamelCase = kwargs["""points_per_crop"""] if "crops_n_layers" in kwargs: __UpperCamelCase = kwargs["""crops_n_layers"""] if "crop_overlap_ratio" in kwargs: __UpperCamelCase = kwargs["""crop_overlap_ratio"""] if "crop_n_points_downscale_factor" in kwargs: __UpperCamelCase = kwargs["""crop_n_points_downscale_factor"""] # postprocess args if "pred_iou_thresh" in kwargs: __UpperCamelCase = kwargs["""pred_iou_thresh"""] if "stability_score_offset" in kwargs: __UpperCamelCase = kwargs["""stability_score_offset"""] if "mask_threshold" in kwargs: __UpperCamelCase = kwargs["""mask_threshold"""] if "stability_score_thresh" in kwargs: __UpperCamelCase = kwargs["""stability_score_thresh"""] if "crops_nms_thresh" in kwargs: __UpperCamelCase = kwargs["""crops_nms_thresh"""] if "output_rle_mask" in kwargs: __UpperCamelCase = kwargs["""output_rle_mask"""] if "output_bboxes_mask" in kwargs: __UpperCamelCase = kwargs["""output_bboxes_mask"""] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , lowercase , *lowercase , lowercase=None , lowercase=None , **lowercase ) -> Union[str, Any]: return super().__call__(lowercase , *lowercase , num_workers=lowercase , batch_size=lowercase , **lowercase ) def __lowerCamelCase ( self , lowercase , lowercase=6_4 , lowercase = 0 , lowercase = 5_1_2 / 1_5_0_0 , lowercase = 3_2 , lowercase = 1 , ) -> Union[str, Any]: __UpperCamelCase = load_image(lowercase ) __UpperCamelCase = self.image_processor.size["""longest_edge"""] __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self.image_processor.generate_crop_boxes( lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) __UpperCamelCase = self.image_processor(images=lowercase , return_tensors="""pt""" ) with self.device_placement(): if self.framework == "pt": __UpperCamelCase = self.get_inference_context() with inference_context(): __UpperCamelCase = self._ensure_tensor_on_device(lowercase , device=self.device ) __UpperCamelCase = self.model.get_image_embeddings(model_inputs.pop("""pixel_values""" ) ) __UpperCamelCase = image_embeddings __UpperCamelCase = grid_points.shape[1] __UpperCamelCase = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( """Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. """ """To return all points at once, set points_per_batch to None""" ) for i in range(0 , lowercase , lowercase ): __UpperCamelCase = grid_points[:, i : i + points_per_batch, :, :] __UpperCamelCase = input_labels[:, i : i + points_per_batch] __UpperCamelCase = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def __lowerCamelCase ( self , lowercase , lowercase=0.88 , lowercase=0.95 , lowercase=0 , lowercase=1 , ) -> Dict: __UpperCamelCase = model_inputs.pop("""input_boxes""" ) __UpperCamelCase = model_inputs.pop("""is_last""" ) __UpperCamelCase = model_inputs.pop("""original_sizes""" ).tolist() __UpperCamelCase = model_inputs.pop("""reshaped_input_sizes""" ).tolist() __UpperCamelCase = self.model(**lowercase ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks __UpperCamelCase = model_outputs["""pred_masks"""] __UpperCamelCase = self.image_processor.post_process_masks( lowercase , lowercase , lowercase , lowercase , binarize=lowercase ) __UpperCamelCase = model_outputs["""iou_scores"""] __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , lowercase , lowercase , lowercase , lowercase , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def __lowerCamelCase ( self , lowercase , lowercase=False , lowercase=False , lowercase=0.7 , ) -> List[Any]: __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = [] for model_output in model_outputs: all_scores.append(model_output.pop("""iou_scores""" ) ) all_masks.extend(model_output.pop("""masks""" ) ) all_boxes.append(model_output.pop("""boxes""" ) ) __UpperCamelCase = torch.cat(lowercase ) __UpperCamelCase = torch.cat(lowercase ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self.image_processor.post_process_for_mask_generation( lowercase , lowercase , lowercase , lowercase ) __UpperCamelCase = defaultdict(lowercase ) for output in model_outputs: for k, v in output.items(): extra[k].append(lowercase ) __UpperCamelCase = {} if output_rle_mask: __UpperCamelCase = rle_mask if output_bboxes_mask: __UpperCamelCase = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
349
'''simple docstring''' import logging import os from .state import PartialState class UpperCAmelCase__ ( logging.LoggerAdapter): @staticmethod def __lowerCamelCase ( lowercase ) -> Dict: __UpperCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __lowerCamelCase ( self , lowercase , lowercase , *lowercase , **lowercase ) -> List[str]: if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) __UpperCamelCase = kwargs.pop("""main_process_only""" , lowercase ) __UpperCamelCase = kwargs.pop("""in_order""" , lowercase ) if self.isEnabledFor(lowercase ): if self._should_log(lowercase ): __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) elif in_order: __UpperCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) state.wait_for_everyone() def _lowercase ( __A ,__A = None ): '''simple docstring''' if log_level is None: __UpperCamelCase = os.environ.get("""ACCELERATE_LOG_LEVEL""" ,__A ) __UpperCamelCase = logging.getLogger(__A ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__A ,{} )
349
1
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput a__ : List[Any] = 8 def _lowercase ( __A ,__A=BITS ): '''simple docstring''' __UpperCamelCase = x.device __UpperCamelCase = (x * 255).int().clamp(0 ,255 ) __UpperCamelCase = 2 ** torch.arange(bits - 1 ,-1 ,-1 ,device=__A ) __UpperCamelCase = rearrange(__A ,"""d -> d 1 1""" ) __UpperCamelCase = rearrange(__A ,"""b c h w -> b c 1 h w""" ) __UpperCamelCase = ((x & mask) != 0).float() __UpperCamelCase = rearrange(__A ,"""b c d h w -> b (c d) h w""" ) __UpperCamelCase = bits * 2 - 1 return bits def _lowercase ( __A ,__A=BITS ): '''simple docstring''' __UpperCamelCase = x.device __UpperCamelCase = (x > 0).int() __UpperCamelCase = 2 ** torch.arange(bits - 1 ,-1 ,-1 ,device=__A ,dtype=torch.intaa ) __UpperCamelCase = rearrange(__A ,"""d -> d 1 1""" ) __UpperCamelCase = rearrange(__A ,"""b (c d) h w -> b c d h w""" ,d=8 ) __UpperCamelCase = reduce(x * mask ,"""b c d h w -> b c h w""" ,"""sum""" ) return (dec / 255).clamp(0.0 ,1.0 ) def _lowercase ( self ,__A ,__A ,__A ,__A = 0.0 ,__A = True ,__A=None ,__A = True ,): '''simple docstring''' if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) __UpperCamelCase = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas __UpperCamelCase = self.alphas_cumprod[timestep] __UpperCamelCase = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod __UpperCamelCase = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" __UpperCamelCase = self.bit_scale if self.config.clip_sample: __UpperCamelCase = torch.clamp(__A ,-scale ,__A ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) __UpperCamelCase = self._get_variance(__A ,__A ) __UpperCamelCase = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide __UpperCamelCase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCamelCase = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __UpperCamelCase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 __UpperCamelCase = model_output.device if torch.is_tensor(__A ) else """cpu""" __UpperCamelCase = torch.randn(model_output.shape ,dtype=model_output.dtype ,generator=__A ).to(__A ) __UpperCamelCase = self._get_variance(__A ,__A ) ** 0.5 * eta * noise __UpperCamelCase = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=__A ,pred_original_sample=__A ) def _lowercase ( self ,__A ,__A ,__A ,__A="epsilon" ,__A=None ,__A = True ,): '''simple docstring''' __UpperCamelCase = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: __UpperCamelCase , __UpperCamelCase = torch.split(__A ,sample.shape[1] ,dim=1 ) else: __UpperCamelCase = None # 1. compute alphas, betas __UpperCamelCase = self.alphas_cumprod[t] __UpperCamelCase = self.alphas_cumprod[t - 1] if t > 0 else self.one __UpperCamelCase = 1 - alpha_prod_t __UpperCamelCase = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": __UpperCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": __UpperCamelCase = model_output else: raise ValueError(f"Unsupported prediction_type {prediction_type}." ) # 3. Clip "predicted x_0" __UpperCamelCase = self.bit_scale if self.config.clip_sample: __UpperCamelCase = torch.clamp(__A ,-scale ,__A ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __UpperCamelCase = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t __UpperCamelCase = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf __UpperCamelCase = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise __UpperCamelCase = 0 if t > 0: __UpperCamelCase = torch.randn( model_output.size() ,dtype=model_output.dtype ,layout=model_output.layout ,generator=__A ).to(model_output.device ) __UpperCamelCase = (self._get_variance(__A ,predicted_variance=__A ) ** 0.5) * noise __UpperCamelCase = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=__A ,pred_original_sample=__A ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase , lowercase = 1.0 , ) -> int: super().__init__() __UpperCamelCase = bit_scale __UpperCamelCase = ( ddim_bit_scheduler_step if isinstance(lowercase , lowercase ) else ddpm_bit_scheduler_step ) self.register_modules(unet=lowercase , scheduler=lowercase ) @torch.no_grad() def __call__( self , lowercase = 2_5_6 , lowercase = 2_5_6 , lowercase = 5_0 , lowercase = None , lowercase = 1 , lowercase = "pil" , lowercase = True , **lowercase , ) -> Union[Tuple, ImagePipelineOutput]: __UpperCamelCase = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=lowercase , ) __UpperCamelCase = decimal_to_bits(lowercase ) * self.bit_scale __UpperCamelCase = latents.to(self.device ) self.scheduler.set_timesteps(lowercase ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual __UpperCamelCase = self.unet(lowercase , lowercase ).sample # compute the previous noisy sample x_t -> x_t-1 __UpperCamelCase = self.scheduler.step(lowercase , lowercase , lowercase ).prev_sample __UpperCamelCase = bits_to_decimal(lowercase ) if output_type == "pil": __UpperCamelCase = self.numpy_to_pil(lowercase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase )
349
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase__ : def __init__( self ) -> Any: __UpperCamelCase = False def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase ) -> str: if not self.initialized: __UpperCamelCase = RagRetriever( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = True def __lowerCamelCase ( self ) -> Optional[Any]: self.retriever.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.retriever._main_retrieve(lowercase , lowercase ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase=None ) -> List[Any]: if index is not None and index.is_initialized() and len(lowercase ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowercase , lowercase , lowercase , lowercase ) for worker in self.retrieval_workers ] ) def __lowerCamelCase ( self ) -> Dict: logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> List[str]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCamelCase = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCamelCase , __UpperCamelCase = ray.get(random_worker.retrieve.remote(lowercase , lowercase ) ) else: __UpperCamelCase , __UpperCamelCase = self._main_retrieve(lowercase , lowercase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase=None , **lowercase ) -> Any: return super(lowercase , cls ).get_tokenizers(lowercase , lowercase , **lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase=None , **lowercase ) -> int: __UpperCamelCase = kwargs.pop("""config""" , lowercase ) or RagConfig.from_pretrained(lowercase , **lowercase ) __UpperCamelCase = RagTokenizer.from_pretrained(lowercase , config=lowercase ) __UpperCamelCase = rag_tokenizer.question_encoder __UpperCamelCase = rag_tokenizer.generator if indexed_dataset is not None: __UpperCamelCase = """custom""" __UpperCamelCase = CustomHFIndex(config.retrieval_vector_size , lowercase ) else: __UpperCamelCase = cls._build_index(lowercase ) return cls( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , retrieval_workers=lowercase , index=lowercase , )
349
1
'''simple docstring''' from __future__ import annotations a__ : List[Any] = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def _lowercase ( __A ,__A ,__A ,__A ,__A ,): '''simple docstring''' __UpperCamelCase = [ [0 for col in range(len(grid[0] ) )] for row in range(len(__A ) ) ] # the reference grid __UpperCamelCase = 1 __UpperCamelCase = [ [0 for col in range(len(grid[0] ) )] for row in range(len(__A ) ) ] # the action grid __UpperCamelCase = init[0] __UpperCamelCase = init[1] __UpperCamelCase = 0 __UpperCamelCase = g + heuristic[x][y] # cost from starting cell to destination cell __UpperCamelCase = [[f, g, x, y]] __UpperCamelCase = False # flag that is set when search is complete __UpperCamelCase = False # flag set if we can't find expand while not found and not resign: if len(__A ) == 0: raise ValueError("""Algorithm is unable to find solution""" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() __UpperCamelCase = cell.pop() __UpperCamelCase = next_cell[2] __UpperCamelCase = next_cell[3] __UpperCamelCase = next_cell[1] if x == goal[0] and y == goal[1]: __UpperCamelCase = True else: for i in range(len(__A ) ): # to try out different valid actions __UpperCamelCase = x + DIRECTIONS[i][0] __UpperCamelCase = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(__A ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: __UpperCamelCase = g + cost __UpperCamelCase = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) __UpperCamelCase = 1 __UpperCamelCase = i __UpperCamelCase = [] __UpperCamelCase = goal[0] __UpperCamelCase = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: __UpperCamelCase = x - DIRECTIONS[action[x][y]][0] __UpperCamelCase = y - DIRECTIONS[action[x][y]][1] __UpperCamelCase = xa __UpperCamelCase = ya invpath.append([x, y] ) __UpperCamelCase = [] for i in range(len(__A ) ): path.append(invpath[len(__A ) - 1 - i] ) return path, action if __name__ == "__main__": a__ : Optional[int] = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] a__ : int = [0, 0] # all coordinates are given in format [y,x] a__ : Any = [len(grid) - 1, len(grid[0]) - 1] a__ : str = 1 # the cost map which pushes the path closer to the goal a__ : List[Any] = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): a__ : str = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map a__ : Any = 9_9 a__ , a__ : Optional[Any] = search(grid, init, goal, cost, heuristic) print('ACTION MAP') for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
349
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : Any = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': 5_1_2, 'squeezebert/squeezebert-mnli': 5_1_2, 'squeezebert/squeezebert-mnli-headless': 5_1_2, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class UpperCAmelCase__ ( UpperCAmelCase_): __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 = SqueezeBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> Tuple: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) __UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowercase ) != tokenize_chinese_chars ): __UpperCamelCase = getattr(lowercase , normalizer_state.pop("""type""" ) ) __UpperCamelCase = do_lower_case __UpperCamelCase = strip_accents __UpperCamelCase = tokenize_chinese_chars __UpperCamelCase = normalizer_class(**lowercase ) __UpperCamelCase = do_lower_case def __lowerCamelCase ( self , lowercase , lowercase=None ) -> Tuple: __UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __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 __lowerCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: __UpperCamelCase = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
349
1
'''simple docstring''' 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 _lowercase ( __A ,__A ): '''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 _lowercase ( __A ,__A ,__A ): '''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 _lowercase ( __A ,__A ): '''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 _lowercase ( __A ,__A ,__A ,__A ,__A = 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 , __UpperCamelCase , __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 , __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__": a__ : Optional[int] = 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.', ) a__ : Dict = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def _lowercase ( ): '''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] ) )
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a__ : str = { 'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'], 'processing_trocr': ['TrOCRProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ 'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrOCRForCausalLM', 'TrOCRPreTrainedModel', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' import numpy as np def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = int(np.ceil((x_end - xa) / h ) ) __UpperCamelCase = np.zeros((n + 1,) ) __UpperCamelCase = ya __UpperCamelCase = xa for k in range(__A ): __UpperCamelCase = f(__A ,y[k] ) __UpperCamelCase = f(x + 0.5 * h ,y[k] + 0.5 * h * ka ) __UpperCamelCase = f(x + 0.5 * h ,y[k] + 0.5 * h * ka ) __UpperCamelCase = f(x + h ,y[k] + h * ka ) __UpperCamelCase = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
349
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig a__ : Union[str, Any] = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''albert''' def __init__( self , lowercase=3_0_0_0_0 , lowercase=1_2_8 , lowercase=4_0_9_6 , lowercase=1_2 , lowercase=1 , lowercase=6_4 , lowercase=1_6_3_8_4 , lowercase=1 , lowercase="gelu_new" , lowercase=0 , lowercase=0 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=0.1 , lowercase="absolute" , lowercase=0 , lowercase=2 , lowercase=3 , **lowercase , ) -> Any: super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) __UpperCamelCase = vocab_size __UpperCamelCase = embedding_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_hidden_groups __UpperCamelCase = num_attention_heads __UpperCamelCase = inner_group_num __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 = classifier_dropout_prob __UpperCamelCase = position_embedding_type class UpperCAmelCase__ ( UpperCAmelCase_): @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
349
1
'''simple docstring''' def _lowercase ( __A ,__A ,__A=False ): '''simple docstring''' if isinstance(__A ,__A ) and isinstance(__A ,__A ): __UpperCamelCase = len(set_a.intersection(__A ) ) if alternative_union: __UpperCamelCase = len(__A ) + len(__A ) else: __UpperCamelCase = len(set_a.union(__A ) ) return intersection / union if isinstance(__A ,(list, tuple) ) and isinstance(__A ,(list, tuple) ): __UpperCamelCase = [element for element in set_a if element in set_b] if alternative_union: __UpperCamelCase = len(__A ) + len(__A ) return len(__A ) / union else: __UpperCamelCase = set_a + [element for element in set_b if element not in set_a] return len(__A ) / len(__A ) return len(__A ) / len(__A ) return None if __name__ == "__main__": a__ : List[Any] = {'a', 'b', 'c', 'd', 'e'} a__ : List[str] = {'c', 'd', 'e', 'f', 'h', 'i'} print(jaccard_similarity(set_a, set_b))
349
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _lowercase ( __A ): '''simple docstring''' return (data["data"], data["target"]) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = XGBRegressor(verbosity=0 ,random_state=42 ) xgb.fit(__A ,__A ) # Predict target for test data __UpperCamelCase = xgb.predict(__A ) __UpperCamelCase = predictions.reshape(len(__A ) ,1 ) return predictions def _lowercase ( ): '''simple docstring''' __UpperCamelCase = fetch_california_housing() __UpperCamelCase , __UpperCamelCase = data_handling(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = train_test_split( __A ,__A ,test_size=0.25 ,random_state=1 ) __UpperCamelCase = xgboost(__A ,__A ,__A ) # Error printing print(f"Mean Absolute Error : {mean_absolute_error(__A ,__A )}" ) print(f"Mean Square Error : {mean_squared_error(__A ,__A )}" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
349
1
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__ : Union[str, Any] = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = PegasusTokenizer __SCREAMING_SNAKE_CASE = PegasusTokenizerFast __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True def __lowerCamelCase ( self ) -> Dict: super().setUp() # We have a SentencePiece fixture for testing __UpperCamelCase = PegasusTokenizer(lowercase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowerCamelCase ( self ) -> List[str]: return PegasusTokenizer.from_pretrained("""google/pegasus-large""" ) def __lowerCamelCase ( self , **lowercase ) -> PegasusTokenizer: return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowercase ) def __lowerCamelCase ( self , lowercase ) -> Any: return ("This is a test", "This is a test") def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = """</s>""" __UpperCamelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<pad>""" ) self.assertEqual(vocab_keys[1] , """</s>""" ) self.assertEqual(vocab_keys[-1] , """v""" ) self.assertEqual(len(lowercase ) , 1_1_0_3 ) def __lowerCamelCase ( self ) -> Tuple: self.assertEqual(self.get_tokenizer().vocab_size , 1_1_0_3 ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __UpperCamelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) __UpperCamelCase = ( """Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important""" """ </s> <pad> <pad> <pad>""" ) __UpperCamelCase = rust_tokenizer([raw_input_str] , return_tensors=lowercase , add_special_tokens=lowercase ).input_ids[0] __UpperCamelCase = py_tokenizer([raw_input_str] , return_tensors=lowercase , add_special_tokens=lowercase ).input_ids[0] self.assertListEqual(lowercase , lowercase ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __UpperCamelCase = """<mask_1> To ensure a <mask_2> flow of bank resolutions.""" __UpperCamelCase = [2, 4_1_3, 6_1_5, 1_1_4, 3, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __UpperCamelCase = tokenizer([raw_input_str] , return_tensors=lowercase ).input_ids[0] self.assertListEqual(lowercase , lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6_1_0_3 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_0_3 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_0_5 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_0_2_4 __UpperCamelCase = """To ensure a smooth flow of bank resolutions.""" __UpperCamelCase = [4_1_3, 6_1_5, 1_1_4, 2_2_9_1, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __UpperCamelCase = tokenizer([raw_input_str] , return_tensors=lowercase ).input_ids[0] self.assertListEqual(lowercase , lowercase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = ["""This is going to be way too long.""" * 1_5_0, """short example"""] __UpperCamelCase = ["""not super long but more than 5 tokens""", """tiny"""] __UpperCamelCase = self._large_tokenizer(lowercase , padding=lowercase , truncation=lowercase , return_tensors="""pt""" ) __UpperCamelCase = self._large_tokenizer( text_target=lowercase , max_length=5 , padding=lowercase , truncation=lowercase , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 1_0_2_4) assert batch.attention_mask.shape == (2, 1_0_2_4) assert targets["input_ids"].shape == (2, 5) assert len(lowercase ) == 2 # input_ids, attention_mask. @slow def __lowerCamelCase ( self ) -> List[str]: # fmt: off __UpperCamelCase = {"""input_ids""": [[3_8_9_7_9, 1_4_3, 1_8_4_8_5, 6_0_6, 1_3_0, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 5_4_1_8_9, 1_1_2_9, 1_1_1, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 9_1_1_4, 1_4_7_8_7, 1_2_1, 1_3_2_4_9, 1_5_8, 5_9_2, 9_5_6, 1_2_1, 1_4_6_2_1, 3_1_5_7_6, 1_4_3, 6_2_6_1_3, 1_0_8, 9_6_8_8, 9_3_0, 4_3_4_3_0, 1_1_5_6_2, 6_2_6_1_3, 3_0_4, 1_0_8, 1_1_4_4_3, 8_9_7, 1_0_8, 9_3_1_4, 1_7_4_1_5, 6_3_3_9_9, 1_0_8, 1_1_4_4_3, 7_6_1_4, 1_8_3_1_6, 1_1_8, 4_2_8_4, 7_1_4_8, 1_2_4_3_0, 1_4_3, 1_4_0_0, 2_5_7_0_3, 1_5_8, 1_1_1, 4_2_8_4, 7_1_4_8, 1_1_7_7_2, 1_4_3, 2_1_2_9_7, 1_0_6_4, 1_5_8, 1_2_2, 2_0_4, 3_5_0_6, 1_7_5_4, 1_1_3_3, 1_4_7_8_7, 1_5_8_1, 1_1_5, 3_3_2_2_4, 4_4_8_2, 1_1_1, 1_3_5_5, 1_1_0, 2_9_1_7_3, 3_1_7, 5_0_8_3_3, 1_0_8, 2_0_1_4_7, 9_4_6_6_5, 1_1_1, 7_7_1_9_8, 1_0_7, 1], [1_1_0, 6_2_6_1_3, 1_1_7, 6_3_8, 1_1_2, 1_1_3_3, 1_2_1, 2_0_0_9_8, 1_3_5_5, 7_9_0_5_0, 1_3_8_7_2, 1_3_5, 1_5_9_6, 5_3_5_4_1, 1_3_5_2, 1_4_1, 1_3_0_3_9, 5_5_4_2, 1_2_4, 3_0_2, 5_1_8, 1_1_1, 2_6_8, 2_9_5_6, 1_1_5, 1_4_9, 4_4_2_7, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_3_9, 1_2_3_5, 2_7_9_9, 1_8_2_8_9, 1_7_7_8_0, 2_0_4, 1_0_9, 9_4_7_4, 1_2_9_6, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name="""google/bigbird-pegasus-large-arxiv""" , revision="""ba85d0851d708441f91440d509690f1ab6353415""" , ) @require_sentencepiece @require_tokenizers class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = PegasusTokenizer __SCREAMING_SNAKE_CASE = PegasusTokenizerFast __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True def __lowerCamelCase ( self ) -> List[str]: super().setUp() # We have a SentencePiece fixture for testing __UpperCamelCase = PegasusTokenizer(lowercase , offset=0 , mask_token_sent=lowercase , mask_token="""[MASK]""" ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowerCamelCase ( self ) -> List[str]: return PegasusTokenizer.from_pretrained("""google/bigbird-pegasus-large-arxiv""" ) def __lowerCamelCase ( self , **lowercase ) -> PegasusTokenizer: return PegasusTokenizer.from_pretrained(self.tmpdirname , **lowercase ) def __lowerCamelCase ( self , lowercase ) -> Tuple: return ("This is a test", "This is a test") def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __UpperCamelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) __UpperCamelCase = ( """Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>""" """ <pad> <pad> <pad>""" ) __UpperCamelCase = rust_tokenizer([raw_input_str] , return_tensors=lowercase , add_special_tokens=lowercase ).input_ids[0] __UpperCamelCase = py_tokenizer([raw_input_str] , return_tensors=lowercase , add_special_tokens=lowercase ).input_ids[0] self.assertListEqual(lowercase , lowercase ) @require_torch def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = ["""This is going to be way too long.""" * 1_0_0_0, """short example"""] __UpperCamelCase = ["""not super long but more than 5 tokens""", """tiny"""] __UpperCamelCase = self._large_tokenizer(lowercase , padding=lowercase , truncation=lowercase , return_tensors="""pt""" ) __UpperCamelCase = self._large_tokenizer( text_target=lowercase , max_length=5 , padding=lowercase , truncation=lowercase , return_tensors="""pt""" ) assert batch.input_ids.shape == (2, 4_0_9_6) assert batch.attention_mask.shape == (2, 4_0_9_6) assert targets["input_ids"].shape == (2, 5) assert len(lowercase ) == 2 # input_ids, attention_mask. def __lowerCamelCase ( self ) -> str: __UpperCamelCase = ( """This is an example string that is used to test the original TF implementation against the HF""" """ implementation""" ) __UpperCamelCase = self._large_tokenizer(lowercase ).input_ids self.assertListEqual( lowercase , [1_8_2, 1_1_7, 1_4_2, 5_8_7, 4_2_1_1, 1_2_0, 1_1_7, 2_6_3, 1_1_2, 8_0_4, 1_0_9, 8_5_6, 2_5_0_1_6, 3_1_3_7, 4_6_4, 1_0_9, 2_6_9_5_5, 3_1_3_7, 1] , )
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=2 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=4_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: __UpperCamelCase = TFPegasusModel(config=lowercase ).get_decoder() __UpperCamelCase = inputs_dict["""input_ids"""] __UpperCamelCase = input_ids[:1, :] __UpperCamelCase = inputs_dict["""attention_mask"""][:1, :] __UpperCamelCase = inputs_dict["""head_mask"""] __UpperCamelCase = 1 # first forward pass __UpperCamelCase = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) __UpperCamelCase , __UpperCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __UpperCamelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) __UpperCamelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __UpperCamelCase = model(lowercase , attention_mask=lowercase )[0] __UpperCamelCase = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __UpperCamelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx] __UpperCamelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1E-3 ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,__A=None ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = tf.cast(tf.math.not_equal(__A ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: __UpperCamelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: __UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration,) if is_tf_available() else () __SCREAMING_SNAKE_CASE = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> str: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase__ ( unittest.TestCase): __SCREAMING_SNAKE_CASE = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] __SCREAMING_SNAKE_CASE = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers __SCREAMING_SNAKE_CASE = '''google/pegasus-xsum''' @cached_property def __lowerCamelCase ( self ) -> int: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __lowerCamelCase ( self , **lowercase ) -> Optional[int]: __UpperCamelCase = self.translate_src_text(**lowercase ) assert self.expected_text == generated_words def __lowerCamelCase ( self , **lowercase ) -> Optional[Any]: __UpperCamelCase = self.tokenizer(self.src_text , **lowercase , padding=lowercase , return_tensors="""tf""" ) __UpperCamelCase = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) __UpperCamelCase = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase ) return generated_words @slow def __lowerCamelCase ( self ) -> Dict: self._assert_generated_batch_equal_expected()
349
1
'''simple docstring''' from typing import Optional import pyspark from .. import Features, NamedSplit from ..download import DownloadMode from ..packaged_modules.spark.spark import Spark from .abc import AbstractDatasetReader class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase = None , lowercase = None , lowercase = True , lowercase = None , lowercase = False , lowercase = None , lowercase = True , lowercase = "arrow" , **lowercase , ) -> List[Any]: super().__init__( split=lowercase , features=lowercase , cache_dir=lowercase , keep_in_memory=lowercase , streaming=lowercase , **lowercase , ) __UpperCamelCase = load_from_cache_file __UpperCamelCase = file_format __UpperCamelCase = Spark( df=lowercase , features=lowercase , cache_dir=lowercase , working_dir=lowercase , **lowercase , ) def __lowerCamelCase ( self ) -> List[str]: if self.streaming: return self.builder.as_streaming_dataset(split=self.split ) __UpperCamelCase = None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD self.builder.download_and_prepare( download_mode=lowercase , file_format=self._file_format , ) return self.builder.as_dataset(split=self.split )
349
'''simple docstring''' import string def _lowercase ( __A ): '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): __UpperCamelCase = """""" for symbol in message: if symbol in string.ascii_uppercase: __UpperCamelCase = string.ascii_uppercase.find(__A ) __UpperCamelCase = num - key if num < 0: __UpperCamelCase = num + len(string.ascii_uppercase ) __UpperCamelCase = translated + string.ascii_uppercase[num] else: __UpperCamelCase = translated + symbol print(f"Decryption using Key #{key}: {translated}" ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = input("""Encrypted message: """ ) __UpperCamelCase = message.upper() decrypt(__A ) if __name__ == "__main__": import doctest doctest.testmod() main()
349
1
'''simple docstring''' from bisect import bisect from itertools import accumulate def _lowercase ( __A ,__A ,__A ,__A ): '''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()
349
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : Dict = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''gptj''' __SCREAMING_SNAKE_CASE = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , lowercase=5_0_4_0_0 , lowercase=2_0_4_8 , lowercase=4_0_9_6 , lowercase=2_8 , lowercase=1_6 , lowercase=6_4 , lowercase=None , lowercase="gelu_new" , lowercase=0.0 , lowercase=0.0 , lowercase=0.0 , lowercase=1E-5 , lowercase=0.02 , lowercase=True , lowercase=5_0_2_5_6 , lowercase=5_0_2_5_6 , lowercase=False , **lowercase , ) -> Tuple: __UpperCamelCase = vocab_size __UpperCamelCase = n_positions __UpperCamelCase = n_embd __UpperCamelCase = n_layer __UpperCamelCase = n_head __UpperCamelCase = n_inner __UpperCamelCase = rotary_dim __UpperCamelCase = activation_function __UpperCamelCase = resid_pdrop __UpperCamelCase = embd_pdrop __UpperCamelCase = attn_pdrop __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = initializer_range __UpperCamelCase = use_cache __UpperCamelCase = bos_token_id __UpperCamelCase = eos_token_id super().__init__( bos_token_id=lowercase , eos_token_id=lowercase , tie_word_embeddings=lowercase , **lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase = "default" , lowercase = None , lowercase = False , ) -> List[str]: super().__init__(lowercase , task=lowercase , patching_specs=lowercase , use_past=lowercase ) if not getattr(self._config , """pad_token_id""" , lowercase ): # TODO: how to do that better? __UpperCamelCase = 0 @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: __UpperCamelCase = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(lowercase , direction="""inputs""" ) __UpperCamelCase = {0: """batch""", 1: """past_sequence + sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return common_inputs @property def __lowerCamelCase ( self ) -> int: return self._config.n_layer @property def __lowerCamelCase ( self ) -> int: return self._config.n_head def __lowerCamelCase ( self , lowercase , lowercase = -1 , lowercase = -1 , lowercase = False , lowercase = None , ) -> Mapping[str, Any]: __UpperCamelCase = super(lowercase , self ).generate_dummy_inputs( lowercase , batch_size=lowercase , seq_length=lowercase , is_pair=lowercase , framework=lowercase ) # We need to order the input in the way they appears in the forward() __UpperCamelCase = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __UpperCamelCase , __UpperCamelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __UpperCamelCase = seqlen + 2 __UpperCamelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __UpperCamelCase = [ (torch.zeros(lowercase ), torch.zeros(lowercase )) for _ in range(self.num_layers ) ] __UpperCamelCase = common_inputs["""attention_mask"""] if self.use_past: __UpperCamelCase = ordered_inputs["""attention_mask"""].dtype __UpperCamelCase = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(lowercase , lowercase , dtype=lowercase )] , dim=1 ) return ordered_inputs @property def __lowerCamelCase ( self ) -> int: return 1_3
349
1
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node a__ : Optional[Any] = 4 a__ : str = 3 class UpperCAmelCase__ ( UpperCAmelCase_): pass def _lowercase ( __A ): '''simple docstring''' for shard in shards: for i in range(__A ): yield {"i": i, "shard": shard} def _lowercase ( ): '''simple docstring''' __UpperCamelCase = int(os.environ["""RANK"""] ) __UpperCamelCase = int(os.environ["""WORLD_SIZE"""] ) __UpperCamelCase = ArgumentParser() parser.add_argument("""--streaming""" ,type=__A ) parser.add_argument("""--local_rank""" ,type=__A ) parser.add_argument("""--num_workers""" ,type=__A ,default=0 ) __UpperCamelCase = parser.parse_args() __UpperCamelCase = args.streaming __UpperCamelCase = args.num_workers __UpperCamelCase = {"""shards""": [f"shard_{shard_idx}" for shard_idx in range(__A )]} __UpperCamelCase = IterableDataset.from_generator(__A ,gen_kwargs=__A ) if not streaming: __UpperCamelCase = Dataset.from_list(list(__A ) ) __UpperCamelCase = split_dataset_by_node(__A ,rank=__A ,world_size=__A ) __UpperCamelCase = torch.utils.data.DataLoader(__A ,num_workers=__A ) __UpperCamelCase = NUM_SHARDS * NUM_ITEMS_PER_SHARD __UpperCamelCase = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) __UpperCamelCase = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(f"local_size {local_size} != expected_local_size {expected_local_size}" ) if __name__ == "__main__": main()
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a__ : int = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['LayoutLMv3FeatureExtractor'] a__ : str = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' import numpy as np def _lowercase ( __A ,__A ,__A = 1E-12 ,__A = 100 ,): '''simple docstring''' assert np.shape(__A )[0] == np.shape(__A )[1] # Ensure proper dimensionality. assert np.shape(__A )[0] == np.shape(__A )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(__A ) == np.iscomplexobj(__A ) __UpperCamelCase = np.iscomplexobj(__A ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(__A ,input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __UpperCamelCase = False __UpperCamelCase = 0 __UpperCamelCase = 0 __UpperCamelCase = 1E12 while not convergence: # Multiple matrix by the vector. __UpperCamelCase = np.dot(__A ,__A ) # Normalize the resulting output vector. __UpperCamelCase = w / np.linalg.norm(__A ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __UpperCamelCase = vector.conj().T if is_complex else vector.T __UpperCamelCase = np.dot(__A ,np.dot(__A ,__A ) ) # Check convergence. __UpperCamelCase = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __UpperCamelCase = True __UpperCamelCase = lambda_ if is_complex: __UpperCamelCase = np.real(lambda_ ) return lambda_, vector def _lowercase ( ): '''simple docstring''' __UpperCamelCase = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __UpperCamelCase = np.array([41, 4, 20] ) __UpperCamelCase = real_input_matrix.astype(np.complexaaa ) __UpperCamelCase = np.triu(1j * complex_input_matrix ,1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __UpperCamelCase = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __UpperCamelCase = real_input_matrix __UpperCamelCase = real_vector elif problem_type == "complex": __UpperCamelCase = complex_input_matrix __UpperCamelCase = complex_vector # Our implementation. __UpperCamelCase , __UpperCamelCase = power_iteration(__A ,__A ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __UpperCamelCase , __UpperCamelCase = np.linalg.eigh(__A ) # Last eigenvalue is the maximum one. __UpperCamelCase = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __UpperCamelCase = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(__A ) - np.abs(__A ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
349
'''simple docstring''' def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = len(__A ) __UpperCamelCase = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __UpperCamelCase = True # sum is not zero and set is empty then false for i in range(1 ,required_sum + 1 ): __UpperCamelCase = False for i in range(1 ,arr_len + 1 ): for j in range(1 ,required_sum + 1 ): if arr[i - 1] > j: __UpperCamelCase = subset[i - 1][j] if arr[i - 1] <= j: __UpperCamelCase = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase__ : def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=9_9 , lowercase=2_4 , lowercase=2 , lowercase=6 , lowercase=3_7 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=5_1_2 , lowercase=1_6 , lowercase=2 , lowercase=0.02 , lowercase=3 , lowercase=None , lowercase=1_0_0_0 , ) -> str: __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 = scope __UpperCamelCase = range_bbox def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __UpperCamelCase = bbox[i, j, 3] __UpperCamelCase = bbox[i, j, 1] __UpperCamelCase = t if bbox[i, j, 2] < bbox[i, j, 0]: __UpperCamelCase = bbox[i, j, 2] __UpperCamelCase = bbox[i, j, 0] __UpperCamelCase = t __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 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 = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def __lowerCamelCase ( self ) -> List[str]: return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Tuple: __UpperCamelCase = LiltModel(config=lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model(lowercase , bbox=lowercase , attention_mask=lowercase , token_type_ids=lowercase ) __UpperCamelCase = model(lowercase , bbox=lowercase , token_type_ids=lowercase ) __UpperCamelCase = model(lowercase , bbox=lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Dict: __UpperCamelCase = self.num_labels __UpperCamelCase = LiltForTokenClassification(config=lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model( lowercase , bbox=lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> int: __UpperCamelCase = LiltForQuestionAnswering(config=lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model( lowercase , bbox=lowercase , attention_mask=lowercase , token_type_ids=lowercase , start_positions=lowercase , end_positions=lowercase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) = config_and_inputs __UpperCamelCase = { """input_ids""": input_ids, """bbox""": bbox, """token_type_ids""": token_type_ids, """attention_mask""": input_mask, } return config, inputs_dict @require_torch class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Any: return True def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = LiltModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , hidden_size=3_7 ) def __lowerCamelCase ( self ) -> Optional[Any]: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase ) def __lowerCamelCase ( self ) -> Optional[int]: __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(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase ) def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase ) @slow def __lowerCamelCase ( self ) -> Optional[int]: for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = LiltModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_torch @slow class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> str: __UpperCamelCase = LiltModel.from_pretrained("""SCUT-DLVCLab/lilt-roberta-en-base""" ).to(lowercase ) __UpperCamelCase = torch.tensor([[1, 2]] , device=lowercase ) __UpperCamelCase = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase ) # forward pass with torch.no_grad(): __UpperCamelCase = model(input_ids=lowercase , bbox=lowercase ) __UpperCamelCase = torch.Size([1, 2, 7_6_8] ) __UpperCamelCase = torch.tensor( [[-0.0_653, 0.0_950, -0.0_061], [-0.0_545, 0.0_926, -0.0_324]] , device=lowercase , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase , atol=1E-3 ) )
349
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger a__ : Any = get_logger(__name__) class UpperCAmelCase__ : def __init__( self , lowercase = None ) -> List[str]: __UpperCamelCase = ( os.path.join(lowercase , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) __UpperCamelCase = Extractor def __lowerCamelCase ( self , lowercase ) -> str: from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" __UpperCamelCase = os.path.abspath(lowercase ) return os.path.join(self.extract_dir , hash_url_to_filename(lowercase ) ) def __lowerCamelCase ( self , lowercase , lowercase ) -> bool: return force_extract or ( not os.path.isfile(lowercase ) and not (os.path.isdir(lowercase ) and os.listdir(lowercase )) ) def __lowerCamelCase ( self , lowercase , lowercase = False ) -> str: __UpperCamelCase = self.extractor.infer_extractor_format(lowercase ) if not extractor_format: return input_path __UpperCamelCase = self._get_output_path(lowercase ) if self._do_extract(lowercase , lowercase ): self.extractor.extract(lowercase , lowercase , lowercase ) return output_path class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod @abstractmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: ... @staticmethod @abstractmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: ... class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> int: with open(lowercase , """rb""" ) as f: return f.read(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if not magic_number: __UpperCamelCase = max(len(lowercase ) for cls_magic_number in cls.magic_numbers ) try: __UpperCamelCase = cls.read_magic_number(lowercase , lowercase ) except OSError: return False return any(magic_number.startswith(lowercase ) for cls_magic_number in cls.magic_numbers ) class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: return tarfile.is_tarfile(lowercase ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: def resolved(lowercase ) -> str: return os.path.realpath(os.path.abspath(lowercase ) ) def badpath(lowercase , lowercase ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(lowercase , lowercase ) ).startswith(lowercase ) def badlink(lowercase , lowercase ) -> bool: # Links are interpreted relative to the directory containing the link __UpperCamelCase = resolved(os.path.join(lowercase , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=lowercase ) __UpperCamelCase = resolved(lowercase ) for finfo in members: if badpath(finfo.name , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked (illegal path)" ) elif finfo.issym() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}" ) elif finfo.islnk() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}" ) else: yield finfo @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = tarfile.open(lowercase ) tar_file.extractall(lowercase , members=TarExtractor.safemembers(lowercase , lowercase ) ) tar_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x1F\x8B'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with gzip.open(lowercase , """rb""" ) as gzip_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [ B'''PK\x03\x04''', B'''PK\x05\x06''', # empty archive B'''PK\x07\x08''', # spanned archive ] @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if super().is_extractable(lowercase , magic_number=lowercase ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(lowercase , """rb""" ) as fp: __UpperCamelCase = _EndRecData(lowercase ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: __UpperCamelCase = fp.read(lowercase ) # CD is where we expect it to be if len(lowercase ) == sizeCentralDir: __UpperCamelCase = struct.unpack(lowercase , lowercase ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) with zipfile.ZipFile(lowercase , """r""" ) as zip_file: zip_file.extractall(lowercase ) zip_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with lzma.open(lowercase ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = rarfile.RarFile(lowercase ) rf.extractall(lowercase ) rf.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x28\xb5\x2F\xFD'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd __UpperCamelCase = zstd.ZstdDecompressor() with open(lowercase , """rb""" ) as ifh, open(lowercase , """wb""" ) as ofh: dctx.copy_stream(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x42\x5A\x68'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with bza.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(lowercase , exist_ok=lowercase ) with pyazr.SevenZipFile(lowercase , """r""" ) as archive: archive.extractall(lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x04\x22\x4D\x18'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) __SCREAMING_SNAKE_CASE = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def __lowerCamelCase ( cls ) -> Union[str, Any]: return max( len(lowercase ) for extractor in cls.extractors.values() if issubclass(lowercase , lowercase ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: try: return MagicNumberBaseExtractor.read_magic_number(lowercase , magic_number_length=lowercase ) except OSError: return b"" @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = False ) -> bool: warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = cls.infer_extractor_format(lowercase ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def __lowerCamelCase ( cls , lowercase ) -> str: # <Added version="2.4.0"/> __UpperCamelCase = cls._get_magic_number_max_length() __UpperCamelCase = cls._read_magic_number(lowercase , lowercase ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(lowercase , magic_number=lowercase ): return extractor_format @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase = None , lowercase = "deprecated" , ) -> None: os.makedirs(os.path.dirname(lowercase ) , exist_ok=lowercase ) # Prevent parallel extractions __UpperCamelCase = str(Path(lowercase ).with_suffix(""".lock""" ) ) with FileLock(lowercase ): shutil.rmtree(lowercase , ignore_errors=lowercase ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(lowercase , lowercase ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = extractor if extractor != """deprecated""" else extractor_format else: __UpperCamelCase = cls.extractors[extractor_format] return extractor.extract(lowercase , lowercase ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=lowercase , ) for extractor in cls.extractors.values(): if extractor.is_extractable(lowercase ): return extractor.extract(lowercase , lowercase )
349
1
'''simple docstring''' def _lowercase ( __A ): '''simple docstring''' if len(__A ) <= 1: return lst __UpperCamelCase = 1 while i < len(__A ): if lst[i - 1] <= lst[i]: i += 1 else: __UpperCamelCase , __UpperCamelCase = lst[i], lst[i - 1] i -= 1 if i == 0: __UpperCamelCase = 1 return lst if __name__ == "__main__": a__ : List[Any] = input('Enter numbers separated by a comma:\n').strip() a__ : Any = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
349
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=5 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=2_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Optional[Any]: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> str: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __UpperCamelCase = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = np.concatenate([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , decoder_attention_mask=lowercase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Any: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase , decoder_attention_mask=lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = np.not_equal(__A ,config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __UpperCamelCase = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape ,dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ).astype(np.inta ), ] ,axis=-1 ,) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __SCREAMING_SNAKE_CASE = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = FlaxPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> List[Any]: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = self._prepare_for_class(lowercase , lowercase ) __UpperCamelCase = model_class(lowercase ) @jax.jit def encode_jitted(lowercase , lowercase=None , **lowercase ): return model.encode(input_ids=lowercase , attention_mask=lowercase ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) __UpperCamelCase = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(lowercase , lowercase , lowercase ): return model.decode( decoder_input_ids=lowercase , decoder_attention_mask=lowercase , encoder_outputs=lowercase , ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __lowerCamelCase ( self ) -> Dict: for model_class_name in self.all_model_classes: __UpperCamelCase = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=lowercase ) __UpperCamelCase = np.ones((1, 1) ) __UpperCamelCase = model(lowercase ) self.assertIsNotNone(lowercase ) @slow def __lowerCamelCase ( self ) -> str: __UpperCamelCase = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] __UpperCamelCase = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] __UpperCamelCase = tokenizer(lowercase , return_tensors="""np""" , truncation=lowercase , max_length=5_1_2 , padding=lowercase ) __UpperCamelCase = model.generate(**lowercase , num_beams=2 ).sequences __UpperCamelCase = tokenizer.batch_decode(lowercase , skip_special_tokens=lowercase ) assert tgt_text == decoded
349
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : int = logging.get_logger(__name__) a__ : Union[str, Any] = { 'tanreinama/GPTSAN-2.8B-spout_is_uniform': ( 'https://huggingface.co/tanreinama/GPTSAN-2.8B-spout_is_uniform/resolve/main/config.json' ), } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''gptsan-japanese''' __SCREAMING_SNAKE_CASE = [ '''past_key_values''', ] __SCREAMING_SNAKE_CASE = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , lowercase=3_6_0_0_0 , lowercase=1_2_8_0 , lowercase=1_0_2_4 , lowercase=8_1_9_2 , lowercase=4_0_9_6 , lowercase=1_2_8 , lowercase=1_0 , lowercase=0 , lowercase=1_6 , lowercase=1_6 , lowercase=1_2_8 , lowercase=0.0 , lowercase=1E-5 , lowercase=False , lowercase=0.0 , lowercase="float32" , lowercase=False , lowercase=False , lowercase=False , lowercase=0.002 , lowercase=False , lowercase=True , lowercase=3_5_9_9_8 , lowercase=3_5_9_9_5 , lowercase=3_5_9_9_9 , **lowercase , ) -> Optional[Any]: __UpperCamelCase = vocab_size __UpperCamelCase = max_position_embeddings __UpperCamelCase = d_model __UpperCamelCase = d_ff __UpperCamelCase = d_ext __UpperCamelCase = d_spout __UpperCamelCase = num_switch_layers __UpperCamelCase = num_ext_layers __UpperCamelCase = num_switch_layers + num_ext_layers __UpperCamelCase = num_heads __UpperCamelCase = num_experts __UpperCamelCase = expert_capacity __UpperCamelCase = dropout_rate __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = router_bias __UpperCamelCase = router_jitter_noise __UpperCamelCase = router_dtype __UpperCamelCase = router_ignore_padding_tokens __UpperCamelCase = output_hidden_states __UpperCamelCase = output_attentions __UpperCamelCase = initializer_factor __UpperCamelCase = output_router_logits __UpperCamelCase = use_cache super().__init__( separator_token_id=lowercase , pad_token_id=lowercase , eos_token_id=lowercase , **lowercase , )
349
'''simple docstring''' import pytest a__ : List[str] = '__dummy_dataset1__' a__ : Optional[int] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dataset_loading_script_name __UpperCamelCase = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=__A ) __UpperCamelCase = script_dir / f"{script_name}.py" with open(__A ,"""w""" ) as f: f.write(__A ) return str(__A )
349
1
'''simple docstring''' import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''Wav2Vec2FeatureExtractor''' __SCREAMING_SNAKE_CASE = '''AutoTokenizer''' def __init__( self , lowercase , lowercase ) -> List[str]: super().__init__(lowercase , lowercase ) __UpperCamelCase = self.feature_extractor __UpperCamelCase = False @classmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> int: try: return super().from_pretrained(lowercase , **lowercase ) except OSError: warnings.warn( f"Loading a tokenizer inside {cls.__name__} from a config that does not" """ include a `tokenizer_class` attribute is deprecated and will be """ """removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`""" """ attribute to either your `config.json` or `tokenizer_config.json` """ """file to suppress this warning: """ , lowercase , ) __UpperCamelCase = WavaVecaFeatureExtractor.from_pretrained(lowercase , **lowercase ) __UpperCamelCase = WavaVecaCTCTokenizer.from_pretrained(lowercase , **lowercase ) return cls(feature_extractor=lowercase , tokenizer=lowercase ) def __call__( self , *lowercase , **lowercase ) -> Any: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*lowercase , **lowercase ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) __UpperCamelCase = kwargs.pop("""raw_speech""" ) else: __UpperCamelCase = kwargs.pop("""audio""" , lowercase ) __UpperCamelCase = kwargs.pop("""sampling_rate""" , lowercase ) __UpperCamelCase = kwargs.pop("""text""" , lowercase ) if len(lowercase ) > 0: __UpperCamelCase = args[0] __UpperCamelCase = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: __UpperCamelCase = self.feature_extractor(lowercase , *lowercase , sampling_rate=lowercase , **lowercase ) if text is not None: __UpperCamelCase = self.tokenizer(lowercase , **lowercase ) if text is None: return inputs elif audio is None: return encodings else: __UpperCamelCase = encodings["""input_ids"""] return inputs def __lowerCamelCase ( self , *lowercase , **lowercase ) -> Tuple: # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*lowercase , **lowercase ) __UpperCamelCase = kwargs.pop("""input_features""" , lowercase ) __UpperCamelCase = kwargs.pop("""labels""" , lowercase ) if len(lowercase ) > 0: __UpperCamelCase = args[0] __UpperCamelCase = args[1:] if input_features is not None: __UpperCamelCase = self.feature_extractor.pad(lowercase , *lowercase , **lowercase ) if labels is not None: __UpperCamelCase = self.tokenizer.pad(lowercase , **lowercase ) if labels is None: return input_features elif input_features is None: return labels else: __UpperCamelCase = labels["""input_ids"""] return input_features def __lowerCamelCase ( self , *lowercase , **lowercase ) -> Dict: return self.tokenizer.batch_decode(*lowercase , **lowercase ) def __lowerCamelCase ( self , *lowercase , **lowercase ) -> List[Any]: return self.tokenizer.decode(*lowercase , **lowercase ) @contextmanager def __lowerCamelCase ( self ) -> List[str]: warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) __UpperCamelCase = True __UpperCamelCase = self.tokenizer yield __UpperCamelCase = self.feature_extractor __UpperCamelCase = False
349
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } a__ : List[str] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} with open(__A ,"""r""" ) as file: for line_number, line in enumerate(__A ): __UpperCamelCase = line.strip() if line: __UpperCamelCase = line.split() __UpperCamelCase = line_number __UpperCamelCase = words[0] __UpperCamelCase = value return result def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' for attribute in key.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = getattr(__A ,__A ).shape elif weight_type is not None and weight_type == "param": __UpperCamelCase = hf_pointer for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = shape_pointer.shape # let's reduce dimension __UpperCamelCase = value[0] 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 == "param": for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = value else: __UpperCamelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __UpperCamelCase = """.""".join([key, hf_param_name] ) else: __UpperCamelCase = key __UpperCamelCase = value if """lm_head""" in full_key else value[0] a__ : Dict = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _lowercase ( __A ,__A ,__A=None ,__A=None ): '''simple docstring''' __UpperCamelCase = False for key, mapped_key in MAPPING.items(): __UpperCamelCase = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __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: # TODO: don't match quantizer.weight_proj __UpperCamelCase = """weight""" else: __UpperCamelCase = None if hf_dict is not None: rename_dict(__A ,__A ,__A ,__A ,__A ) else: set_recursively(__A ,__A ,__A ,__A ,__A ) return is_used return is_used def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = [] __UpperCamelCase = fairseq_model.state_dict() __UpperCamelCase = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __A ,__A ,__A ,__A ,hf_model.config.feat_extract_norm == """group""" ,) __UpperCamelCase = True else: __UpperCamelCase = load_wavaveca_layer(__A ,__A ,__A ) if not is_used: unused_weights.append(__A ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''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 _lowercase ( __A ,__A ,__A=None ,__A=None ,__A=True ,__A=False ): '''simple docstring''' if config_path is not None: __UpperCamelCase = WavaVecaConfig.from_pretrained(__A ) else: __UpperCamelCase = WavaVecaConfig() if is_seq_class: __UpperCamelCase = read_txt_into_dict(__A ) __UpperCamelCase = idalabel __UpperCamelCase = WavaVecaForSequenceClassification(__A ) __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) feature_extractor.save_pretrained(__A ) elif is_finetuned: if dict_path: __UpperCamelCase = Dictionary.load(__A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase = target_dict.pad_index __UpperCamelCase = target_dict.bos_index __UpperCamelCase = target_dict.eos_index __UpperCamelCase = len(target_dict.symbols ) __UpperCamelCase = os.path.join(__A ,"""vocab.json""" ) if not os.path.isdir(__A ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__A ) ) return os.makedirs(__A ,exist_ok=__A ) __UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCamelCase = 0 __UpperCamelCase = 1 with open(__A ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(__A ,__A ) __UpperCamelCase = WavaVecaCTCTokenizer( __A ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=__A ,) __UpperCamelCase = True if config.feat_extract_norm == """layer""" else False __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) __UpperCamelCase = WavaVecaProcessor(feature_extractor=__A ,tokenizer=__A ) processor.save_pretrained(__A ) __UpperCamelCase = WavaVecaForCTC(__A ) else: __UpperCamelCase = WavaVecaForPreTraining(__A ) if is_finetuned or is_seq_class: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __UpperCamelCase = argparse.Namespace(task="""audio_pretraining""" ) __UpperCamelCase = fairseq.tasks.setup_task(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=__A ) __UpperCamelCase = model[0].eval() recursively_load_weights(__A ,__A ,not is_finetuned ) hf_wavavec.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) a__ : Optional[int] = parser.parse_args() a__ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
349
1
'''simple docstring''' from collections.abc import Sequence def _lowercase ( __A = None ): '''simple docstring''' if nums is None or not nums: raise ValueError("""Input sequence should not be empty""" ) __UpperCamelCase = nums[0] for i in range(1 ,len(__A ) ): __UpperCamelCase = nums[i] __UpperCamelCase = max(__A ,ans + num ,__A ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user a__ : Optional[int] = int(input('Enter number of elements : ').strip()) a__ : Any = list(map(int, input('\nEnter the numbers : ').strip().split()))[:n] print(max_subsequence_sum(array))
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCAmelCase__ : def __init__( self , lowercase , ) -> Union[str, Any]: __UpperCamelCase = parent __UpperCamelCase = 1_3 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = 9_9 __UpperCamelCase = 3_2 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 3_7 __UpperCamelCase = """gelu""" __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 5_1_2 __UpperCamelCase = 1_6 __UpperCamelCase = 2 __UpperCamelCase = 0.02 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = None def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = None if self.use_input_mask: __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = TFDistilBertModel(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]: __UpperCamelCase = TFDistilBertForMaskedLM(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = TFDistilBertForQuestionAnswering(config=lowercase ) __UpperCamelCase = { """input_ids""": input_ids, """attention_mask""": input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForSequenceClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: __UpperCamelCase = self.num_choices __UpperCamelCase = TFDistilBertForMultipleChoice(lowercase ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForTokenClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.prepare_config_and_inputs() ((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFDistilBertModel, '''fill-mask''': TFDistilBertForMaskedLM, '''question-answering''': TFDistilBertForQuestionAnswering, '''text-classification''': TFDistilBertForSequenceClassification, '''token-classification''': TFDistilBertForTokenClassification, '''zero-shot''': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = TFDistilBertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , dim=3_7 ) def __lowerCamelCase ( self ) -> Any: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) @slow def __lowerCamelCase ( self ) -> Tuple: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): __UpperCamelCase = TFDistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_tf class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase = model(lowercase )[0] __UpperCamelCase = [1, 6, 7_6_8] self.assertEqual(output.shape , lowercase ) __UpperCamelCase = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-4 )
349
1
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None def _lowercase ( ): '''simple docstring''' __UpperCamelCase = Node(1 ) __UpperCamelCase = Node(2 ) __UpperCamelCase = Node(3 ) __UpperCamelCase = Node(4 ) __UpperCamelCase = Node(5 ) return tree def _lowercase ( __A ): '''simple docstring''' return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _lowercase ( __A ): '''simple docstring''' return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _lowercase ( __A ): '''simple docstring''' return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _lowercase ( __A ): '''simple docstring''' return (max(height(root.left ) ,height(root.right ) ) + 1) if root else 0 def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = [] if root is None: return output __UpperCamelCase = deque([root] ) while process_queue: __UpperCamelCase = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = [] def populate_output(__A ,__A ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left ,level - 1 ) populate_output(root.right ,level - 1 ) populate_output(__A ,__A ) return output def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = [] def populate_output(__A ,__A ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right ,level - 1 ) populate_output(root.left ,level - 1 ) populate_output(__A ,__A ) return output def _lowercase ( __A ): '''simple docstring''' if root is None: return [] __UpperCamelCase = [] __UpperCamelCase = 0 __UpperCamelCase = height(__A ) for h in range(1 ,height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(__A ,__A ) ) __UpperCamelCase = 1 else: output.append(get_nodes_from_right_to_left(__A ,__A ) ) __UpperCamelCase = 0 return output def _lowercase ( ): # Main function for testing. '''simple docstring''' __UpperCamelCase = make_tree() print(f"In-order Traversal: {inorder(__A )}" ) print(f"Pre-order Traversal: {preorder(__A )}" ) print(f"Post-order Traversal: {postorder(__A )}" ,"""\n""" ) print(f"Height of Tree: {height(__A )}" ,"""\n""" ) print("""Complete Level Order Traversal: """ ) print(level_order(__A ) ,"""\n""" ) print("""Level-wise order Traversal: """ ) for level in range(1 ,height(__A ) + 1 ): print(f"Level {level}:" ,get_nodes_from_left_to_right(__A ,level=__A ) ) print("""\nZigZag order Traversal: """ ) print(zigzag(__A ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
349
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _lowercase ( __A ,__A ): '''simple docstring''' return math.sqrt(sum(pow(a - b ,2 ) for a, b in zip(__A ,__A ) ) ) def _lowercase ( __A ,__A ): '''simple docstring''' if dataset.ndim != value_array.ndim: __UpperCamelCase = ( """Wrong input data's dimensions... """ f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(__A ) try: if dataset.shape[1] != value_array.shape[1]: __UpperCamelCase = ( """Wrong input data's shape... """ f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(__A ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: __UpperCamelCase = ( """Input data have different datatype... """ f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(__A ) __UpperCamelCase = [] for value in value_array: __UpperCamelCase = euclidean(__A ,dataset[0] ) __UpperCamelCase = dataset[0].tolist() for dataset_value in dataset[1:]: __UpperCamelCase = euclidean(__A ,__A ) if dist > temp_dist: __UpperCamelCase = temp_dist __UpperCamelCase = dataset_value.tolist() answer.append([vector, dist] ) return answer def _lowercase ( __A ,__A ): '''simple docstring''' return np.dot(__A ,__A ) / (norm(__A ) * norm(__A )) if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' a__ : Union[str, Any] = 9.8_06_65 def _lowercase ( __A ,__A ,__A = g ): '''simple docstring''' if fluid_density <= 0: raise ValueError("""Impossible fluid density""" ) if volume < 0: raise ValueError("""Impossible Object volume""" ) if gravity <= 0: raise ValueError("""Impossible Gravity""" ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
349
'''simple docstring''' from datetime import datetime import requests def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = """https://downloadgram.net/wp-json/wppress/video-downloader/video?url=""" __UpperCamelCase = requests.get(base_url + url ).json()[0]["""urls"""][0]["""src"""] return requests.get(__A ).content if __name__ == "__main__": a__ : int = input('Enter Video/IGTV url: ').strip() a__ : int = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4''' with open(file_name, 'wb') as fp: fp.write(download_video(url)) print(f'''Done. Video saved to disk as {file_name}.''')
349
1
'''simple docstring''' 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 a__ : Dict = logging.get_logger(__name__) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''pixel_values'''] def __init__( self , lowercase = True , lowercase = None , lowercase = PILImageResampling.BICUBIC , lowercase = True , lowercase = True , lowercase = 1 / 2_5_5 , lowercase = None , lowercase = True , lowercase = None , lowercase = None , **lowercase , ) -> None: super().__init__(**lowercase ) __UpperCamelCase = size if size is not None else {"""height""": 2_2_4, """width""": 2_2_4} __UpperCamelCase = get_size_dict(lowercase ) __UpperCamelCase = crop_size if crop_size is not None else {"""height""": 2_2_4, """width""": 2_2_4} __UpperCamelCase = get_size_dict(lowercase , default_to_square=lowercase , 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 __lowerCamelCase ( self , lowercase , lowercase , lowercase = PILImageResampling.BILINEAR , lowercase = None , **lowercase , ) -> np.ndarray: __UpperCamelCase = get_size_dict(lowercase ) if "shortest_edge" in size: __UpperCamelCase = get_resize_output_image_size(lowercase , size=size["""shortest_edge"""] , default_to_square=lowercase ) # 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(lowercase , size=lowercase , resample=lowercase , data_format=lowercase , **lowercase ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> np.ndarray: __UpperCamelCase = get_size_dict(lowercase ) 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(lowercase , size=(size["""height"""], size["""width"""]) , data_format=lowercase , **lowercase ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase = None , **lowercase ) -> np.ndarray: return rescale(lowercase , scale=lowercase , data_format=lowercase , **lowercase ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase = None , **lowercase , ) -> np.ndarray: return normalize(lowercase , mean=lowercase , std=lowercase , data_format=lowercase , **lowercase ) def __lowerCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> BatchFeature: __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(lowercase , param_name="""crop_size""" , default_to_square=lowercase ) __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(lowercase ) if not is_batched(lowercase ): __UpperCamelCase = [images] if not valid_images(lowercase ): 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(lowercase ) for image in images] if do_resize: __UpperCamelCase = [self.resize(image=lowercase , size=lowercase , resample=lowercase ) for image in images] if do_center_crop: __UpperCamelCase = [self.center_crop(image=lowercase , size=lowercase ) for image in images] if do_rescale: __UpperCamelCase = [self.rescale(image=lowercase , scale=lowercase ) for image in images] if do_normalize: __UpperCamelCase = [self.normalize(image=lowercase , mean=lowercase , std=lowercase ) for image in images] __UpperCamelCase = [to_channel_dimension_format(lowercase , lowercase ) for image in images] __UpperCamelCase = {"""pixel_values""": images} return BatchFeature(data=lowercase , tensor_type=lowercase )
349
'''simple docstring''' import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowercase ( __A ,__A=False ): '''simple docstring''' try: __UpperCamelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __UpperCamelCase = default else: # KEY is set, convert it to True or False. try: __UpperCamelCase = strtobool(__A ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no." ) return _value a__ : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) a__ : Union[str, Any] = parse_flag_from_env('RUN_REMOTE', default=False) a__ : Any = parse_flag_from_env('RUN_LOCAL', default=True) a__ : List[Any] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a__ : Optional[int] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a__ : Optional[int] = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a__ : Optional[Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a__ : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a__ : str = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a__ : str = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a__ : Tuple = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowercase ( __A ): '''simple docstring''' try: import faiss # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires faiss""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import regex # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires regex""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import elasticsearch # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires elasticsearch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import sqlalchemy # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires sqlalchemy""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TORCH_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires PyTorch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TF_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires TensorFlow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.JAX_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires JAX""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.PIL_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires Pillow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import transformers # noqa F401 except ImportError: return unittest.skip("""test requires transformers""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import tiktoken # noqa F401 except ImportError: return unittest.skip("""test requires tiktoken""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import spacy # noqa F401 except ImportError: return unittest.skip("""test requires spacy""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' def _require_spacy_model(__A ): try: import spacy # noqa F401 spacy.load(__A ) except ImportError: return unittest.skip("""test requires spacy""" )(__A ) except OSError: return unittest.skip("""test requires spacy model '{}'""".format(__A ) )(__A ) else: return test_case return _require_spacy_model def _lowercase ( __A ): '''simple docstring''' try: import pyspark # noqa F401 except ImportError: return unittest.skip("""test requires pyspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import joblibspark # noqa F401 except ImportError: return unittest.skip("""test requires joblibspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_slow_tests or _run_slow_tests == 0: __UpperCamelCase = unittest.skip("""test is slow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_local_tests or _run_local_tests == 0: __UpperCamelCase = unittest.skip("""test is local""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_packaged_tests or _run_packaged_tests == 0: __UpperCamelCase = unittest.skip("""test is packaged""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_remote_tests or _run_remote_tests == 0: __UpperCamelCase = unittest.skip("""test requires remote""" )(__A ) return test_case def _lowercase ( *__A ): '''simple docstring''' def decorate(cls ): for name, fn in cls.__dict__.items(): if callable(__A ) and name.startswith("""test""" ): for decorator in decorators: __UpperCamelCase = decorator(__A ) setattr(cls ,__A ,__A ) return cls return decorate class UpperCAmelCase__ ( UpperCAmelCase_): pass class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 @contextmanager def _lowercase ( __A=OfflineSimulationMode.CONNECTION_FAILS ,__A=1E-16 ): '''simple docstring''' __UpperCamelCase = requests.Session().request def timeout_request(__A ,__A ,__A ,**__A ): # Change the url to an invalid url so that the connection hangs __UpperCamelCase = """https://10.255.255.1""" if kwargs.get("""timeout""" ) is None: raise RequestWouldHangIndefinitelyError( f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) __UpperCamelCase = timeout try: return online_request(__A ,__A ,**__A ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __UpperCamelCase = url __UpperCamelCase = e.args[0] __UpperCamelCase = (max_retry_error.args[0].replace("""10.255.255.1""" ,f"OfflineMock[{url}]" ),) __UpperCamelCase = (max_retry_error,) raise def raise_connection_error(__A ,__A ,**__A ): raise requests.ConnectionError("""Offline mode is enabled.""" ,request=__A ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("""requests.Session.send""" ,__A ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("""requests.Session.request""" ,__A ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,__A ): yield else: raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" ) @contextmanager def _lowercase ( *__A ,**__A ): '''simple docstring''' __UpperCamelCase = str(Path().resolve() ) with tempfile.TemporaryDirectory(*__A ,**__A ) as tmp_dir: try: os.chdir(__A ) yield finally: os.chdir(__A ) @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowercase ( __A ,__A ): '''simple docstring''' return deepcopy(__A ).integers(0 ,100 ,10 ).tolist() == deepcopy(__A ).integers(0 ,100 ,10 ).tolist() def _lowercase ( __A ): '''simple docstring''' import decorator from requests.exceptions import HTTPError def _wrapper(__A ,*__A ,**__A ): try: return func(*__A ,**__A ) except HTTPError as err: if str(__A ).startswith("""500""" ) or str(__A ).startswith("""502""" ): pytest.xfail(str(__A ) ) raise err return decorator.decorator(_wrapper ,__A ) class UpperCAmelCase__ : def __init__( self , lowercase , lowercase , lowercase ) -> str: __UpperCamelCase = returncode __UpperCamelCase = stdout __UpperCamelCase = stderr async def _lowercase ( __A ,__A ): '''simple docstring''' while True: __UpperCamelCase = await stream.readline() if line: callback(__A ) else: break async def _lowercase ( __A ,__A=None ,__A=None ,__A=None ,__A=False ,__A=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(__A ) ) __UpperCamelCase = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=__A ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=__A ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __UpperCamelCase = [] __UpperCamelCase = [] def tee(__A ,__A ,__A ,__A="" ): __UpperCamelCase = line.decode("""utf-8""" ).rstrip() sink.append(__A ) if not quiet: print(__A ,__A ,file=__A ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __A : tee(__A ,__A ,sys.stdout ,label="""stdout:""" ) ), _read_stream(p.stderr ,lambda __A : tee(__A ,__A ,sys.stderr ,label="""stderr:""" ) ), ] ,timeout=__A ,) return _RunOutput(await p.wait() ,__A ,__A ) def _lowercase ( __A ,__A=None ,__A=None ,__A=180 ,__A=False ,__A=True ): '''simple docstring''' __UpperCamelCase = asyncio.get_event_loop() __UpperCamelCase = loop.run_until_complete( _stream_subprocess(__A ,env=__A ,stdin=__A ,timeout=__A ,quiet=__A ,echo=__A ) ) __UpperCamelCase = """ """.join(__A ) if result.returncode > 0: __UpperCamelCase = """\n""".join(result.stderr ) raise RuntimeError( f"'{cmd_str}' failed with returncode {result.returncode}\n\n" f"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f"'{cmd_str}' produced no output." ) return result def _lowercase ( ): '''simple docstring''' __UpperCamelCase = os.environ.get("""PYTEST_XDIST_WORKER""" ,"""gw0""" ) __UpperCamelCase = re.sub(R"""^gw""" ,"""""" ,__A ,0 ,re.M ) return int(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = 29_500 __UpperCamelCase = pytest_xdist_worker_id() return port + uniq_delta
349
1
'''simple docstring''' from collections.abc import Generator from math import sin def _lowercase ( __A ): '''simple docstring''' if len(__A ) != 32: raise ValueError("""Input must be of length 32""" ) __UpperCamelCase = b"""""" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def _lowercase ( __A ): '''simple docstring''' if i < 0: raise ValueError("""Input must be non-negative""" ) __UpperCamelCase = format(__A ,"""08x""" )[-8:] __UpperCamelCase = b"""""" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8""" ) return little_endian_hex def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = b"""""" for char in message: bit_string += format(__A ,"""08b""" ).encode("""utf-8""" ) __UpperCamelCase = format(len(__A ) ,"""064b""" ).encode("""utf-8""" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__A ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def _lowercase ( __A ): '''simple docstring''' if len(__A ) % 512 != 0: raise ValueError("""Input must have length that's a multiple of 512""" ) for pos in range(0 ,len(__A ) ,512 ): __UpperCamelCase = bit_string[pos : pos + 512] __UpperCamelCase = [] for i in range(0 ,512 ,32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) ,2 ) ) yield block_words def _lowercase ( __A ): '''simple docstring''' if i < 0: raise ValueError("""Input must be non-negative""" ) __UpperCamelCase = format(__A ,"""032b""" ) __UpperCamelCase = """""" for c in i_str: new_str += "1" if c == "0" else "0" return int(__A ,2 ) def _lowercase ( __A ,__A ): '''simple docstring''' return (a + b) % 2**32 def _lowercase ( __A ,__A ): '''simple docstring''' if i < 0: raise ValueError("""Input must be non-negative""" ) if shift < 0: raise ValueError("""Shift must be non-negative""" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = preprocess(__A ) __UpperCamelCase = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states __UpperCamelCase = 0x67_45_23_01 __UpperCamelCase = 0xEF_CD_AB_89 __UpperCamelCase = 0x98_BA_DC_FE __UpperCamelCase = 0x10_32_54_76 __UpperCamelCase = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__A ): __UpperCamelCase = aa __UpperCamelCase = ba __UpperCamelCase = ca __UpperCamelCase = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f __UpperCamelCase = d ^ (b & (c ^ d)) __UpperCamelCase = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f __UpperCamelCase = c ^ (d & (b ^ c)) __UpperCamelCase = (5 * i + 1) % 16 elif i <= 47: __UpperCamelCase = b ^ c ^ d __UpperCamelCase = (3 * i + 5) % 16 else: __UpperCamelCase = c ^ (b | not_aa(__A )) __UpperCamelCase = (7 * i) % 16 __UpperCamelCase = (f + a + added_consts[i] + block_words[g]) % 2**32 __UpperCamelCase = d __UpperCamelCase = c __UpperCamelCase = b __UpperCamelCase = sum_aa(__A ,left_rotate_aa(__A ,shift_amounts[i] ) ) # Add hashed chunk to running total __UpperCamelCase = sum_aa(__A ,__A ) __UpperCamelCase = sum_aa(__A ,__A ) __UpperCamelCase = sum_aa(__A ,__A ) __UpperCamelCase = sum_aa(__A ,__A ) __UpperCamelCase = reformat_hex(__A ) + reformat_hex(__A ) + reformat_hex(__A ) + reformat_hex(__A ) return digest if __name__ == "__main__": import doctest doctest.testmod()
349
'''simple docstring''' import re def _lowercase ( __A ): '''simple docstring''' return [char.split() for char in re.split(R"""[^ a-z A-Z 0-9 \s]""" ,str_ )] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = split_input(str_ ) return "".join( ["""""".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' try: __UpperCamelCase = split_input(__A ) if upper: __UpperCamelCase = """""".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __UpperCamelCase = """""".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _lowercase ( __A ): '''simple docstring''' return to_simple_case(__A ) def _lowercase ( __A ): '''simple docstring''' try: __UpperCamelCase = to_simple_case(__A ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""_""" ) def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""-""" ) if __name__ == "__main__": __import__('doctest').testmod()
349
1
'''simple docstring''' import math def _lowercase ( __A = 100 ): '''simple docstring''' __UpperCamelCase = sum(i * i for i in range(1 ,n + 1 ) ) __UpperCamelCase = int(math.pow(sum(range(1 ,n + 1 ) ) ,2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f'''{solution() = }''')
349
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCamelCase ( self ) -> int: __UpperCamelCase = 1 __UpperCamelCase = 3 __UpperCamelCase = (3_2, 3_2) __UpperCamelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowercase ) return image @property def __lowerCamelCase ( self ) -> Dict: torch.manual_seed(0 ) __UpperCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) return model @property def __lowerCamelCase ( self ) -> List[str]: torch.manual_seed(0 ) __UpperCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def __lowerCamelCase ( self ) -> Optional[int]: torch.manual_seed(0 ) __UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(lowercase ) @property def __lowerCamelCase ( self ) -> Tuple: def extract(*lowercase , **lowercase ): class UpperCAmelCase__ : def __init__( self ) -> Tuple: __UpperCamelCase = torch.ones([0] ) def __lowerCamelCase ( self , lowercase ) -> List[str]: self.pixel_values.to(lowercase ) return self return Out() return extract def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=lowercase ) assert isinstance(lowercase , lowercase ) assert isinstance(pipe.scheduler , lowercase ) assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowercase ) __UpperCamelCase = StableDiffusionPipeline.from_pretrained(lowercase ) # sanity check that the pipeline still works assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 __UpperCamelCase = unet.half() __UpperCamelCase = vae.half() __UpperCamelCase = bert.half() # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 6_4, 6_4, 3) @nightly @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) __UpperCamelCase = 4_0_0_3_6_6_0_3_4_6 __UpperCamelCase = 7 # without safety guidance (sld_guidance_scale = 0) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """padme amidala taking a bath artwork, safe for work, no nudity""" __UpperCamelCase = 2_7_3_4_9_7_1_7_5_5 __UpperCamelCase = 7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) __UpperCamelCase = 1_0_4_4_3_5_5_2_3_4 __UpperCamelCase = 1_2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
349
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Dict = logging.get_logger(__name__) a__ : Union[str, Any] = { 'uw-madison/mra-base-512-4': 'https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json', } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''mra''' def __init__( self , lowercase=5_0_2_6_5 , lowercase=7_6_8 , lowercase=1_2 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=5_1_2 , lowercase=1 , lowercase=0.02 , lowercase=1E-5 , lowercase="absolute" , lowercase=4 , lowercase="full" , lowercase=0 , lowercase=0 , lowercase=1 , lowercase=0 , lowercase=2 , **lowercase , ) -> Optional[Any]: super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) __UpperCamelCase = vocab_size __UpperCamelCase = max_position_embeddings __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 = initializer_range __UpperCamelCase = type_vocab_size __UpperCamelCase = layer_norm_eps __UpperCamelCase = position_embedding_type __UpperCamelCase = block_per_row __UpperCamelCase = approx_mode __UpperCamelCase = initial_prior_first_n_blocks __UpperCamelCase = initial_prior_diagonal_n_blocks
349
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> str: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Any: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] )
349
1
'''simple docstring''' import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING a__ : Any = logging.get_logger(__name__) a__ : str = { 'microsoft/conditional-detr-resnet-50': ( 'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json' ), } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''conditional_detr''' __SCREAMING_SNAKE_CASE = ['''past_key_values'''] __SCREAMING_SNAKE_CASE = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , lowercase=True , lowercase=None , lowercase=3 , lowercase=3_0_0 , lowercase=6 , lowercase=2_0_4_8 , lowercase=8 , lowercase=6 , lowercase=2_0_4_8 , lowercase=8 , lowercase=0.0 , lowercase=0.0 , lowercase=True , lowercase="relu" , lowercase=2_5_6 , lowercase=0.1 , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=1.0 , lowercase=False , lowercase="sine" , lowercase="resnet50" , lowercase=True , lowercase=False , lowercase=2 , lowercase=5 , lowercase=2 , lowercase=1 , lowercase=1 , lowercase=2 , lowercase=5 , lowercase=2 , lowercase=0.25 , **lowercase , ) -> Any: 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(lowercase , lowercase ): __UpperCamelCase = backbone_config.get("""model_type""" ) __UpperCamelCase = CONFIG_MAPPING[backbone_model_type] __UpperCamelCase = config_class.from_dict(lowercase ) __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 = cls_loss_coefficient __UpperCamelCase = bbox_loss_coefficient __UpperCamelCase = giou_loss_coefficient __UpperCamelCase = focal_alpha super().__init__(is_encoder_decoder=lowercase , **lowercase ) @property def __lowerCamelCase ( self ) -> int: return self.encoder_attention_heads @property def __lowerCamelCase ( self ) -> int: return self.d_model def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __UpperCamelCase = self.backbone_config.to_dict() __UpperCamelCase = self.__class__.model_type return output class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = version.parse('''1.11''') @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def __lowerCamelCase ( self ) -> float: return 1E-5 @property def __lowerCamelCase ( self ) -> int: return 1_2
349
'''simple docstring''' import logging import os from .state import PartialState class UpperCAmelCase__ ( logging.LoggerAdapter): @staticmethod def __lowerCamelCase ( lowercase ) -> Dict: __UpperCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __lowerCamelCase ( self , lowercase , lowercase , *lowercase , **lowercase ) -> List[str]: if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) __UpperCamelCase = kwargs.pop("""main_process_only""" , lowercase ) __UpperCamelCase = kwargs.pop("""in_order""" , lowercase ) if self.isEnabledFor(lowercase ): if self._should_log(lowercase ): __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) elif in_order: __UpperCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) state.wait_for_everyone() def _lowercase ( __A ,__A = None ): '''simple docstring''' if log_level is None: __UpperCamelCase = os.environ.get("""ACCELERATE_LOG_LEVEL""" ,__A ) __UpperCamelCase = logging.getLogger(__A ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__A ,{} )
349
1
'''simple docstring''' import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class UpperCAmelCase__ : @staticmethod def __lowerCamelCase ( *lowercase , **lowercase ) -> int: pass def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class UpperCAmelCase__ ( unittest.TestCase): __SCREAMING_SNAKE_CASE = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Union[str, Any]: __UpperCamelCase = DepthEstimationPipeline(model=lowercase , image_processor=lowercase ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __lowerCamelCase ( self , lowercase , lowercase ) -> Tuple: __UpperCamelCase = depth_estimator("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) self.assertEqual({"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )} , lowercase ) import datasets __UpperCamelCase = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) __UpperCamelCase = depth_estimator( [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] ) self.assertEqual( [ {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, ] , lowercase , ) @require_tf @unittest.skip("""Depth estimation is not implemented in TF""" ) def __lowerCamelCase ( self ) -> Any: pass @slow @require_torch def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = """Intel/dpt-large""" __UpperCamelCase = pipeline("""depth-estimation""" , model=lowercase ) __UpperCamelCase = depth_estimator("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) __UpperCamelCase = hashimage(outputs["""depth"""] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs["""predicted_depth"""].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs["""predicted_depth"""].min().item() ) , 2.662 ) @require_torch def __lowerCamelCase ( self ) -> Tuple: # This is highly irregular to have no small tests. self.skipTest("""There is not hf-internal-testing tiny model for either GLPN nor DPT""" )
349
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase__ : def __init__( self ) -> Any: __UpperCamelCase = False def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase ) -> str: if not self.initialized: __UpperCamelCase = RagRetriever( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = True def __lowerCamelCase ( self ) -> Optional[Any]: self.retriever.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.retriever._main_retrieve(lowercase , lowercase ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase=None ) -> List[Any]: if index is not None and index.is_initialized() and len(lowercase ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowercase , lowercase , lowercase , lowercase ) for worker in self.retrieval_workers ] ) def __lowerCamelCase ( self ) -> Dict: logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> List[str]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCamelCase = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCamelCase , __UpperCamelCase = ray.get(random_worker.retrieve.remote(lowercase , lowercase ) ) else: __UpperCamelCase , __UpperCamelCase = self._main_retrieve(lowercase , lowercase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase=None , **lowercase ) -> Any: return super(lowercase , cls ).get_tokenizers(lowercase , lowercase , **lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase=None , **lowercase ) -> int: __UpperCamelCase = kwargs.pop("""config""" , lowercase ) or RagConfig.from_pretrained(lowercase , **lowercase ) __UpperCamelCase = RagTokenizer.from_pretrained(lowercase , config=lowercase ) __UpperCamelCase = rag_tokenizer.question_encoder __UpperCamelCase = rag_tokenizer.generator if indexed_dataset is not None: __UpperCamelCase = """custom""" __UpperCamelCase = CustomHFIndex(config.retrieval_vector_size , lowercase ) else: __UpperCamelCase = cls._build_index(lowercase ) return cls( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , retrieval_workers=lowercase , index=lowercase , )
349
1
'''simple docstring''' import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = checkpoint __UpperCamelCase = {} __UpperCamelCase = vae_state_dict["""encoder.conv_in.weight"""] __UpperCamelCase = vae_state_dict["""encoder.conv_in.bias"""] __UpperCamelCase = vae_state_dict["""encoder.conv_out.weight"""] __UpperCamelCase = vae_state_dict["""encoder.conv_out.bias"""] __UpperCamelCase = vae_state_dict["""encoder.norm_out.weight"""] __UpperCamelCase = vae_state_dict["""encoder.norm_out.bias"""] __UpperCamelCase = vae_state_dict["""decoder.conv_in.weight"""] __UpperCamelCase = vae_state_dict["""decoder.conv_in.bias"""] __UpperCamelCase = vae_state_dict["""decoder.conv_out.weight"""] __UpperCamelCase = vae_state_dict["""decoder.conv_out.bias"""] __UpperCamelCase = vae_state_dict["""decoder.norm_out.weight"""] __UpperCamelCase = vae_state_dict["""decoder.norm_out.bias"""] __UpperCamelCase = vae_state_dict["""quant_conv.weight"""] __UpperCamelCase = vae_state_dict["""quant_conv.bias"""] __UpperCamelCase = vae_state_dict["""post_quant_conv.weight"""] __UpperCamelCase = vae_state_dict["""post_quant_conv.bias"""] # Retrieves the keys for the encoder down blocks only __UpperCamelCase = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """encoder.down""" in layer} ) __UpperCamelCase = { layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(__A ) } # Retrieves the keys for the decoder up blocks only __UpperCamelCase = len({""".""".join(layer.split(""".""" )[:3] ) for layer in vae_state_dict if """decoder.up""" in layer} ) __UpperCamelCase = { layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(__A ) } for i in range(__A ): __UpperCamelCase = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key] if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict: __UpperCamelCase = vae_state_dict.pop( f"encoder.down.{i}.downsample.conv.weight" ) __UpperCamelCase = vae_state_dict.pop( f"encoder.down.{i}.downsample.conv.bias" ) __UpperCamelCase = renew_vae_resnet_paths(__A ) __UpperCamelCase = {"""old""": f"down.{i}.block", """new""": f"down_blocks.{i}.resnets"} assign_to_checkpoint(__A ,__A ,__A ,additional_replacements=[meta_path] ,config=__A ) __UpperCamelCase = [key for key in vae_state_dict if """encoder.mid.block""" in key] __UpperCamelCase = 2 for i in range(1 ,num_mid_res_blocks + 1 ): __UpperCamelCase = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key] __UpperCamelCase = renew_vae_resnet_paths(__A ) __UpperCamelCase = {"""old""": f"mid.block_{i}", """new""": f"mid_block.resnets.{i - 1}"} assign_to_checkpoint(__A ,__A ,__A ,additional_replacements=[meta_path] ,config=__A ) __UpperCamelCase = [key for key in vae_state_dict if """encoder.mid.attn""" in key] __UpperCamelCase = renew_vae_attention_paths(__A ) __UpperCamelCase = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(__A ,__A ,__A ,additional_replacements=[meta_path] ,config=__A ) conv_attn_to_linear(__A ) for i in range(__A ): __UpperCamelCase = num_up_blocks - 1 - i __UpperCamelCase = [ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key ] if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict: __UpperCamelCase = vae_state_dict[ f"decoder.up.{block_id}.upsample.conv.weight" ] __UpperCamelCase = vae_state_dict[ f"decoder.up.{block_id}.upsample.conv.bias" ] __UpperCamelCase = renew_vae_resnet_paths(__A ) __UpperCamelCase = {"""old""": f"up.{block_id}.block", """new""": f"up_blocks.{i}.resnets"} assign_to_checkpoint(__A ,__A ,__A ,additional_replacements=[meta_path] ,config=__A ) __UpperCamelCase = [key for key in vae_state_dict if """decoder.mid.block""" in key] __UpperCamelCase = 2 for i in range(1 ,num_mid_res_blocks + 1 ): __UpperCamelCase = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key] __UpperCamelCase = renew_vae_resnet_paths(__A ) __UpperCamelCase = {"""old""": f"mid.block_{i}", """new""": f"mid_block.resnets.{i - 1}"} assign_to_checkpoint(__A ,__A ,__A ,additional_replacements=[meta_path] ,config=__A ) __UpperCamelCase = [key for key in vae_state_dict if """decoder.mid.attn""" in key] __UpperCamelCase = renew_vae_attention_paths(__A ) __UpperCamelCase = {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""} assign_to_checkpoint(__A ,__A ,__A ,additional_replacements=[meta_path] ,config=__A ) conv_attn_to_linear(__A ) return new_checkpoint def _lowercase ( __A ,__A ,): '''simple docstring''' __UpperCamelCase = requests.get( """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml""" ) __UpperCamelCase = io.BytesIO(r.content ) __UpperCamelCase = OmegaConf.load(__A ) __UpperCamelCase = 512 __UpperCamelCase = """cuda""" if torch.cuda.is_available() else """cpu""" if checkpoint_path.endswith("""safetensors""" ): from safetensors import safe_open __UpperCamelCase = {} with safe_open(__A ,framework="""pt""" ,device="""cpu""" ) as f: for key in f.keys(): __UpperCamelCase = f.get_tensor(__A ) else: __UpperCamelCase = torch.load(__A ,map_location=__A )["""state_dict"""] # Convert the VAE model. __UpperCamelCase = create_vae_diffusers_config(__A ,image_size=__A ) __UpperCamelCase = custom_convert_ldm_vae_checkpoint(__A ,__A ) __UpperCamelCase = AutoencoderKL(**__A ) vae.load_state_dict(__A ) vae.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('--vae_pt_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.') parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the VAE.pt to convert.') a__ : Optional[int] = parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
349
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : Any = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': 5_1_2, 'squeezebert/squeezebert-mnli': 5_1_2, 'squeezebert/squeezebert-mnli-headless': 5_1_2, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class UpperCAmelCase__ ( UpperCAmelCase_): __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 = SqueezeBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> Tuple: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) __UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowercase ) != tokenize_chinese_chars ): __UpperCamelCase = getattr(lowercase , normalizer_state.pop("""type""" ) ) __UpperCamelCase = do_lower_case __UpperCamelCase = strip_accents __UpperCamelCase = tokenize_chinese_chars __UpperCamelCase = normalizer_class(**lowercase ) __UpperCamelCase = do_lower_case def __lowerCamelCase ( self , lowercase , lowercase=None ) -> Tuple: __UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __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 __lowerCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: __UpperCamelCase = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
349
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> str: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Any: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] )
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a__ : str = { 'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'], 'processing_trocr': ['TrOCRProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ 'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrOCRForCausalLM', 'TrOCRPreTrainedModel', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = StableDiffusionControlNetImgaImgPipeline __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''}) __SCREAMING_SNAKE_CASE = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowerCamelCase ( self ) -> int: torch.manual_seed(0 ) __UpperCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) torch.manual_seed(0 ) __UpperCamelCase = ControlNetModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=3_2 , conditioning_embedding_out_channels=(1_6, 3_2) , ) torch.manual_seed(0 ) __UpperCamelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) torch.manual_seed(0 ) __UpperCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) __UpperCamelCase = CLIPTextModel(lowercase ) __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __UpperCamelCase = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __lowerCamelCase ( self , lowercase , lowercase=0 ) -> Dict: if str(lowercase ).startswith("""mps""" ): __UpperCamelCase = torch.manual_seed(lowercase ) else: __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(lowercase ) __UpperCamelCase = 2 __UpperCamelCase = randn_tensor( (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor) , generator=lowercase , device=torch.device(lowercase ) , ) __UpperCamelCase = floats_tensor(control_image.shape , rng=random.Random(lowercase ) ).to(lowercase ) __UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCamelCase = Image.fromarray(np.uinta(lowercase ) ).convert("""RGB""" ).resize((6_4, 6_4) ) __UpperCamelCase = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def __lowerCamelCase ( self ) -> Any: return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __lowerCamelCase ( self ) -> Any: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def __lowerCamelCase ( self ) -> Optional[int]: self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = StableDiffusionControlNetImgaImgPipeline __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} __SCREAMING_SNAKE_CASE = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __SCREAMING_SNAKE_CASE = frozenset([]) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def __lowerCamelCase ( self ) -> Union[str, Any]: torch.manual_seed(0 ) __UpperCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) torch.manual_seed(0 ) def init_weights(lowercase ): if isinstance(lowercase , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) __UpperCamelCase = ControlNetModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=3_2 , conditioning_embedding_out_channels=(1_6, 3_2) , ) controlneta.controlnet_down_blocks.apply(lowercase ) torch.manual_seed(0 ) __UpperCamelCase = ControlNetModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , in_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , cross_attention_dim=3_2 , conditioning_embedding_out_channels=(1_6, 3_2) , ) controlneta.controlnet_down_blocks.apply(lowercase ) torch.manual_seed(0 ) __UpperCamelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) torch.manual_seed(0 ) __UpperCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) __UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) __UpperCamelCase = CLIPTextModel(lowercase ) __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) __UpperCamelCase = MultiControlNetModel([controlneta, controlneta] ) __UpperCamelCase = { """unet""": unet, """controlnet""": controlnet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __lowerCamelCase ( self , lowercase , lowercase=0 ) -> List[Any]: if str(lowercase ).startswith("""mps""" ): __UpperCamelCase = torch.manual_seed(lowercase ) else: __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(lowercase ) __UpperCamelCase = 2 __UpperCamelCase = [ randn_tensor( (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor) , generator=lowercase , device=torch.device(lowercase ) , ), randn_tensor( (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor) , generator=lowercase , device=torch.device(lowercase ) , ), ] __UpperCamelCase = floats_tensor(control_image[0].shape , rng=random.Random(lowercase ) ).to(lowercase ) __UpperCamelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __UpperCamelCase = Image.fromarray(np.uinta(lowercase ) ).convert("""RGB""" ).resize((6_4, 6_4) ) __UpperCamelCase = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", """image""": image, """control_image""": control_image, } return inputs def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.get_dummy_components() __UpperCamelCase = self.pipeline_class(**lowercase ) pipe.to(lowercase ) __UpperCamelCase = 10.0 __UpperCamelCase = 4 __UpperCamelCase = self.get_dummy_inputs(lowercase ) __UpperCamelCase = steps __UpperCamelCase = scale __UpperCamelCase = pipe(**lowercase )[0] __UpperCamelCase = self.get_dummy_inputs(lowercase ) __UpperCamelCase = steps __UpperCamelCase = scale __UpperCamelCase = pipe(**lowercase , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] __UpperCamelCase = self.get_dummy_inputs(lowercase ) __UpperCamelCase = steps __UpperCamelCase = scale __UpperCamelCase = pipe(**lowercase , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] __UpperCamelCase = self.get_dummy_inputs(lowercase ) __UpperCamelCase = steps __UpperCamelCase = scale __UpperCamelCase = pipe(**lowercase , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def __lowerCamelCase ( self ) -> Optional[int]: return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __lowerCamelCase ( self ) -> Optional[int]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def __lowerCamelCase ( self ) -> Union[str, Any]: self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.get_dummy_components() __UpperCamelCase = self.pipeline_class(**lowercase ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(lowercase ) except NotImplementedError: pass @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = ControlNetModel.from_pretrained("""lllyasviel/sd-controlnet-canny""" ) __UpperCamelCase = StableDiffusionControlNetImgaImgPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase , controlnet=lowercase ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = torch.Generator(device="""cpu""" ).manual_seed(0 ) __UpperCamelCase = """evil space-punk bird""" __UpperCamelCase = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ).resize((5_1_2, 5_1_2) ) __UpperCamelCase = load_image( """https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png""" ).resize((5_1_2, 5_1_2) ) __UpperCamelCase = pipe( lowercase , lowercase , control_image=lowercase , generator=lowercase , output_type="""np""" , num_inference_steps=5_0 , strength=0.6 , ) __UpperCamelCase = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) __UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy""" ) assert np.abs(expected_image - image ).max() < 9E-2
349
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig a__ : Union[str, Any] = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''albert''' def __init__( self , lowercase=3_0_0_0_0 , lowercase=1_2_8 , lowercase=4_0_9_6 , lowercase=1_2 , lowercase=1 , lowercase=6_4 , lowercase=1_6_3_8_4 , lowercase=1 , lowercase="gelu_new" , lowercase=0 , lowercase=0 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=0.1 , lowercase="absolute" , lowercase=0 , lowercase=2 , lowercase=3 , **lowercase , ) -> Any: super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) __UpperCamelCase = vocab_size __UpperCamelCase = embedding_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_hidden_groups __UpperCamelCase = num_attention_heads __UpperCamelCase = inner_group_num __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 = classifier_dropout_prob __UpperCamelCase = position_embedding_type class UpperCAmelCase__ ( UpperCAmelCase_): @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
349
1
'''simple docstring''' from jiwer import compute_measures import datasets a__ : str = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' a__ : int = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe 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.\n\nThis 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.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' a__ : Union[str, Any] = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCAmelCase__ ( datasets.Metric): def __lowerCamelCase ( self ) -> Optional[int]: 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 __lowerCamelCase ( self , lowercase=None , lowercase=None , lowercase=False ) -> List[Any]: if concatenate_texts: return compute_measures(lowercase , lowercase )["wer"] else: __UpperCamelCase = 0 __UpperCamelCase = 0 for prediction, reference in zip(lowercase , lowercase ): __UpperCamelCase = compute_measures(lowercase , lowercase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
349
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _lowercase ( __A ): '''simple docstring''' return (data["data"], data["target"]) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = XGBRegressor(verbosity=0 ,random_state=42 ) xgb.fit(__A ,__A ) # Predict target for test data __UpperCamelCase = xgb.predict(__A ) __UpperCamelCase = predictions.reshape(len(__A ) ,1 ) return predictions def _lowercase ( ): '''simple docstring''' __UpperCamelCase = fetch_california_housing() __UpperCamelCase , __UpperCamelCase = data_handling(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = train_test_split( __A ,__A ,test_size=0.25 ,random_state=1 ) __UpperCamelCase = xgboost(__A ,__A ,__A ) # Error printing print(f"Mean Absolute Error : {mean_absolute_error(__A ,__A )}" ) print(f"Mean Square Error : {mean_squared_error(__A ,__A )}" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
349
1
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def _lowercase ( __A ,__A ,__A ,__A = 100 ,): '''simple docstring''' __UpperCamelCase = x_start __UpperCamelCase = fnc(__A ) __UpperCamelCase = 0.0 for _ in range(__A ): # Approximates small segments of curve as linear and solve # for trapezoidal area __UpperCamelCase = (x_end - x_start) / steps + xa __UpperCamelCase = fnc(__A ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __UpperCamelCase = xa __UpperCamelCase = fxa return area if __name__ == "__main__": def _lowercase ( __A ): '''simple docstring''' return x**3 + x**2 print('f(x) = x^3 + x^2') print('The area between the curve, x = -5, x = 5 and the x axis is:') a__ : Optional[Any] = 1_0 while i <= 1_0_0_0_0_0: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 1_0
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=2 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=4_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: __UpperCamelCase = TFPegasusModel(config=lowercase ).get_decoder() __UpperCamelCase = inputs_dict["""input_ids"""] __UpperCamelCase = input_ids[:1, :] __UpperCamelCase = inputs_dict["""attention_mask"""][:1, :] __UpperCamelCase = inputs_dict["""head_mask"""] __UpperCamelCase = 1 # first forward pass __UpperCamelCase = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) __UpperCamelCase , __UpperCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __UpperCamelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) __UpperCamelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __UpperCamelCase = model(lowercase , attention_mask=lowercase )[0] __UpperCamelCase = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __UpperCamelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx] __UpperCamelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1E-3 ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,__A=None ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = tf.cast(tf.math.not_equal(__A ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: __UpperCamelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: __UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration,) if is_tf_available() else () __SCREAMING_SNAKE_CASE = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> str: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase__ ( unittest.TestCase): __SCREAMING_SNAKE_CASE = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] __SCREAMING_SNAKE_CASE = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers __SCREAMING_SNAKE_CASE = '''google/pegasus-xsum''' @cached_property def __lowerCamelCase ( self ) -> int: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __lowerCamelCase ( self , **lowercase ) -> Optional[int]: __UpperCamelCase = self.translate_src_text(**lowercase ) assert self.expected_text == generated_words def __lowerCamelCase ( self , **lowercase ) -> Optional[Any]: __UpperCamelCase = self.tokenizer(self.src_text , **lowercase , padding=lowercase , return_tensors="""tf""" ) __UpperCamelCase = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) __UpperCamelCase = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase ) return generated_words @slow def __lowerCamelCase ( self ) -> Dict: self._assert_generated_batch_equal_expected()
349
1
'''simple docstring''' print((lambda quine: quine % quine)('print((lambda quine: quine %% quine)(%r))'))
349
'''simple docstring''' import string def _lowercase ( __A ): '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): __UpperCamelCase = """""" for symbol in message: if symbol in string.ascii_uppercase: __UpperCamelCase = string.ascii_uppercase.find(__A ) __UpperCamelCase = num - key if num < 0: __UpperCamelCase = num + len(string.ascii_uppercase ) __UpperCamelCase = translated + string.ascii_uppercase[num] else: __UpperCamelCase = translated + symbol print(f"Decryption using Key #{key}: {translated}" ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = input("""Encrypted message: """ ) __UpperCamelCase = message.upper() decrypt(__A ) if __name__ == "__main__": import doctest doctest.testmod() main()
349
1
'''simple docstring''' import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase__ : def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=True , lowercase=False , lowercase=False , lowercase=False , lowercase=2 , lowercase=9_9 , lowercase=0 , lowercase=3_2 , lowercase=5 , lowercase=4 , lowercase=0.1 , lowercase=0.1 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=2 , lowercase=4 , lowercase="last" , lowercase=True , lowercase=None , lowercase=0 , ) -> Dict: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_input_lengths __UpperCamelCase = use_token_type_ids __UpperCamelCase = use_labels __UpperCamelCase = gelu_activation __UpperCamelCase = sinusoidal_embeddings __UpperCamelCase = causal __UpperCamelCase = asm __UpperCamelCase = n_langs __UpperCamelCase = vocab_size __UpperCamelCase = n_special __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = type_sequence_label_size __UpperCamelCase = initializer_range __UpperCamelCase = num_labels __UpperCamelCase = num_choices __UpperCamelCase = summary_type __UpperCamelCase = use_proj __UpperCamelCase = scope __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None if self.use_input_lengths: __UpperCamelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __UpperCamelCase = None if self.use_token_type_ids: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __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] , 2 ).float() __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __lowerCamelCase ( self ) -> Any: return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Tuple: __UpperCamelCase = XLMModel(config=lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model(lowercase , lengths=lowercase , langs=lowercase ) __UpperCamelCase = model(lowercase , langs=lowercase ) __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Any: __UpperCamelCase = XLMWithLMHeadModel(lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model(lowercase , token_type_ids=lowercase , labels=lowercase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> int: __UpperCamelCase = XLMForQuestionAnsweringSimple(lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model(lowercase ) __UpperCamelCase = model(lowercase , start_positions=lowercase , end_positions=lowercase ) __UpperCamelCase = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> int: __UpperCamelCase = XLMForQuestionAnswering(lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model(lowercase ) __UpperCamelCase = model( lowercase , start_positions=lowercase , end_positions=lowercase , cls_index=lowercase , is_impossible=lowercase , p_mask=lowercase , ) __UpperCamelCase = model( lowercase , start_positions=lowercase , end_positions=lowercase , cls_index=lowercase , is_impossible=lowercase , ) ((__UpperCamelCase) , ) = result_with_labels.to_tuple() __UpperCamelCase = model(lowercase , start_positions=lowercase , end_positions=lowercase ) ((__UpperCamelCase) , ) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> List[str]: __UpperCamelCase = XLMForSequenceClassification(lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model(lowercase ) __UpperCamelCase = model(lowercase , labels=lowercase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> Union[str, Any]: __UpperCamelCase = self.num_labels __UpperCamelCase = XLMForTokenClassification(lowercase ) model.to(lowercase ) model.eval() __UpperCamelCase = model(lowercase , attention_mask=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ) -> str: __UpperCamelCase = self.num_choices __UpperCamelCase = XLMForMultipleChoice(config=lowercase ) model.to(lowercase ) 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( lowercase , attention_mask=lowercase , token_type_ids=lowercase , labels=lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths} return config, inputs_dict @require_torch class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) __SCREAMING_SNAKE_CASE = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Any: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("""Fast""" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def __lowerCamelCase ( self , lowercase , lowercase , lowercase=False ) -> Union[str, Any]: __UpperCamelCase = super()._prepare_for_class(lowercase , lowercase , return_labels=lowercase ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": __UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase ) __UpperCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowercase ) return inputs_dict def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = XLMModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , emb_dim=3_7 ) def __lowerCamelCase ( self ) -> Tuple: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*lowercase ) def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*lowercase ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*lowercase ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*lowercase ) def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*lowercase ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase=False , lowercase=1 ) -> List[Any]: self.assertIsInstance(lowercase , lowercase ) self.assertListEqual( [isinstance(lowercase , lowercase ) for iter_attentions in attentions] , [True] * len(lowercase ) ) self.assertEqual(len(lowercase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(lowercase ): # adds PAD dummy token __UpperCamelCase = min_length + idx + 1 __UpperCamelCase = min_length + idx + 1 __UpperCamelCase = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(lowercase ) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase=False , lowercase=1 ) -> Tuple: self.assertIsInstance(lowercase , lowercase ) self.assertListEqual( [isinstance(lowercase , lowercase ) for iter_hidden_states in hidden_states] , [True] * len(lowercase ) , ) self.assertEqual(len(lowercase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(lowercase ): # adds PAD dummy token __UpperCamelCase = min_length + idx + 1 __UpperCamelCase = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(lowercase ) , ) pass @slow def __lowerCamelCase ( self ) -> Any: for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = XLMModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_torch class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> int: __UpperCamelCase = XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048""" ) model.to(lowercase ) __UpperCamelCase = torch.tensor([[1_4, 4_4_7]] , dtype=torch.long , device=lowercase ) # the president __UpperCamelCase = [ 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference __UpperCamelCase = model.generate(lowercase , do_sample=lowercase ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , lowercase )
349
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : Dict = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''gptj''' __SCREAMING_SNAKE_CASE = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , lowercase=5_0_4_0_0 , lowercase=2_0_4_8 , lowercase=4_0_9_6 , lowercase=2_8 , lowercase=1_6 , lowercase=6_4 , lowercase=None , lowercase="gelu_new" , lowercase=0.0 , lowercase=0.0 , lowercase=0.0 , lowercase=1E-5 , lowercase=0.02 , lowercase=True , lowercase=5_0_2_5_6 , lowercase=5_0_2_5_6 , lowercase=False , **lowercase , ) -> Tuple: __UpperCamelCase = vocab_size __UpperCamelCase = n_positions __UpperCamelCase = n_embd __UpperCamelCase = n_layer __UpperCamelCase = n_head __UpperCamelCase = n_inner __UpperCamelCase = rotary_dim __UpperCamelCase = activation_function __UpperCamelCase = resid_pdrop __UpperCamelCase = embd_pdrop __UpperCamelCase = attn_pdrop __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = initializer_range __UpperCamelCase = use_cache __UpperCamelCase = bos_token_id __UpperCamelCase = eos_token_id super().__init__( bos_token_id=lowercase , eos_token_id=lowercase , tie_word_embeddings=lowercase , **lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase = "default" , lowercase = None , lowercase = False , ) -> List[str]: super().__init__(lowercase , task=lowercase , patching_specs=lowercase , use_past=lowercase ) if not getattr(self._config , """pad_token_id""" , lowercase ): # TODO: how to do that better? __UpperCamelCase = 0 @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: __UpperCamelCase = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(lowercase , direction="""inputs""" ) __UpperCamelCase = {0: """batch""", 1: """past_sequence + sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return common_inputs @property def __lowerCamelCase ( self ) -> int: return self._config.n_layer @property def __lowerCamelCase ( self ) -> int: return self._config.n_head def __lowerCamelCase ( self , lowercase , lowercase = -1 , lowercase = -1 , lowercase = False , lowercase = None , ) -> Mapping[str, Any]: __UpperCamelCase = super(lowercase , self ).generate_dummy_inputs( lowercase , batch_size=lowercase , seq_length=lowercase , is_pair=lowercase , framework=lowercase ) # We need to order the input in the way they appears in the forward() __UpperCamelCase = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __UpperCamelCase , __UpperCamelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __UpperCamelCase = seqlen + 2 __UpperCamelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __UpperCamelCase = [ (torch.zeros(lowercase ), torch.zeros(lowercase )) for _ in range(self.num_layers ) ] __UpperCamelCase = common_inputs["""attention_mask"""] if self.use_past: __UpperCamelCase = ordered_inputs["""attention_mask"""].dtype __UpperCamelCase = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(lowercase , lowercase , dtype=lowercase )] , dim=1 ) return ordered_inputs @property def __lowerCamelCase ( self ) -> int: return 1_3
349
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCAmelCase__ : def __init__( self , lowercase , ) -> Union[str, Any]: __UpperCamelCase = parent __UpperCamelCase = 1_3 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = 9_9 __UpperCamelCase = 3_2 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 3_7 __UpperCamelCase = """gelu""" __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 5_1_2 __UpperCamelCase = 1_6 __UpperCamelCase = 2 __UpperCamelCase = 0.02 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = None def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = None if self.use_input_mask: __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = TFDistilBertModel(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]: __UpperCamelCase = TFDistilBertForMaskedLM(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = TFDistilBertForQuestionAnswering(config=lowercase ) __UpperCamelCase = { """input_ids""": input_ids, """attention_mask""": input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForSequenceClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: __UpperCamelCase = self.num_choices __UpperCamelCase = TFDistilBertForMultipleChoice(lowercase ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForTokenClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.prepare_config_and_inputs() ((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFDistilBertModel, '''fill-mask''': TFDistilBertForMaskedLM, '''question-answering''': TFDistilBertForQuestionAnswering, '''text-classification''': TFDistilBertForSequenceClassification, '''token-classification''': TFDistilBertForTokenClassification, '''zero-shot''': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = TFDistilBertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , dim=3_7 ) def __lowerCamelCase ( self ) -> Any: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) @slow def __lowerCamelCase ( self ) -> Tuple: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): __UpperCamelCase = TFDistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_tf class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase = model(lowercase )[0] __UpperCamelCase = [1, 6, 7_6_8] self.assertEqual(output.shape , lowercase ) __UpperCamelCase = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-4 )
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a__ : int = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['LayoutLMv3FeatureExtractor'] a__ : str = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' import requests def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = {"""Content-Type""": """application/json"""} __UpperCamelCase = requests.post(__A ,json={"""text""": message_body} ,headers=__A ) if response.status_code != 200: __UpperCamelCase = ( """Request to slack returned an error """ f"{response.status_code}, the response is:\n{response.text}" ) raise ValueError(__A ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
349
'''simple docstring''' def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = len(__A ) __UpperCamelCase = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __UpperCamelCase = True # sum is not zero and set is empty then false for i in range(1 ,required_sum + 1 ): __UpperCamelCase = False for i in range(1 ,arr_len + 1 ): for j in range(1 ,required_sum + 1 ): if arr[i - 1] > j: __UpperCamelCase = subset[i - 1][j] if arr[i - 1] <= j: __UpperCamelCase = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' a__ : List[Any] = '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
349
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger a__ : Any = get_logger(__name__) class UpperCAmelCase__ : def __init__( self , lowercase = None ) -> List[str]: __UpperCamelCase = ( os.path.join(lowercase , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) __UpperCamelCase = Extractor def __lowerCamelCase ( self , lowercase ) -> str: from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" __UpperCamelCase = os.path.abspath(lowercase ) return os.path.join(self.extract_dir , hash_url_to_filename(lowercase ) ) def __lowerCamelCase ( self , lowercase , lowercase ) -> bool: return force_extract or ( not os.path.isfile(lowercase ) and not (os.path.isdir(lowercase ) and os.listdir(lowercase )) ) def __lowerCamelCase ( self , lowercase , lowercase = False ) -> str: __UpperCamelCase = self.extractor.infer_extractor_format(lowercase ) if not extractor_format: return input_path __UpperCamelCase = self._get_output_path(lowercase ) if self._do_extract(lowercase , lowercase ): self.extractor.extract(lowercase , lowercase , lowercase ) return output_path class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod @abstractmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: ... @staticmethod @abstractmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: ... class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> int: with open(lowercase , """rb""" ) as f: return f.read(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if not magic_number: __UpperCamelCase = max(len(lowercase ) for cls_magic_number in cls.magic_numbers ) try: __UpperCamelCase = cls.read_magic_number(lowercase , lowercase ) except OSError: return False return any(magic_number.startswith(lowercase ) for cls_magic_number in cls.magic_numbers ) class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: return tarfile.is_tarfile(lowercase ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: def resolved(lowercase ) -> str: return os.path.realpath(os.path.abspath(lowercase ) ) def badpath(lowercase , lowercase ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(lowercase , lowercase ) ).startswith(lowercase ) def badlink(lowercase , lowercase ) -> bool: # Links are interpreted relative to the directory containing the link __UpperCamelCase = resolved(os.path.join(lowercase , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=lowercase ) __UpperCamelCase = resolved(lowercase ) for finfo in members: if badpath(finfo.name , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked (illegal path)" ) elif finfo.issym() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}" ) elif finfo.islnk() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}" ) else: yield finfo @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = tarfile.open(lowercase ) tar_file.extractall(lowercase , members=TarExtractor.safemembers(lowercase , lowercase ) ) tar_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x1F\x8B'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with gzip.open(lowercase , """rb""" ) as gzip_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [ B'''PK\x03\x04''', B'''PK\x05\x06''', # empty archive B'''PK\x07\x08''', # spanned archive ] @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if super().is_extractable(lowercase , magic_number=lowercase ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(lowercase , """rb""" ) as fp: __UpperCamelCase = _EndRecData(lowercase ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: __UpperCamelCase = fp.read(lowercase ) # CD is where we expect it to be if len(lowercase ) == sizeCentralDir: __UpperCamelCase = struct.unpack(lowercase , lowercase ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) with zipfile.ZipFile(lowercase , """r""" ) as zip_file: zip_file.extractall(lowercase ) zip_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with lzma.open(lowercase ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = rarfile.RarFile(lowercase ) rf.extractall(lowercase ) rf.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x28\xb5\x2F\xFD'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd __UpperCamelCase = zstd.ZstdDecompressor() with open(lowercase , """rb""" ) as ifh, open(lowercase , """wb""" ) as ofh: dctx.copy_stream(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x42\x5A\x68'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with bza.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(lowercase , exist_ok=lowercase ) with pyazr.SevenZipFile(lowercase , """r""" ) as archive: archive.extractall(lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x04\x22\x4D\x18'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) __SCREAMING_SNAKE_CASE = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def __lowerCamelCase ( cls ) -> Union[str, Any]: return max( len(lowercase ) for extractor in cls.extractors.values() if issubclass(lowercase , lowercase ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: try: return MagicNumberBaseExtractor.read_magic_number(lowercase , magic_number_length=lowercase ) except OSError: return b"" @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = False ) -> bool: warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = cls.infer_extractor_format(lowercase ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def __lowerCamelCase ( cls , lowercase ) -> str: # <Added version="2.4.0"/> __UpperCamelCase = cls._get_magic_number_max_length() __UpperCamelCase = cls._read_magic_number(lowercase , lowercase ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(lowercase , magic_number=lowercase ): return extractor_format @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase = None , lowercase = "deprecated" , ) -> None: os.makedirs(os.path.dirname(lowercase ) , exist_ok=lowercase ) # Prevent parallel extractions __UpperCamelCase = str(Path(lowercase ).with_suffix(""".lock""" ) ) with FileLock(lowercase ): shutil.rmtree(lowercase , ignore_errors=lowercase ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(lowercase , lowercase ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = extractor if extractor != """deprecated""" else extractor_format else: __UpperCamelCase = cls.extractors[extractor_format] return extractor.extract(lowercase , lowercase ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=lowercase , ) for extractor in cls.extractors.values(): if extractor.is_extractable(lowercase ): return extractor.extract(lowercase , lowercase )
349
1
'''simple docstring''' class UpperCAmelCase__ : def __init__( self , lowercase , lowercase , lowercase ) -> Optional[Any]: __UpperCamelCase = name __UpperCamelCase = value __UpperCamelCase = weight def __repr__( self ) -> Any: return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def __lowerCamelCase ( self ) -> Any: return self.value def __lowerCamelCase ( self ) -> Optional[Any]: return self.name def __lowerCamelCase ( self ) -> Any: return self.weight def __lowerCamelCase ( self ) -> List[str]: return self.value / self.weight def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = [] for i in range(len(__A ) ): menu.append(Things(name[i] ,value[i] ,weight[i] ) ) return menu def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = sorted(__A ,key=__A ,reverse=__A ) __UpperCamelCase = [] __UpperCamelCase , __UpperCamelCase = 0.0, 0.0 for i in range(len(__A ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def _lowercase ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
349
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=5 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=2_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Optional[Any]: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> str: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __UpperCamelCase = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = np.concatenate([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , decoder_attention_mask=lowercase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Any: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase , decoder_attention_mask=lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = np.not_equal(__A ,config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __UpperCamelCase = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape ,dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ).astype(np.inta ), ] ,axis=-1 ,) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __SCREAMING_SNAKE_CASE = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = FlaxPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> List[Any]: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = self._prepare_for_class(lowercase , lowercase ) __UpperCamelCase = model_class(lowercase ) @jax.jit def encode_jitted(lowercase , lowercase=None , **lowercase ): return model.encode(input_ids=lowercase , attention_mask=lowercase ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) __UpperCamelCase = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(lowercase , lowercase , lowercase ): return model.decode( decoder_input_ids=lowercase , decoder_attention_mask=lowercase , encoder_outputs=lowercase , ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __lowerCamelCase ( self ) -> Dict: for model_class_name in self.all_model_classes: __UpperCamelCase = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=lowercase ) __UpperCamelCase = np.ones((1, 1) ) __UpperCamelCase = model(lowercase ) self.assertIsNotNone(lowercase ) @slow def __lowerCamelCase ( self ) -> str: __UpperCamelCase = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] __UpperCamelCase = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] __UpperCamelCase = tokenizer(lowercase , return_tensors="""np""" , truncation=lowercase , max_length=5_1_2 , padding=lowercase ) __UpperCamelCase = model.generate(**lowercase , num_beams=2 ).sequences __UpperCamelCase = tokenizer.batch_decode(lowercase , skip_special_tokens=lowercase ) assert tgt_text == decoded
349
1
'''simple docstring''' def _lowercase ( __A ): '''simple docstring''' if not isinstance(__A ,__A ): __UpperCamelCase = f"Input value of [number={number}] must be an integer" raise TypeError(__A ) if number < 0: return False __UpperCamelCase = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
349
'''simple docstring''' import pytest a__ : List[str] = '__dummy_dataset1__' a__ : Optional[int] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dataset_loading_script_name __UpperCamelCase = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=__A ) __UpperCamelCase = script_dir / f"{script_name}.py" with open(__A ,"""w""" ) as f: f.write(__A ) return str(__A )
349
1
'''simple docstring''' from __future__ import annotations import math def _lowercase ( __A ): '''simple docstring''' if num <= 0: __UpperCamelCase = f"{num}: Invalid input, please enter a positive integer." raise ValueError(__A ) __UpperCamelCase = [True] * (num + 1) __UpperCamelCase = [] __UpperCamelCase = 2 __UpperCamelCase = int(math.sqrt(__A ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__A ) # Set multiples of start be False for i in range(start * start ,num + 1 ,__A ): if sieve[i] is True: __UpperCamelCase = False start += 1 for j in range(end + 1 ,num + 1 ): if sieve[j] is True: prime.append(__A ) return prime if __name__ == "__main__": print(prime_sieve(int(input('Enter a positive integer: ').strip())))
349
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } a__ : List[str] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} with open(__A ,"""r""" ) as file: for line_number, line in enumerate(__A ): __UpperCamelCase = line.strip() if line: __UpperCamelCase = line.split() __UpperCamelCase = line_number __UpperCamelCase = words[0] __UpperCamelCase = value return result def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' for attribute in key.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = getattr(__A ,__A ).shape elif weight_type is not None and weight_type == "param": __UpperCamelCase = hf_pointer for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = shape_pointer.shape # let's reduce dimension __UpperCamelCase = value[0] 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 == "param": for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = value else: __UpperCamelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __UpperCamelCase = """.""".join([key, hf_param_name] ) else: __UpperCamelCase = key __UpperCamelCase = value if """lm_head""" in full_key else value[0] a__ : Dict = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _lowercase ( __A ,__A ,__A=None ,__A=None ): '''simple docstring''' __UpperCamelCase = False for key, mapped_key in MAPPING.items(): __UpperCamelCase = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __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: # TODO: don't match quantizer.weight_proj __UpperCamelCase = """weight""" else: __UpperCamelCase = None if hf_dict is not None: rename_dict(__A ,__A ,__A ,__A ,__A ) else: set_recursively(__A ,__A ,__A ,__A ,__A ) return is_used return is_used def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = [] __UpperCamelCase = fairseq_model.state_dict() __UpperCamelCase = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __A ,__A ,__A ,__A ,hf_model.config.feat_extract_norm == """group""" ,) __UpperCamelCase = True else: __UpperCamelCase = load_wavaveca_layer(__A ,__A ,__A ) if not is_used: unused_weights.append(__A ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''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 _lowercase ( __A ,__A ,__A=None ,__A=None ,__A=True ,__A=False ): '''simple docstring''' if config_path is not None: __UpperCamelCase = WavaVecaConfig.from_pretrained(__A ) else: __UpperCamelCase = WavaVecaConfig() if is_seq_class: __UpperCamelCase = read_txt_into_dict(__A ) __UpperCamelCase = idalabel __UpperCamelCase = WavaVecaForSequenceClassification(__A ) __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) feature_extractor.save_pretrained(__A ) elif is_finetuned: if dict_path: __UpperCamelCase = Dictionary.load(__A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase = target_dict.pad_index __UpperCamelCase = target_dict.bos_index __UpperCamelCase = target_dict.eos_index __UpperCamelCase = len(target_dict.symbols ) __UpperCamelCase = os.path.join(__A ,"""vocab.json""" ) if not os.path.isdir(__A ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__A ) ) return os.makedirs(__A ,exist_ok=__A ) __UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCamelCase = 0 __UpperCamelCase = 1 with open(__A ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(__A ,__A ) __UpperCamelCase = WavaVecaCTCTokenizer( __A ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=__A ,) __UpperCamelCase = True if config.feat_extract_norm == """layer""" else False __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) __UpperCamelCase = WavaVecaProcessor(feature_extractor=__A ,tokenizer=__A ) processor.save_pretrained(__A ) __UpperCamelCase = WavaVecaForCTC(__A ) else: __UpperCamelCase = WavaVecaForPreTraining(__A ) if is_finetuned or is_seq_class: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __UpperCamelCase = argparse.Namespace(task="""audio_pretraining""" ) __UpperCamelCase = fairseq.tasks.setup_task(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=__A ) __UpperCamelCase = model[0].eval() recursively_load_weights(__A ,__A ,not is_finetuned ) hf_wavavec.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) a__ : Optional[int] = parser.parse_args() a__ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
349
1
'''simple docstring''' import inspect import unittest from typing import List import numpy as np from transformers import EfficientFormerConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, ) from transformers.models.efficientformer.modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_vision_available(): from PIL import Image from transformers import EfficientFormerImageProcessor class UpperCAmelCase__ : def __init__( self , lowercase , lowercase = 1_3 , lowercase = 6_4 , lowercase = 2 , lowercase = 3 , lowercase = 3 , lowercase = True , lowercase = True , lowercase = 1_2_8 , lowercase=[1_6, 3_2, 6_4, 1_2_8] , lowercase = 7 , lowercase = 4 , lowercase = 3_7 , lowercase = "gelu" , lowercase = 0.1 , lowercase = 0.1 , lowercase = 1_0 , lowercase = 0.02 , lowercase = 2 , lowercase = 1 , lowercase = 1_2_8 , lowercase = [2, 2, 2, 2] , lowercase = 2 , lowercase = 2 , ) -> List[Any]: __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 = encoder_stride __UpperCamelCase = num_attention_outputs __UpperCamelCase = embed_dim __UpperCamelCase = embed_dim + 1 __UpperCamelCase = resolution __UpperCamelCase = depths __UpperCamelCase = hidden_sizes __UpperCamelCase = dim __UpperCamelCase = mlp_expansion_ratio def __lowerCamelCase ( self ) -> List[Any]: __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 __lowerCamelCase ( self ) -> Union[str, Any]: return EfficientFormerConfig( 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=lowercase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , resolution=self.resolution , depths=self.depths , hidden_sizes=self.hidden_sizes , dim=self.dim , mlp_expansion_ratio=self.mlp_expansion_ratio , ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> List[str]: __UpperCamelCase = TFEfficientFormerModel(config=lowercase ) __UpperCamelCase = model(lowercase , training=lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = self.type_sequence_label_size __UpperCamelCase = TFEfficientFormerForImageClassification(lowercase ) __UpperCamelCase = model(lowercase , labels=lowercase , training=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __UpperCamelCase = 1 __UpperCamelCase = TFEfficientFormerForImageClassification(lowercase ) __UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCamelCase = model(lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCamelCase ( self ) -> str: __UpperCamelCase = self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = config_and_inputs __UpperCamelCase = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( TFEfficientFormerModel, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerForImageClassification, ) if is_tf_available() else () ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFEfficientFormerModel, '''image-classification''': ( TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, ), } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = TFEfficientFormerModelTester(self ) __UpperCamelCase = ConfigTester( self , config_class=lowercase , has_text_modality=lowercase , hidden_size=3_7 ) def __lowerCamelCase ( self ) -> Optional[Any]: self.config_tester.run_common_tests() @unittest.skip(reason="""EfficientFormer does not use inputs_embeds""" ) def __lowerCamelCase ( self ) -> Optional[Any]: pass @unittest.skip(reason="""EfficientFormer does not support input and output embeddings""" ) def __lowerCamelCase ( self ) -> Dict: pass def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase = [*signature.parameters.keys()] __UpperCamelCase = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: def check_hidden_states_output(lowercase , lowercase , lowercase ): __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model(**self._prepare_for_class(lowercase , lowercase ) , training=lowercase ) __UpperCamelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __UpperCamelCase = getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(lowercase ) , lowercase ) if hasattr(self.model_tester , """encoder_seq_length""" ): __UpperCamelCase = self.model_tester.encoder_seq_length if hasattr(self.model_tester , """chunk_length""" ) and self.model_tester.chunk_length > 1: __UpperCamelCase = seq_length * self.model_tester.chunk_length else: __UpperCamelCase = self.model_tester.seq_length self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) if config.is_encoder_decoder: __UpperCamelCase = outputs.decoder_hidden_states self.asseretIsInstance(lowercase , (list, tuple) ) self.assertEqual(len(lowercase ) , lowercase ) __UpperCamelCase = getattr(self.model_tester , """seq_length""" , lowercase ) __UpperCamelCase = getattr(self.model_tester , """decoder_seq_length""" , lowercase ) self.assertListEqual( list(hidden_states[-1].shape[-2:] ) , [decoder_seq_length, self.model_tester.hidden_size] , ) __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(lowercase , lowercase , lowercase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCamelCase = True check_hidden_states_output(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase=False ) -> List[Any]: __UpperCamelCase = super()._prepare_for_class(lowercase , lowercase , return_labels=lowercase ) if return_labels: if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase ) @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet""" ) def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase ) @slow def __lowerCamelCase ( self ) -> List[str]: for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFEfficientFormerModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase = True __UpperCamelCase = getattr(self.model_tester , """seq_length""" , lowercase ) __UpperCamelCase = getattr(self.model_tester , """encoder_seq_length""" , lowercase ) __UpperCamelCase = getattr(self.model_tester , """key_length""" , lowercase ) __UpperCamelCase = getattr(self.model_tester , """chunk_length""" , lowercase ) if chunk_length is not None and hasattr(self.model_tester , """num_hashes""" ): __UpperCamelCase = encoder_seq_length * self.model_tester.num_hashes for model_class in self.all_model_classes: __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model(**self._prepare_for_class(lowercase , lowercase ) , training=lowercase ) __UpperCamelCase = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(lowercase ) , self.model_tester.num_attention_outputs ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __UpperCamelCase = True __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model(**self._prepare_for_class(lowercase , lowercase ) , training=lowercase ) __UpperCamelCase = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(lowercase ) , self.model_tester.num_attention_outputs ) if chunk_length is not None: self.assertListEqual( list(attentions[0].shape[-4:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length] , ) else: self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length] , ) def __lowerCamelCase ( self ) -> str: # We use a simplified version of this test for EfficientFormer because it requires training=False # and Keras refuses to let us force that during functional construction __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # Prepare our model __UpperCamelCase = model_class(lowercase ) # These are maximally general inputs for the model, with multiple None dimensions # Hopefully this will catch any conditionals that fail for flexible shapes __UpperCamelCase = { key: tf.keras.Input(shape=val.shape[1:] , dtype=val.dtype , name=lowercase ) for key, val in model.input_signature.items() if key in model.dummy_inputs } __UpperCamelCase = model(lowercase ) self.assertTrue(outputs_dict is not None ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCAmelCase__ ( unittest.TestCase): @cached_property def __lowerCamelCase ( self ) -> List[str]: return ( EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300""" ) if is_vision_available() else None ) @slow def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300""" ) __UpperCamelCase = self.default_image_processor __UpperCamelCase = prepare_img() __UpperCamelCase = image_processor(images=lowercase , return_tensors="""tf""" ) # forward pass __UpperCamelCase = model(**lowercase , training=lowercase ) # verify the logits __UpperCamelCase = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , lowercase ) __UpperCamelCase = tf.constant([-0.0_555, 0.4_825, -0.0_852] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , lowercase , atol=1E-4 ) ) @slow def __lowerCamelCase ( self ) -> int: __UpperCamelCase = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained( """snap-research/efficientformer-l1-300""" ) __UpperCamelCase = self.default_image_processor __UpperCamelCase = prepare_img() __UpperCamelCase = image_processor(images=lowercase , return_tensors="""tf""" ) # forward pass __UpperCamelCase = model(**lowercase , training=lowercase ) # verify the logits __UpperCamelCase = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , lowercase ) __UpperCamelCase = tf.constant([-0.1_312, 0.4_353, -1.0_499] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , lowercase , atol=1E-4 ) )
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCAmelCase__ : def __init__( self , lowercase , ) -> Union[str, Any]: __UpperCamelCase = parent __UpperCamelCase = 1_3 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = 9_9 __UpperCamelCase = 3_2 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 3_7 __UpperCamelCase = """gelu""" __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 5_1_2 __UpperCamelCase = 1_6 __UpperCamelCase = 2 __UpperCamelCase = 0.02 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = None def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = None if self.use_input_mask: __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = TFDistilBertModel(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]: __UpperCamelCase = TFDistilBertForMaskedLM(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = TFDistilBertForQuestionAnswering(config=lowercase ) __UpperCamelCase = { """input_ids""": input_ids, """attention_mask""": input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForSequenceClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: __UpperCamelCase = self.num_choices __UpperCamelCase = TFDistilBertForMultipleChoice(lowercase ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForTokenClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.prepare_config_and_inputs() ((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFDistilBertModel, '''fill-mask''': TFDistilBertForMaskedLM, '''question-answering''': TFDistilBertForQuestionAnswering, '''text-classification''': TFDistilBertForSequenceClassification, '''token-classification''': TFDistilBertForTokenClassification, '''zero-shot''': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = TFDistilBertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , dim=3_7 ) def __lowerCamelCase ( self ) -> Any: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) @slow def __lowerCamelCase ( self ) -> Tuple: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): __UpperCamelCase = TFDistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_tf class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase = model(lowercase )[0] __UpperCamelCase = [1, 6, 7_6_8] self.assertEqual(output.shape , lowercase ) __UpperCamelCase = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-4 )
349
1
'''simple docstring''' def _lowercase ( __A = 2_000_000 ): '''simple docstring''' __UpperCamelCase = [0 for i in range(n + 1 )] __UpperCamelCase = 1 __UpperCamelCase = 1 for i in range(2 ,int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i ,n + 1 ,__A ): __UpperCamelCase = 1 __UpperCamelCase = 0 for i in range(__A ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f'''{solution() = }''')
349
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _lowercase ( __A ,__A ): '''simple docstring''' return math.sqrt(sum(pow(a - b ,2 ) for a, b in zip(__A ,__A ) ) ) def _lowercase ( __A ,__A ): '''simple docstring''' if dataset.ndim != value_array.ndim: __UpperCamelCase = ( """Wrong input data's dimensions... """ f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(__A ) try: if dataset.shape[1] != value_array.shape[1]: __UpperCamelCase = ( """Wrong input data's shape... """ f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(__A ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: __UpperCamelCase = ( """Input data have different datatype... """ f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(__A ) __UpperCamelCase = [] for value in value_array: __UpperCamelCase = euclidean(__A ,dataset[0] ) __UpperCamelCase = dataset[0].tolist() for dataset_value in dataset[1:]: __UpperCamelCase = euclidean(__A ,__A ) if dist > temp_dist: __UpperCamelCase = temp_dist __UpperCamelCase = dataset_value.tolist() answer.append([vector, dist] ) return answer def _lowercase ( __A ,__A ): '''simple docstring''' return np.dot(__A ,__A ) / (norm(__A ) * norm(__A )) if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig a__ : List[Any] = logging.get_logger(__name__) a__ : Optional[Any] = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''dpt''' def __init__( self , lowercase=7_6_8 , lowercase=1_2 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=1E-12 , lowercase=3_8_4 , lowercase=1_6 , lowercase=3 , lowercase=False , lowercase=True , lowercase=[2, 5, 8, 1_1] , lowercase="project" , lowercase=[4, 2, 1, 0.5] , lowercase=[9_6, 1_9_2, 3_8_4, 7_6_8] , lowercase=2_5_6 , lowercase=-1 , lowercase=False , lowercase=True , lowercase=0.4 , lowercase=2_5_5 , lowercase=0.1 , lowercase=[1, 1_0_2_4, 2_4, 2_4] , lowercase=[0, 1] , lowercase=None , **lowercase , ) -> Any: super().__init__(**lowercase ) __UpperCamelCase = hidden_size __UpperCamelCase = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("""Initializing the config with a `BiT` backbone.""" ) __UpperCamelCase = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, } __UpperCamelCase = BitConfig(**lowercase ) elif isinstance(lowercase , lowercase ): logger.info("""Initializing the config with a `BiT` backbone.""" ) __UpperCamelCase = BitConfig(**lowercase ) elif isinstance(lowercase , lowercase ): __UpperCamelCase = backbone_config else: raise ValueError( f"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}." ) __UpperCamelCase = backbone_featmap_shape __UpperCamelCase = neck_ignore_stages if readout_type != "project": raise ValueError("""Readout type must be 'project' when using `DPT-hybrid` mode.""" ) else: __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = [] __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_act __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = initializer_range __UpperCamelCase = layer_norm_eps __UpperCamelCase = image_size __UpperCamelCase = patch_size __UpperCamelCase = num_channels __UpperCamelCase = qkv_bias __UpperCamelCase = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("""Readout_type must be one of ['ignore', 'add', 'project']""" ) __UpperCamelCase = readout_type __UpperCamelCase = reassemble_factors __UpperCamelCase = neck_hidden_sizes __UpperCamelCase = fusion_hidden_size __UpperCamelCase = head_in_index __UpperCamelCase = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) __UpperCamelCase = use_auxiliary_head __UpperCamelCase = auxiliary_loss_weight __UpperCamelCase = semantic_loss_ignore_index __UpperCamelCase = semantic_classifier_dropout def __lowerCamelCase ( self ) -> str: __UpperCamelCase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: __UpperCamelCase = self.backbone_config.to_dict() __UpperCamelCase = self.__class__.model_type return output
349
'''simple docstring''' from datetime import datetime import requests def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = """https://downloadgram.net/wp-json/wppress/video-downloader/video?url=""" __UpperCamelCase = requests.get(base_url + url ).json()[0]["""urls"""][0]["""src"""] return requests.get(__A ).content if __name__ == "__main__": a__ : int = input('Enter Video/IGTV url: ').strip() a__ : int = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4''' with open(file_name, 'wb') as fp: fp.write(download_video(url)) print(f'''Done. Video saved to disk as {file_name}.''')
349
1
'''simple docstring''' 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 _lowercase ( __A ): '''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 _lowercase ( __A ): '''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
349
'''simple docstring''' import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowercase ( __A ,__A=False ): '''simple docstring''' try: __UpperCamelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __UpperCamelCase = default else: # KEY is set, convert it to True or False. try: __UpperCamelCase = strtobool(__A ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no." ) return _value a__ : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) a__ : Union[str, Any] = parse_flag_from_env('RUN_REMOTE', default=False) a__ : Any = parse_flag_from_env('RUN_LOCAL', default=True) a__ : List[Any] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a__ : Optional[int] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a__ : Optional[int] = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a__ : Optional[Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a__ : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a__ : str = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a__ : str = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a__ : Tuple = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowercase ( __A ): '''simple docstring''' try: import faiss # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires faiss""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import regex # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires regex""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import elasticsearch # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires elasticsearch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import sqlalchemy # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires sqlalchemy""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TORCH_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires PyTorch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TF_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires TensorFlow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.JAX_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires JAX""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.PIL_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires Pillow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import transformers # noqa F401 except ImportError: return unittest.skip("""test requires transformers""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import tiktoken # noqa F401 except ImportError: return unittest.skip("""test requires tiktoken""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import spacy # noqa F401 except ImportError: return unittest.skip("""test requires spacy""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' def _require_spacy_model(__A ): try: import spacy # noqa F401 spacy.load(__A ) except ImportError: return unittest.skip("""test requires spacy""" )(__A ) except OSError: return unittest.skip("""test requires spacy model '{}'""".format(__A ) )(__A ) else: return test_case return _require_spacy_model def _lowercase ( __A ): '''simple docstring''' try: import pyspark # noqa F401 except ImportError: return unittest.skip("""test requires pyspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import joblibspark # noqa F401 except ImportError: return unittest.skip("""test requires joblibspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_slow_tests or _run_slow_tests == 0: __UpperCamelCase = unittest.skip("""test is slow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_local_tests or _run_local_tests == 0: __UpperCamelCase = unittest.skip("""test is local""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_packaged_tests or _run_packaged_tests == 0: __UpperCamelCase = unittest.skip("""test is packaged""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_remote_tests or _run_remote_tests == 0: __UpperCamelCase = unittest.skip("""test requires remote""" )(__A ) return test_case def _lowercase ( *__A ): '''simple docstring''' def decorate(cls ): for name, fn in cls.__dict__.items(): if callable(__A ) and name.startswith("""test""" ): for decorator in decorators: __UpperCamelCase = decorator(__A ) setattr(cls ,__A ,__A ) return cls return decorate class UpperCAmelCase__ ( UpperCAmelCase_): pass class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 @contextmanager def _lowercase ( __A=OfflineSimulationMode.CONNECTION_FAILS ,__A=1E-16 ): '''simple docstring''' __UpperCamelCase = requests.Session().request def timeout_request(__A ,__A ,__A ,**__A ): # Change the url to an invalid url so that the connection hangs __UpperCamelCase = """https://10.255.255.1""" if kwargs.get("""timeout""" ) is None: raise RequestWouldHangIndefinitelyError( f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) __UpperCamelCase = timeout try: return online_request(__A ,__A ,**__A ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __UpperCamelCase = url __UpperCamelCase = e.args[0] __UpperCamelCase = (max_retry_error.args[0].replace("""10.255.255.1""" ,f"OfflineMock[{url}]" ),) __UpperCamelCase = (max_retry_error,) raise def raise_connection_error(__A ,__A ,**__A ): raise requests.ConnectionError("""Offline mode is enabled.""" ,request=__A ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("""requests.Session.send""" ,__A ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("""requests.Session.request""" ,__A ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,__A ): yield else: raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" ) @contextmanager def _lowercase ( *__A ,**__A ): '''simple docstring''' __UpperCamelCase = str(Path().resolve() ) with tempfile.TemporaryDirectory(*__A ,**__A ) as tmp_dir: try: os.chdir(__A ) yield finally: os.chdir(__A ) @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowercase ( __A ,__A ): '''simple docstring''' return deepcopy(__A ).integers(0 ,100 ,10 ).tolist() == deepcopy(__A ).integers(0 ,100 ,10 ).tolist() def _lowercase ( __A ): '''simple docstring''' import decorator from requests.exceptions import HTTPError def _wrapper(__A ,*__A ,**__A ): try: return func(*__A ,**__A ) except HTTPError as err: if str(__A ).startswith("""500""" ) or str(__A ).startswith("""502""" ): pytest.xfail(str(__A ) ) raise err return decorator.decorator(_wrapper ,__A ) class UpperCAmelCase__ : def __init__( self , lowercase , lowercase , lowercase ) -> str: __UpperCamelCase = returncode __UpperCamelCase = stdout __UpperCamelCase = stderr async def _lowercase ( __A ,__A ): '''simple docstring''' while True: __UpperCamelCase = await stream.readline() if line: callback(__A ) else: break async def _lowercase ( __A ,__A=None ,__A=None ,__A=None ,__A=False ,__A=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(__A ) ) __UpperCamelCase = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=__A ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=__A ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __UpperCamelCase = [] __UpperCamelCase = [] def tee(__A ,__A ,__A ,__A="" ): __UpperCamelCase = line.decode("""utf-8""" ).rstrip() sink.append(__A ) if not quiet: print(__A ,__A ,file=__A ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __A : tee(__A ,__A ,sys.stdout ,label="""stdout:""" ) ), _read_stream(p.stderr ,lambda __A : tee(__A ,__A ,sys.stderr ,label="""stderr:""" ) ), ] ,timeout=__A ,) return _RunOutput(await p.wait() ,__A ,__A ) def _lowercase ( __A ,__A=None ,__A=None ,__A=180 ,__A=False ,__A=True ): '''simple docstring''' __UpperCamelCase = asyncio.get_event_loop() __UpperCamelCase = loop.run_until_complete( _stream_subprocess(__A ,env=__A ,stdin=__A ,timeout=__A ,quiet=__A ,echo=__A ) ) __UpperCamelCase = """ """.join(__A ) if result.returncode > 0: __UpperCamelCase = """\n""".join(result.stderr ) raise RuntimeError( f"'{cmd_str}' failed with returncode {result.returncode}\n\n" f"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f"'{cmd_str}' produced no output." ) return result def _lowercase ( ): '''simple docstring''' __UpperCamelCase = os.environ.get("""PYTEST_XDIST_WORKER""" ,"""gw0""" ) __UpperCamelCase = re.sub(R"""^gw""" ,"""""" ,__A ,0 ,re.M ) return int(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = 29_500 __UpperCamelCase = pytest_xdist_worker_id() return port + uniq_delta
349
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : Dict = logging.get_logger(__name__) a__ : List[Any] = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''roformer''' def __init__( self , lowercase=5_0_0_0_0 , lowercase=None , lowercase=7_6_8 , lowercase=1_2 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=1_5_3_6 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=0 , lowercase=False , lowercase=True , **lowercase , ) -> Optional[Any]: super().__init__(pad_token_id=lowercase , **lowercase ) __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size if embedding_size is None else embedding_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 = rotary_value __UpperCamelCase = use_cache class UpperCAmelCase__ ( UpperCAmelCase_): @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} __UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
349
'''simple docstring''' import re def _lowercase ( __A ): '''simple docstring''' return [char.split() for char in re.split(R"""[^ a-z A-Z 0-9 \s]""" ,str_ )] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = split_input(str_ ) return "".join( ["""""".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' try: __UpperCamelCase = split_input(__A ) if upper: __UpperCamelCase = """""".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __UpperCamelCase = """""".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _lowercase ( __A ): '''simple docstring''' return to_simple_case(__A ) def _lowercase ( __A ): '''simple docstring''' try: __UpperCamelCase = to_simple_case(__A ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""_""" ) def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""-""" ) if __name__ == "__main__": __import__('doctest').testmod()
349
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) a__ : str = { 'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Speech2TextConfig'], 'processing_speech_to_text': ['Speech2TextProcessor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = ['Speech2TextTokenizer'] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = ['Speech2TextFeatureExtractor'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSpeech2TextForConditionalGeneration', 'TFSpeech2TextModel', 'TFSpeech2TextPreTrainedModel', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ 'SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Speech2TextForConditionalGeneration', 'Speech2TextModel', 'Speech2TextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys a__ : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCamelCase ( self ) -> int: __UpperCamelCase = 1 __UpperCamelCase = 3 __UpperCamelCase = (3_2, 3_2) __UpperCamelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowercase ) return image @property def __lowerCamelCase ( self ) -> Dict: torch.manual_seed(0 ) __UpperCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) return model @property def __lowerCamelCase ( self ) -> List[str]: torch.manual_seed(0 ) __UpperCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def __lowerCamelCase ( self ) -> Optional[int]: torch.manual_seed(0 ) __UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(lowercase ) @property def __lowerCamelCase ( self ) -> Tuple: def extract(*lowercase , **lowercase ): class UpperCAmelCase__ : def __init__( self ) -> Tuple: __UpperCamelCase = torch.ones([0] ) def __lowerCamelCase ( self , lowercase ) -> List[str]: self.pixel_values.to(lowercase ) return self return Out() return extract def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=lowercase ) assert isinstance(lowercase , lowercase ) assert isinstance(pipe.scheduler , lowercase ) assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowercase ) __UpperCamelCase = StableDiffusionPipeline.from_pretrained(lowercase ) # sanity check that the pipeline still works assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 __UpperCamelCase = unet.half() __UpperCamelCase = vae.half() __UpperCamelCase = bert.half() # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 6_4, 6_4, 3) @nightly @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) __UpperCamelCase = 4_0_0_3_6_6_0_3_4_6 __UpperCamelCase = 7 # without safety guidance (sld_guidance_scale = 0) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """padme amidala taking a bath artwork, safe for work, no nudity""" __UpperCamelCase = 2_7_3_4_9_7_1_7_5_5 __UpperCamelCase = 7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) __UpperCamelCase = 1_0_4_4_3_5_5_2_3_4 __UpperCamelCase = 1_2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
349
1
'''simple docstring''' from math import pi, sqrt def _lowercase ( __A ): '''simple docstring''' if num <= 0: raise ValueError("""math domain error""" ) if num > 171.5: raise OverflowError("""math range error""" ) elif num - int(__A ) not in (0, 0.5): raise NotImplementedError("""num must be an integer or a half-integer""" ) elif num == 0.5: return sqrt(__A ) else: return 1.0 if num == 1 else (num - 1) * gamma(num - 1 ) def _lowercase ( ): '''simple docstring''' assert gamma(0.5 ) == sqrt(__A ) assert gamma(1 ) == 1.0 assert gamma(2 ) == 1.0 if __name__ == "__main__": from doctest import testmod testmod() a__ : Tuple = 1.0 while num: a__ : Any = float(input('Gamma of: ')) print(f'''gamma({num}) = {gamma(num)}''') print('\nEnter 0 to exit...')
349
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> str: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Any: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] )
349
1
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } a__ : List[str] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} with open(__A ,"""r""" ) as file: for line_number, line in enumerate(__A ): __UpperCamelCase = line.strip() if line: __UpperCamelCase = line.split() __UpperCamelCase = line_number __UpperCamelCase = words[0] __UpperCamelCase = value return result def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' for attribute in key.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = getattr(__A ,__A ).shape elif weight_type is not None and weight_type == "param": __UpperCamelCase = hf_pointer for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = shape_pointer.shape # let's reduce dimension __UpperCamelCase = value[0] 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 == "param": for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = value else: __UpperCamelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __UpperCamelCase = """.""".join([key, hf_param_name] ) else: __UpperCamelCase = key __UpperCamelCase = value if """lm_head""" in full_key else value[0] a__ : Dict = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _lowercase ( __A ,__A ,__A=None ,__A=None ): '''simple docstring''' __UpperCamelCase = False for key, mapped_key in MAPPING.items(): __UpperCamelCase = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __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: # TODO: don't match quantizer.weight_proj __UpperCamelCase = """weight""" else: __UpperCamelCase = None if hf_dict is not None: rename_dict(__A ,__A ,__A ,__A ,__A ) else: set_recursively(__A ,__A ,__A ,__A ,__A ) return is_used return is_used def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = [] __UpperCamelCase = fairseq_model.state_dict() __UpperCamelCase = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __A ,__A ,__A ,__A ,hf_model.config.feat_extract_norm == """group""" ,) __UpperCamelCase = True else: __UpperCamelCase = load_wavaveca_layer(__A ,__A ,__A ) if not is_used: unused_weights.append(__A ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''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 _lowercase ( __A ,__A ,__A=None ,__A=None ,__A=True ,__A=False ): '''simple docstring''' if config_path is not None: __UpperCamelCase = WavaVecaConfig.from_pretrained(__A ) else: __UpperCamelCase = WavaVecaConfig() if is_seq_class: __UpperCamelCase = read_txt_into_dict(__A ) __UpperCamelCase = idalabel __UpperCamelCase = WavaVecaForSequenceClassification(__A ) __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) feature_extractor.save_pretrained(__A ) elif is_finetuned: if dict_path: __UpperCamelCase = Dictionary.load(__A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase = target_dict.pad_index __UpperCamelCase = target_dict.bos_index __UpperCamelCase = target_dict.eos_index __UpperCamelCase = len(target_dict.symbols ) __UpperCamelCase = os.path.join(__A ,"""vocab.json""" ) if not os.path.isdir(__A ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__A ) ) return os.makedirs(__A ,exist_ok=__A ) __UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCamelCase = 0 __UpperCamelCase = 1 with open(__A ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(__A ,__A ) __UpperCamelCase = WavaVecaCTCTokenizer( __A ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=__A ,) __UpperCamelCase = True if config.feat_extract_norm == """layer""" else False __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) __UpperCamelCase = WavaVecaProcessor(feature_extractor=__A ,tokenizer=__A ) processor.save_pretrained(__A ) __UpperCamelCase = WavaVecaForCTC(__A ) else: __UpperCamelCase = WavaVecaForPreTraining(__A ) if is_finetuned or is_seq_class: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __UpperCamelCase = argparse.Namespace(task="""audio_pretraining""" ) __UpperCamelCase = fairseq.tasks.setup_task(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=__A ) __UpperCamelCase = model[0].eval() recursively_load_weights(__A ,__A ,not is_finetuned ) hf_wavavec.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) a__ : Optional[int] = parser.parse_args() a__ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
349
'''simple docstring''' import logging import os from .state import PartialState class UpperCAmelCase__ ( logging.LoggerAdapter): @staticmethod def __lowerCamelCase ( lowercase ) -> Dict: __UpperCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __lowerCamelCase ( self , lowercase , lowercase , *lowercase , **lowercase ) -> List[str]: if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) __UpperCamelCase = kwargs.pop("""main_process_only""" , lowercase ) __UpperCamelCase = kwargs.pop("""in_order""" , lowercase ) if self.isEnabledFor(lowercase ): if self._should_log(lowercase ): __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) elif in_order: __UpperCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) state.wait_for_everyone() def _lowercase ( __A ,__A = None ): '''simple docstring''' if log_level is None: __UpperCamelCase = os.environ.get("""ACCELERATE_LOG_LEVEL""" ,__A ) __UpperCamelCase = logging.getLogger(__A ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__A ,{} )
349
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a__ : int = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['LayoutLMv3FeatureExtractor'] a__ : str = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase__ : def __init__( self ) -> Any: __UpperCamelCase = False def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase ) -> str: if not self.initialized: __UpperCamelCase = RagRetriever( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = True def __lowerCamelCase ( self ) -> Optional[Any]: self.retriever.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.retriever._main_retrieve(lowercase , lowercase ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase=None ) -> List[Any]: if index is not None and index.is_initialized() and len(lowercase ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowercase , lowercase , lowercase , lowercase ) for worker in self.retrieval_workers ] ) def __lowerCamelCase ( self ) -> Dict: logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> List[str]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCamelCase = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCamelCase , __UpperCamelCase = ray.get(random_worker.retrieve.remote(lowercase , lowercase ) ) else: __UpperCamelCase , __UpperCamelCase = self._main_retrieve(lowercase , lowercase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase=None , **lowercase ) -> Any: return super(lowercase , cls ).get_tokenizers(lowercase , lowercase , **lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase=None , **lowercase ) -> int: __UpperCamelCase = kwargs.pop("""config""" , lowercase ) or RagConfig.from_pretrained(lowercase , **lowercase ) __UpperCamelCase = RagTokenizer.from_pretrained(lowercase , config=lowercase ) __UpperCamelCase = rag_tokenizer.question_encoder __UpperCamelCase = rag_tokenizer.generator if indexed_dataset is not None: __UpperCamelCase = """custom""" __UpperCamelCase = CustomHFIndex(config.retrieval_vector_size , lowercase ) else: __UpperCamelCase = cls._build_index(lowercase ) return cls( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , retrieval_workers=lowercase , index=lowercase , )
349
1
'''simple docstring''' def _lowercase ( __A ,__A ,__A ,__A ,__A ,): '''simple docstring''' __UpperCamelCase = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("""All input parameters must be positive""" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("""Relative densities cannot be greater than one""" ) else: __UpperCamelCase = 1 - (matter_density + radiation_density + dark_energy) __UpperCamelCase = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __UpperCamelCase = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a__ : List[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
349
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_squeezebert import SqueezeBertTokenizer a__ : Optional[Any] = logging.get_logger(__name__) a__ : Union[str, Any] = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__ : Any = { 'vocab_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt' ), 'squeezebert/squeezebert-mnli': 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt', 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'squeezebert/squeezebert-uncased': ( 'https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli': ( 'https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json' ), 'squeezebert/squeezebert-mnli-headless': ( 'https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json' ), }, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': 5_1_2, 'squeezebert/squeezebert-mnli': 5_1_2, 'squeezebert/squeezebert-mnli-headless': 5_1_2, } a__ : Optional[Any] = { 'squeezebert/squeezebert-uncased': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli': {'do_lower_case': True}, 'squeezebert/squeezebert-mnli-headless': {'do_lower_case': True}, } class UpperCAmelCase__ ( UpperCAmelCase_): __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 = SqueezeBertTokenizer def __init__( self , lowercase=None , lowercase=None , lowercase=True , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , lowercase=True , lowercase=None , **lowercase , ) -> Tuple: super().__init__( lowercase , tokenizer_file=lowercase , do_lower_case=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , tokenize_chinese_chars=lowercase , strip_accents=lowercase , **lowercase , ) __UpperCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , lowercase ) != tokenize_chinese_chars ): __UpperCamelCase = getattr(lowercase , normalizer_state.pop("""type""" ) ) __UpperCamelCase = do_lower_case __UpperCamelCase = strip_accents __UpperCamelCase = tokenize_chinese_chars __UpperCamelCase = normalizer_class(**lowercase ) __UpperCamelCase = do_lower_case def __lowerCamelCase ( self , lowercase , lowercase=None ) -> Tuple: __UpperCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __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 __lowerCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: __UpperCamelCase = self._tokenizer.model.save(lowercase , name=lowercase ) return tuple(lowercase )
349
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a__ : Optional[int] = { 'configuration_squeezebert': [ 'SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SqueezeBertConfig', 'SqueezeBertOnnxConfig', ], 'tokenization_squeezebert': ['SqueezeBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = ['SqueezeBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ 'SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'SqueezeBertForMaskedLM', 'SqueezeBertForMultipleChoice', 'SqueezeBertForQuestionAnswering', 'SqueezeBertForSequenceClassification', 'SqueezeBertForTokenClassification', 'SqueezeBertModel', 'SqueezeBertModule', 'SqueezeBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys a__ : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a__ : str = { 'configuration_trocr': ['TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TrOCRConfig'], 'processing_trocr': ['TrOCRProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ 'TROCR_PRETRAINED_MODEL_ARCHIVE_LIST', 'TrOCRForCausalLM', 'TrOCRPreTrainedModel', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _lowercase ( __A ,__A ,__A=1E-12 ): '''simple docstring''' __UpperCamelCase = jnp.divide(emb_a.T ,jnp.clip(jnp.linalg.norm(__A ,axis=1 ) ,a_min=__A ) ).T __UpperCamelCase = jnp.divide(emb_a.T ,jnp.clip(jnp.linalg.norm(__A ,axis=1 ) ,a_min=__A ) ).T return jnp.matmul(__A ,norm_emb_a.T ) class UpperCAmelCase__ ( nn.Module): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = jnp.floataa def __lowerCamelCase ( self ) -> int: __UpperCamelCase = FlaxCLIPVisionModule(self.config.vision_config ) __UpperCamelCase = nn.Dense(self.config.projection_dim , use_bias=lowercase , dtype=self.dtype ) __UpperCamelCase = self.param("""concept_embeds""" , jax.nn.initializers.ones , (1_7, self.config.projection_dim) ) __UpperCamelCase = self.param( """special_care_embeds""" , jax.nn.initializers.ones , (3, self.config.projection_dim) ) __UpperCamelCase = self.param("""concept_embeds_weights""" , jax.nn.initializers.ones , (1_7,) ) __UpperCamelCase = self.param("""special_care_embeds_weights""" , jax.nn.initializers.ones , (3,) ) def __call__( self , lowercase ) -> List[str]: __UpperCamelCase = self.vision_model(lowercase )[1] __UpperCamelCase = self.visual_projection(lowercase ) __UpperCamelCase = jax_cosine_distance(lowercase , self.special_care_embeds ) __UpperCamelCase = jax_cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs __UpperCamelCase = 0.0 __UpperCamelCase = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment __UpperCamelCase = jnp.round(lowercase , 3 ) __UpperCamelCase = jnp.any(special_scores > 0 , axis=1 , keepdims=lowercase ) # Use a lower threshold if an image has any special care concept __UpperCamelCase = is_special_care * 0.01 __UpperCamelCase = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment __UpperCamelCase = jnp.round(lowercase , 3 ) __UpperCamelCase = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = CLIPConfig __SCREAMING_SNAKE_CASE = '''clip_input''' __SCREAMING_SNAKE_CASE = FlaxStableDiffusionSafetyCheckerModule def __init__( self , lowercase , lowercase = None , lowercase = 0 , lowercase = jnp.floataa , lowercase = True , **lowercase , ) -> int: if input_shape is None: __UpperCamelCase = (1, 2_2_4, 2_2_4, 3) __UpperCamelCase = self.module_class(config=lowercase , dtype=lowercase , **lowercase ) super().__init__(lowercase , lowercase , input_shape=lowercase , seed=lowercase , dtype=lowercase , _do_init=_do_init ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase = None ) -> FrozenDict: # init input tensor __UpperCamelCase = jax.random.normal(lowercase , lowercase ) __UpperCamelCase , __UpperCamelCase = jax.random.split(lowercase ) __UpperCamelCase = {"""params""": params_rng, """dropout""": dropout_rng} __UpperCamelCase = self.module.init(lowercase , lowercase )["""params"""] return random_params def __call__( self , lowercase , lowercase = None , ) -> Optional[int]: __UpperCamelCase = jnp.transpose(lowercase , (0, 2, 3, 1) ) return self.module.apply( {"""params""": params or self.params} , jnp.array(lowercase , dtype=jnp.floataa ) , rngs={} , )
349
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig a__ : Union[str, Any] = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''albert''' def __init__( self , lowercase=3_0_0_0_0 , lowercase=1_2_8 , lowercase=4_0_9_6 , lowercase=1_2 , lowercase=1 , lowercase=6_4 , lowercase=1_6_3_8_4 , lowercase=1 , lowercase="gelu_new" , lowercase=0 , lowercase=0 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=0.1 , lowercase="absolute" , lowercase=0 , lowercase=2 , lowercase=3 , **lowercase , ) -> Any: super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) __UpperCamelCase = vocab_size __UpperCamelCase = embedding_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_hidden_groups __UpperCamelCase = num_attention_heads __UpperCamelCase = inner_group_num __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 = classifier_dropout_prob __UpperCamelCase = position_embedding_type class UpperCAmelCase__ ( UpperCAmelCase_): @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __UpperCamelCase = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
349
1
'''simple docstring''' import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors a__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''sequence-classification''' def __init__( self , lowercase ) -> Optional[Any]: if type(lowercase ) == dict: __UpperCamelCase = Namespace(**lowercase ) __UpperCamelCase = glue_output_modes[hparams.task] __UpperCamelCase = glue_tasks_num_labels[hparams.task] super().__init__(lowercase , lowercase , self.mode ) def __lowerCamelCase ( self , **lowercase ) -> Optional[Any]: return self.model(**lowercase ) def __lowerCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: __UpperCamelCase = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCamelCase = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCamelCase = self(**lowercase ) __UpperCamelCase = outputs[0] __UpperCamelCase = self.trainer.lr_schedulers[0]["""scheduler"""] __UpperCamelCase = {"""loss""": loss, """rate""": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = self.hparams __UpperCamelCase = processors[args.task]() __UpperCamelCase = processor.get_labels() for mode in ["train", "dev"]: __UpperCamelCase = self._feature_file(lowercase ) if os.path.exists(lowercase ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , lowercase ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) __UpperCamelCase = ( processor.get_dev_examples(args.data_dir ) if mode == """dev""" else processor.get_train_examples(args.data_dir ) ) __UpperCamelCase = convert_examples_to_features( lowercase , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("""Saving features into cached file %s""" , lowercase ) torch.save(lowercase , lowercase ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase = False ) -> DataLoader: __UpperCamelCase = """dev""" if mode == """test""" else mode __UpperCamelCase = self._feature_file(lowercase ) logger.info("""Loading features from cached file %s""" , lowercase ) __UpperCamelCase = torch.load(lowercase ) __UpperCamelCase = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __UpperCamelCase = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __UpperCamelCase = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __UpperCamelCase = torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __UpperCamelCase = torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(lowercase , lowercase , lowercase , lowercase ) , batch_size=lowercase , shuffle=lowercase , ) def __lowerCamelCase ( self , lowercase , lowercase ) -> List[str]: __UpperCamelCase = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __UpperCamelCase = batch[2] if self.config.model_type in ["""bert""", """xlnet""", """albert"""] else None __UpperCamelCase = self(**lowercase ) __UpperCamelCase , __UpperCamelCase = outputs[:2] __UpperCamelCase = logits.detach().cpu().numpy() __UpperCamelCase = inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def __lowerCamelCase ( self , lowercase ) -> tuple: __UpperCamelCase = torch.stack([x["""val_loss"""] for x in outputs] ).mean().detach().cpu().item() __UpperCamelCase = np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __UpperCamelCase = np.argmax(lowercase , axis=1 ) elif self.hparams.glue_output_mode == "regression": __UpperCamelCase = np.squeeze(lowercase ) __UpperCamelCase = np.concatenate([x["""target"""] for x in outputs] , axis=0 ) __UpperCamelCase = [[] for _ in range(out_label_ids.shape[0] )] __UpperCamelCase = [[] for _ in range(out_label_ids.shape[0] )] __UpperCamelCase = {**{"""val_loss""": val_loss_mean}, **compute_metrics(self.hparams.task , lowercase , lowercase )} __UpperCamelCase = dict(results.items() ) __UpperCamelCase = results return ret, preds_list, out_label_list def __lowerCamelCase ( self , lowercase ) -> dict: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self._eval_end(lowercase ) __UpperCamelCase = ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def __lowerCamelCase ( self , lowercase ) -> dict: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self._eval_end(lowercase ) __UpperCamelCase = ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> Union[str, Any]: BaseTransformer.add_model_specific_args(lowercase , lowercase ) parser.add_argument( """--max_seq_length""" , default=1_2_8 , type=lowercase , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--task""" , default="""""" , type=lowercase , required=lowercase , help="""The GLUE task to run""" , ) parser.add_argument( """--gpus""" , default=0 , type=lowercase , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser def _lowercase ( ): '''simple docstring''' __UpperCamelCase = argparse.ArgumentParser() add_generic_args(__A ,os.getcwd() ) __UpperCamelCase = GLUETransformer.add_model_specific_args(__A ,os.getcwd() ) __UpperCamelCase = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __UpperCamelCase = os.path.join( """./results""" ,f"{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}" ,) os.makedirs(args.output_dir ) __UpperCamelCase = GLUETransformer(__A ) __UpperCamelCase = generic_train(__A ,__A ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __UpperCamelCase = sorted(glob.glob(os.path.join(args.output_dir ,"""checkpoint-epoch=*.ckpt""" ) ,recursive=__A ) ) __UpperCamelCase = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(__A ) if __name__ == "__main__": main()
349
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _lowercase ( __A ): '''simple docstring''' return (data["data"], data["target"]) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = XGBRegressor(verbosity=0 ,random_state=42 ) xgb.fit(__A ,__A ) # Predict target for test data __UpperCamelCase = xgb.predict(__A ) __UpperCamelCase = predictions.reshape(len(__A ) ,1 ) return predictions def _lowercase ( ): '''simple docstring''' __UpperCamelCase = fetch_california_housing() __UpperCamelCase , __UpperCamelCase = data_handling(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = train_test_split( __A ,__A ,test_size=0.25 ,random_state=1 ) __UpperCamelCase = xgboost(__A ,__A ,__A ) # Error printing print(f"Mean Absolute Error : {mean_absolute_error(__A ,__A )}" ) print(f"Mean Square Error : {mean_squared_error(__A ,__A )}" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
349
1
'''simple docstring''' import numpy # List of input, output pairs a__ : List[Any] = ( ((5, 2, 3), 1_5), ((6, 5, 9), 2_5), ((1_1, 1_2, 1_3), 4_1), ((1, 1, 1), 8), ((1_1, 1_2, 1_3), 4_1), ) a__ : List[str] = (((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0)) a__ : Optional[int] = [2, 4, 1, 5] a__ : Optional[Any] = len(train_data) a__ : Union[str, Any] = 0.0_09 def _lowercase ( __A ,__A="train" ): '''simple docstring''' return calculate_hypothesis_value(__A ,__A ) - output( __A ,__A ) def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = 0 for i in range(len(__A ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _lowercase ( __A ,__A ): '''simple docstring''' if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _lowercase ( __A ,__A ): '''simple docstring''' if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _lowercase ( __A ,__A=m ): '''simple docstring''' __UpperCamelCase = 0 for i in range(__A ): if index == -1: summation_value += _error(__A ) else: summation_value += _error(__A ) * train_data[i][0][index] return summation_value def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = summation_of_cost_derivative(__A ,__A ) / m return cost_derivative_value def _lowercase ( ): '''simple docstring''' global parameter_vector # Tune these values to set a tolerance value for predicted output __UpperCamelCase = 0.00_0002 __UpperCamelCase = 0 __UpperCamelCase = 0 while True: j += 1 __UpperCamelCase = [0, 0, 0, 0] for i in range(0 ,len(__A ) ): __UpperCamelCase = get_cost_derivative(i - 1 ) __UpperCamelCase = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( __A ,__A ,atol=__A ,rtol=__A ,): break __UpperCamelCase = temp_parameter_vector print(("""Number of iterations:""", j) ) def _lowercase ( ): '''simple docstring''' for i in range(len(__A ) ): print(("""Actual output value:""", output(__A ,"""test""" )) ) print(("""Hypothesis output:""", calculate_hypothesis_value(__A ,"""test""" )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=2 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=4_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: __UpperCamelCase = TFPegasusModel(config=lowercase ).get_decoder() __UpperCamelCase = inputs_dict["""input_ids"""] __UpperCamelCase = input_ids[:1, :] __UpperCamelCase = inputs_dict["""attention_mask"""][:1, :] __UpperCamelCase = inputs_dict["""head_mask"""] __UpperCamelCase = 1 # first forward pass __UpperCamelCase = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) __UpperCamelCase , __UpperCamelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __UpperCamelCase = tf.concat([input_ids, next_tokens] , axis=-1 ) __UpperCamelCase = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __UpperCamelCase = model(lowercase , attention_mask=lowercase )[0] __UpperCamelCase = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __UpperCamelCase = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx] __UpperCamelCase = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1E-3 ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,__A=None ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = tf.cast(tf.math.not_equal(__A ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: __UpperCamelCase = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: __UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () __SCREAMING_SNAKE_CASE = (TFPegasusForConditionalGeneration,) if is_tf_available() else () __SCREAMING_SNAKE_CASE = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> str: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_sentencepiece @require_tokenizers @require_tf class UpperCAmelCase__ ( unittest.TestCase): __SCREAMING_SNAKE_CASE = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] __SCREAMING_SNAKE_CASE = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers __SCREAMING_SNAKE_CASE = '''google/pegasus-xsum''' @cached_property def __lowerCamelCase ( self ) -> int: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __lowerCamelCase ( self ) -> str: __UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __lowerCamelCase ( self , **lowercase ) -> Optional[int]: __UpperCamelCase = self.translate_src_text(**lowercase ) assert self.expected_text == generated_words def __lowerCamelCase ( self , **lowercase ) -> Optional[Any]: __UpperCamelCase = self.tokenizer(self.src_text , **lowercase , padding=lowercase , return_tensors="""tf""" ) __UpperCamelCase = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) __UpperCamelCase = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase ) return generated_words @slow def __lowerCamelCase ( self ) -> Dict: self._assert_generated_batch_equal_expected()
349
1
'''simple docstring''' import baseaa def _lowercase ( __A ): '''simple docstring''' return baseaa.baaencode(string.encode("""utf-8""" ) ) def _lowercase ( __A ): '''simple docstring''' return baseaa.baadecode(__A ).decode("""utf-8""" ) if __name__ == "__main__": a__ : str = 'Hello World!' a__ : str = baseaa_encode(test) print(encoded) a__ : Union[str, Any] = baseaa_decode(encoded) print(decoded)
349
'''simple docstring''' import string def _lowercase ( __A ): '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): __UpperCamelCase = """""" for symbol in message: if symbol in string.ascii_uppercase: __UpperCamelCase = string.ascii_uppercase.find(__A ) __UpperCamelCase = num - key if num < 0: __UpperCamelCase = num + len(string.ascii_uppercase ) __UpperCamelCase = translated + string.ascii_uppercase[num] else: __UpperCamelCase = translated + symbol print(f"Decryption using Key #{key}: {translated}" ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = input("""Encrypted message: """ ) __UpperCamelCase = message.upper() decrypt(__A ) if __name__ == "__main__": import doctest doctest.testmod() main()
349
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Dict = logging.get_logger(__name__) a__ : str = { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json' ), } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''dpr''' def __init__( self , lowercase=3_0_5_2_2 , lowercase=7_6_8 , lowercase=1_2 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=5_1_2 , lowercase=2 , lowercase=0.02 , lowercase=1E-12 , lowercase=0 , lowercase="absolute" , lowercase = 0 , **lowercase , ) -> int: super().__init__(pad_token_id=lowercase , **lowercase ) __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 = projection_dim __UpperCamelCase = position_embedding_type
349
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a__ : Optional[Any] = logging.get_logger(__name__) a__ : Dict = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''gptj''' __SCREAMING_SNAKE_CASE = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , lowercase=5_0_4_0_0 , lowercase=2_0_4_8 , lowercase=4_0_9_6 , lowercase=2_8 , lowercase=1_6 , lowercase=6_4 , lowercase=None , lowercase="gelu_new" , lowercase=0.0 , lowercase=0.0 , lowercase=0.0 , lowercase=1E-5 , lowercase=0.02 , lowercase=True , lowercase=5_0_2_5_6 , lowercase=5_0_2_5_6 , lowercase=False , **lowercase , ) -> Tuple: __UpperCamelCase = vocab_size __UpperCamelCase = n_positions __UpperCamelCase = n_embd __UpperCamelCase = n_layer __UpperCamelCase = n_head __UpperCamelCase = n_inner __UpperCamelCase = rotary_dim __UpperCamelCase = activation_function __UpperCamelCase = resid_pdrop __UpperCamelCase = embd_pdrop __UpperCamelCase = attn_pdrop __UpperCamelCase = layer_norm_epsilon __UpperCamelCase = initializer_range __UpperCamelCase = use_cache __UpperCamelCase = bos_token_id __UpperCamelCase = eos_token_id super().__init__( bos_token_id=lowercase , eos_token_id=lowercase , tie_word_embeddings=lowercase , **lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase = "default" , lowercase = None , lowercase = False , ) -> List[str]: super().__init__(lowercase , task=lowercase , patching_specs=lowercase , use_past=lowercase ) if not getattr(self._config , """pad_token_id""" , lowercase ): # TODO: how to do that better? __UpperCamelCase = 0 @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: __UpperCamelCase = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(lowercase , direction="""inputs""" ) __UpperCamelCase = {0: """batch""", 1: """past_sequence + sequence"""} else: __UpperCamelCase = {0: """batch""", 1: """sequence"""} return common_inputs @property def __lowerCamelCase ( self ) -> int: return self._config.n_layer @property def __lowerCamelCase ( self ) -> int: return self._config.n_head def __lowerCamelCase ( self , lowercase , lowercase = -1 , lowercase = -1 , lowercase = False , lowercase = None , ) -> Mapping[str, Any]: __UpperCamelCase = super(lowercase , self ).generate_dummy_inputs( lowercase , batch_size=lowercase , seq_length=lowercase , is_pair=lowercase , framework=lowercase ) # We need to order the input in the way they appears in the forward() __UpperCamelCase = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch __UpperCamelCase , __UpperCamelCase = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values __UpperCamelCase = seqlen + 2 __UpperCamelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __UpperCamelCase = [ (torch.zeros(lowercase ), torch.zeros(lowercase )) for _ in range(self.num_layers ) ] __UpperCamelCase = common_inputs["""attention_mask"""] if self.use_past: __UpperCamelCase = ordered_inputs["""attention_mask"""].dtype __UpperCamelCase = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(lowercase , lowercase , dtype=lowercase )] , dim=1 ) return ordered_inputs @property def __lowerCamelCase ( self ) -> int: return 1_3
349
1
'''simple docstring''' import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib a__ : List[str] = threading.Lock() a__ : Optional[logging.Handler] = None a__ : Any = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } a__ : Optional[int] = logging.WARNING a__ : Any = True def _lowercase ( ): '''simple docstring''' __UpperCamelCase = os.getenv("""TRANSFORMERS_VERBOSITY""" ,__A ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, " f"has to be one of: { ', '.join(log_levels.keys() ) }" ) return _default_log_level def _lowercase ( ): '''simple docstring''' return __name__.split(""".""" )[0] def _lowercase ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def _lowercase ( ): '''simple docstring''' global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return __UpperCamelCase = logging.StreamHandler() # Set sys.stderr as stream. __UpperCamelCase = sys.stderr.flush # Apply our default configuration to the library root logger. __UpperCamelCase = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) __UpperCamelCase = False def _lowercase ( ): '''simple docstring''' global _default_handler with _lock: if not _default_handler: return __UpperCamelCase = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) __UpperCamelCase = None def _lowercase ( ): '''simple docstring''' return log_levels def _lowercase ( __A = None ): '''simple docstring''' if name is None: __UpperCamelCase = _get_library_name() _configure_library_root_logger() return logging.getLogger(__A ) def _lowercase ( ): '''simple docstring''' _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def _lowercase ( __A ): '''simple docstring''' _configure_library_root_logger() _get_library_root_logger().setLevel(__A ) def _lowercase ( ): '''simple docstring''' return set_verbosity(__A ) def _lowercase ( ): '''simple docstring''' return set_verbosity(__A ) def _lowercase ( ): '''simple docstring''' return set_verbosity(__A ) def _lowercase ( ): '''simple docstring''' return set_verbosity(__A ) def _lowercase ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def _lowercase ( ): '''simple docstring''' _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def _lowercase ( __A ): '''simple docstring''' _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(__A ) def _lowercase ( __A ): '''simple docstring''' _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(__A ) def _lowercase ( ): '''simple docstring''' _configure_library_root_logger() __UpperCamelCase = False def _lowercase ( ): '''simple docstring''' _configure_library_root_logger() __UpperCamelCase = True def _lowercase ( ): '''simple docstring''' __UpperCamelCase = _get_library_root_logger().handlers for handler in handlers: __UpperCamelCase = logging.Formatter("""[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s""" ) handler.setFormatter(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(__A ) def _lowercase ( self ,*__A ,**__A ): '''simple docstring''' __UpperCamelCase = os.getenv("""TRANSFORMERS_NO_ADVISORY_WARNINGS""" ,__A ) if no_advisory_warnings: return self.warning(*__A ,**__A ) a__ : Tuple = warning_advice @functools.lru_cache(__A ) def _lowercase ( self ,*__A ,**__A ): '''simple docstring''' self.warning(*__A ,**__A ) a__ : str = warning_once class UpperCAmelCase__ : def __init__( self , *lowercase , **lowercase ) -> List[Any]: # pylint: disable=unused-argument __UpperCamelCase = args[0] if args else None def __iter__( self ) -> int: return iter(self._iterator ) def __getattr__( self , lowercase ) -> Union[str, Any]: def empty_fn(*lowercase , **lowercase ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ) -> Dict: return self def __exit__( self , lowercase , lowercase , lowercase ) -> Union[str, Any]: return class UpperCAmelCase__ : def __call__( self , *lowercase , **lowercase ) -> Any: if _tqdm_active: return tqdm_lib.tqdm(*lowercase , **lowercase ) else: return EmptyTqdm(*lowercase , **lowercase ) def __lowerCamelCase ( self , *lowercase , **lowercase ) -> Optional[Any]: __UpperCamelCase = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*lowercase , **lowercase ) def __lowerCamelCase ( self ) -> int: if _tqdm_active: return tqdm_lib.tqdm.get_lock() a__ : Union[str, Any] = _tqdm_cls() def _lowercase ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def _lowercase ( ): '''simple docstring''' global _tqdm_active __UpperCamelCase = True hf_hub_utils.enable_progress_bars() def _lowercase ( ): '''simple docstring''' global _tqdm_active __UpperCamelCase = False hf_hub_utils.disable_progress_bars()
349
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a__ : int = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['LayoutLMv3FeatureExtractor'] a__ : str = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys a__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
349
1
'''simple docstring''' import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer a__ : Any = logging.get_logger(__name__) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''AutoTokenizer''' __SCREAMING_SNAKE_CASE = ['''tokenizer'''] __SCREAMING_SNAKE_CASE = { '''semantic_prompt''': 1, '''coarse_prompt''': 2, '''fine_prompt''': 2, } def __init__( self , lowercase , lowercase=None ) -> Optional[int]: super().__init__(lowercase ) __UpperCamelCase = speaker_embeddings @classmethod def __lowerCamelCase ( cls , lowercase , lowercase="speaker_embeddings_path.json" , **lowercase ) -> List[Any]: if speaker_embeddings_dict_path is not None: __UpperCamelCase = get_file_from_repo( lowercase , lowercase , subfolder=kwargs.pop("""subfolder""" , lowercase ) , cache_dir=kwargs.pop("""cache_dir""" , lowercase ) , force_download=kwargs.pop("""force_download""" , lowercase ) , proxies=kwargs.pop("""proxies""" , lowercase ) , resume_download=kwargs.pop("""resume_download""" , lowercase ) , local_files_only=kwargs.pop("""local_files_only""" , lowercase ) , use_auth_token=kwargs.pop("""use_auth_token""" , lowercase ) , revision=kwargs.pop("""revision""" , lowercase ) , ) if speaker_embeddings_path is None: logger.warning( f"`{os.path.join(lowercase , lowercase )}` does not exists\n , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`." ) __UpperCamelCase = None else: with open(lowercase ) as speaker_embeddings_json: __UpperCamelCase = json.load(lowercase ) else: __UpperCamelCase = None __UpperCamelCase = AutoTokenizer.from_pretrained(lowercase , **lowercase ) return cls(tokenizer=lowercase , speaker_embeddings=lowercase ) def __lowerCamelCase ( self , lowercase , lowercase="speaker_embeddings_path.json" , lowercase="speaker_embeddings" , lowercase = False , **lowercase , ) -> Any: if self.speaker_embeddings is not None: os.makedirs(os.path.join(lowercase , lowercase , """v2""" ) , exist_ok=lowercase ) __UpperCamelCase = {} __UpperCamelCase = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": __UpperCamelCase = self._load_voice_preset(lowercase ) __UpperCamelCase = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict["""repo_or_path"""] , lowercase , f"{prompt_key}_{key}" ) , voice_preset[key] , allow_pickle=lowercase , ) __UpperCamelCase = os.path.join(lowercase , f"{prompt_key}_{key}.npy" ) __UpperCamelCase = tmp_dict with open(os.path.join(lowercase , lowercase ) , """w""" ) as fp: json.dump(lowercase , lowercase ) super().save_pretrained(lowercase , lowercase , **lowercase ) def __lowerCamelCase ( self , lowercase = None , **lowercase ) -> Optional[int]: __UpperCamelCase = self.speaker_embeddings[voice_preset] __UpperCamelCase = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( f"Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}]." ) __UpperCamelCase = get_file_from_repo( self.speaker_embeddings.get("""repo_or_path""" , """/""" ) , voice_preset_paths[key] , subfolder=kwargs.pop("""subfolder""" , lowercase ) , cache_dir=kwargs.pop("""cache_dir""" , lowercase ) , force_download=kwargs.pop("""force_download""" , lowercase ) , proxies=kwargs.pop("""proxies""" , lowercase ) , resume_download=kwargs.pop("""resume_download""" , lowercase ) , local_files_only=kwargs.pop("""local_files_only""" , lowercase ) , use_auth_token=kwargs.pop("""use_auth_token""" , lowercase ) , revision=kwargs.pop("""revision""" , lowercase ) , ) if path is None: raise ValueError( f"`{os.path.join(self.speaker_embeddings.get('repo_or_path' , '/' ) , voice_preset_paths[key] )}` does not exists\n , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n embeddings." ) __UpperCamelCase = np.load(lowercase ) return voice_preset_dict def __lowerCamelCase ( self , lowercase = None ) -> Optional[Any]: for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(f"Voice preset unrecognized, missing {key} as a key." ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray." ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray." ) def __call__( self , lowercase=None , lowercase=None , lowercase="pt" , lowercase=2_5_6 , lowercase=False , lowercase=True , lowercase=False , **lowercase , ) -> Dict: if voice_preset is not None and not isinstance(lowercase , lowercase ): if ( isinstance(lowercase , lowercase ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): __UpperCamelCase = self._load_voice_preset(lowercase ) else: if isinstance(lowercase , lowercase ) and not voice_preset.endswith(""".npz""" ): __UpperCamelCase = voice_preset + """.npz""" __UpperCamelCase = np.load(lowercase ) if voice_preset is not None: self._validate_voice_preset_dict(lowercase , **lowercase ) __UpperCamelCase = BatchFeature(data=lowercase , tensor_type=lowercase ) __UpperCamelCase = self.tokenizer( lowercase , return_tensors=lowercase , padding="""max_length""" , max_length=lowercase , return_attention_mask=lowercase , return_token_type_ids=lowercase , add_special_tokens=lowercase , **lowercase , ) if voice_preset is not None: __UpperCamelCase = voice_preset return encoded_text
349
'''simple docstring''' def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = len(__A ) __UpperCamelCase = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __UpperCamelCase = True # sum is not zero and set is empty then false for i in range(1 ,required_sum + 1 ): __UpperCamelCase = False for i in range(1 ,arr_len + 1 ): for j in range(1 ,required_sum + 1 ): if arr[i - 1] > j: __UpperCamelCase = subset[i - 1][j] if arr[i - 1] <= j: __UpperCamelCase = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' import argparse from collections import defaultdict import yaml a__ : Any = 'docs/source/en/_toctree.yml' def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = defaultdict(__A ) for doc in model_doc: counts[doc["local"]] += 1 __UpperCamelCase = [key for key, value in counts.items() if value > 1] __UpperCamelCase = [] for duplicate_key in duplicates: __UpperCamelCase = list({doc["""title"""] for doc in model_doc if doc["""local"""] == duplicate_key} ) if len(__A ) > 1: raise ValueError( f"{duplicate_key} is present several times in the documentation table of content at " """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc["""local"""]] == 1] ) # Sort return sorted(__A ,key=lambda __A : s["title"].lower() ) def _lowercase ( __A=False ): '''simple docstring''' with open(__A ,encoding="""utf-8""" ) as f: __UpperCamelCase = yaml.safe_load(f.read() ) # Get to the API doc __UpperCamelCase = 0 while content[api_idx]["title"] != "API": api_idx += 1 __UpperCamelCase = content[api_idx]["""sections"""] # Then to the model doc __UpperCamelCase = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 __UpperCamelCase = api_doc[model_idx]["""sections"""] __UpperCamelCase = [(idx, section) for idx, section in enumerate(__A ) if """sections""" in section] __UpperCamelCase = False for idx, modality_doc in modalities_docs: __UpperCamelCase = modality_doc["""sections"""] __UpperCamelCase = clean_model_doc_toc(__A ) if old_modality_doc != new_modality_doc: __UpperCamelCase = True if overwrite: __UpperCamelCase = new_modality_doc if diff: if overwrite: __UpperCamelCase = model_doc __UpperCamelCase = api_doc with open(__A ,"""w""" ,encoding="""utf-8""" ) as f: f.write(yaml.dump(__A ,allow_unicode=__A ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": a__ : List[str] = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') a__ : Optional[int] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
349
'''simple docstring''' import bza import gzip import lzma import os import shutil import struct import tarfile import warnings import zipfile from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, List, Optional, Type, Union from .. import config from .filelock import FileLock from .logging import get_logger a__ : Any = get_logger(__name__) class UpperCAmelCase__ : def __init__( self , lowercase = None ) -> List[str]: __UpperCamelCase = ( os.path.join(lowercase , config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH ) __UpperCamelCase = Extractor def __lowerCamelCase ( self , lowercase ) -> str: from .file_utils import hash_url_to_filename # Path where we extract compressed archives # We extract in the cache dir, and get the extracted path name by hashing the original path" __UpperCamelCase = os.path.abspath(lowercase ) return os.path.join(self.extract_dir , hash_url_to_filename(lowercase ) ) def __lowerCamelCase ( self , lowercase , lowercase ) -> bool: return force_extract or ( not os.path.isfile(lowercase ) and not (os.path.isdir(lowercase ) and os.listdir(lowercase )) ) def __lowerCamelCase ( self , lowercase , lowercase = False ) -> str: __UpperCamelCase = self.extractor.infer_extractor_format(lowercase ) if not extractor_format: return input_path __UpperCamelCase = self._get_output_path(lowercase ) if self._do_extract(lowercase , lowercase ): self.extractor.extract(lowercase , lowercase , lowercase ) return output_path class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod @abstractmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: ... @staticmethod @abstractmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: ... class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> int: with open(lowercase , """rb""" ) as f: return f.read(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if not magic_number: __UpperCamelCase = max(len(lowercase ) for cls_magic_number in cls.magic_numbers ) try: __UpperCamelCase = cls.read_magic_number(lowercase , lowercase ) except OSError: return False return any(magic_number.startswith(lowercase ) for cls_magic_number in cls.magic_numbers ) class UpperCAmelCase__ ( UpperCAmelCase_): @classmethod def __lowerCamelCase ( cls , lowercase , **lowercase ) -> bool: return tarfile.is_tarfile(lowercase ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: def resolved(lowercase ) -> str: return os.path.realpath(os.path.abspath(lowercase ) ) def badpath(lowercase , lowercase ) -> bool: # joinpath will ignore base if path is absolute return not resolved(os.path.join(lowercase , lowercase ) ).startswith(lowercase ) def badlink(lowercase , lowercase ) -> bool: # Links are interpreted relative to the directory containing the link __UpperCamelCase = resolved(os.path.join(lowercase , os.path.dirname(info.name ) ) ) return badpath(info.linkname , base=lowercase ) __UpperCamelCase = resolved(lowercase ) for finfo in members: if badpath(finfo.name , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked (illegal path)" ) elif finfo.issym() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}" ) elif finfo.islnk() and badlink(lowercase , lowercase ): logger.error(f"Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}" ) else: yield finfo @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = tarfile.open(lowercase ) tar_file.extractall(lowercase , members=TarExtractor.safemembers(lowercase , lowercase ) ) tar_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x1F\x8B'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with gzip.open(lowercase , """rb""" ) as gzip_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [ B'''PK\x03\x04''', B'''PK\x05\x06''', # empty archive B'''PK\x07\x08''', # spanned archive ] @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = b"" ) -> bool: if super().is_extractable(lowercase , magic_number=lowercase ): return True try: # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives. # From: https://github.com/python/cpython/pull/5053 from zipfile import ( _CD_SIGNATURE, _ECD_DISK_NUMBER, _ECD_DISK_START, _ECD_ENTRIES_TOTAL, _ECD_OFFSET, _ECD_SIZE, _EndRecData, sizeCentralDir, stringCentralDir, structCentralDir, ) with open(lowercase , """rb""" ) as fp: __UpperCamelCase = _EndRecData(lowercase ) if endrec: if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0: return True # Empty zipfiles are still zipfiles elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]: fp.seek(endrec[_ECD_OFFSET] ) # Central directory is on the same disk if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir: __UpperCamelCase = fp.read(lowercase ) # CD is where we expect it to be if len(lowercase ) == sizeCentralDir: __UpperCamelCase = struct.unpack(lowercase , lowercase ) # CD is the right size if centdir[_CD_SIGNATURE] == stringCentralDir: return True # First central directory entry has correct magic number return False except Exception: # catch all errors in case future python versions change the zipfile internals return False @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: os.makedirs(lowercase , exist_ok=lowercase ) with zipfile.ZipFile(lowercase , """r""" ) as zip_file: zip_file.extractall(lowercase ) zip_file.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\xFD\x37\x7A\x58\x5A\x00'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with lzma.open(lowercase ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00'''] # RAR_ID # RAR5_ID @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.RARFILE_AVAILABLE: raise ImportError("""Please pip install rarfile""" ) import rarfile os.makedirs(lowercase , exist_ok=lowercase ) __UpperCamelCase = rarfile.RarFile(lowercase ) rf.extractall(lowercase ) rf.close() class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x28\xb5\x2F\xFD'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.ZSTANDARD_AVAILABLE: raise ImportError("""Please pip install zstandard""" ) import zstandard as zstd __UpperCamelCase = zstd.ZstdDecompressor() with open(lowercase , """rb""" ) as ifh, open(lowercase , """wb""" ) as ofh: dctx.copy_stream(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x42\x5A\x68'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: with bza.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x37\x7A\xBC\xAF\x27\x1C'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.PY7ZR_AVAILABLE: raise ImportError("""Please pip install py7zr""" ) import pyazr os.makedirs(lowercase , exist_ok=lowercase ) with pyazr.SevenZipFile(lowercase , """r""" ) as archive: archive.extractall(lowercase ) class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = [B'''\x04\x22\x4D\x18'''] @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> None: if not config.LZ4_AVAILABLE: raise ImportError("""Please pip install lz4""" ) import lza.frame with lza.frame.open(lowercase , """rb""" ) as compressed_file: with open(lowercase , """wb""" ) as extracted_file: shutil.copyfileobj(lowercase , lowercase ) class UpperCAmelCase__ : # Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip) __SCREAMING_SNAKE_CASE = { "tar": TarExtractor, "gzip": GzipExtractor, "zip": ZipExtractor, "xz": XzExtractor, "rar": RarExtractor, "zstd": ZstdExtractor, "bz2": BzipaExtractor, "7z": SevenZipExtractor, # <Added version="2.4.0"/> "lz4": LzaExtractor, # <Added version="2.4.0"/> } @classmethod def __lowerCamelCase ( cls ) -> Union[str, Any]: return max( len(lowercase ) for extractor in cls.extractors.values() if issubclass(lowercase , lowercase ) for extractor_magic_number in extractor.magic_numbers ) @staticmethod def __lowerCamelCase ( lowercase , lowercase ) -> str: try: return MagicNumberBaseExtractor.read_magic_number(lowercase , magic_number_length=lowercase ) except OSError: return b"" @classmethod def __lowerCamelCase ( cls , lowercase , lowercase = False ) -> bool: warnings.warn( """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'infer_extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = cls.infer_extractor_format(lowercase ) if extractor_format: return True if not return_extractor else (True, cls.extractors[extractor_format]) return False if not return_extractor else (False, None) @classmethod def __lowerCamelCase ( cls , lowercase ) -> str: # <Added version="2.4.0"/> __UpperCamelCase = cls._get_magic_number_max_length() __UpperCamelCase = cls._read_magic_number(lowercase , lowercase ) for extractor_format, extractor in cls.extractors.items(): if extractor.is_extractable(lowercase , magic_number=lowercase ): return extractor_format @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase = None , lowercase = "deprecated" , ) -> None: os.makedirs(os.path.dirname(lowercase ) , exist_ok=lowercase ) # Prevent parallel extractions __UpperCamelCase = str(Path(lowercase ).with_suffix(""".lock""" ) ) with FileLock(lowercase ): shutil.rmtree(lowercase , ignore_errors=lowercase ) if extractor_format or extractor != "deprecated": if extractor != "deprecated" or not isinstance(lowercase , lowercase ): # passed as positional arg warnings.warn( """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """ """Use 'extractor_format' instead.""" , category=lowercase , ) __UpperCamelCase = extractor if extractor != """deprecated""" else extractor_format else: __UpperCamelCase = cls.extractors[extractor_format] return extractor.extract(lowercase , lowercase ) else: warnings.warn( """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """ """exception in 3.0.0.""" , category=lowercase , ) for extractor in cls.extractors.values(): if extractor.is_extractable(lowercase ): return extractor.extract(lowercase , lowercase )
349
1
'''simple docstring''' from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging a__ : Dict = logging.get_logger(__name__) def _lowercase ( __A ,__A ): '''simple docstring''' try: with open(__A ,"""rb""" ) as flax_state_f: __UpperCamelCase = from_bytes(__A ,flax_state_f.read() ) except UnpicklingError as e: try: with open(__A ) as f: if f.read().startswith("""version""" ): raise OSError( """You seem to have cloned a repository without having git-lfs installed. Please""" """ install git-lfs and run `git lfs install` followed by `git lfs pull` in the""" """ folder you cloned.""" ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. " ) return load_flax_weights_in_pytorch_model(__A ,__A ) def _lowercase ( __A ,__A ): '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( """Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see""" """ https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation""" """ instructions.""" ) raise # check if we have bf16 weights __UpperCamelCase = flatten_dict(jax.tree_util.tree_map(lambda __A : x.dtype == jnp.bfloataa ,__A ) ).values() if any(__A ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( """Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` """ """before loading those in PyTorch model.""" ) __UpperCamelCase = jax.tree_util.tree_map( lambda __A : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params ,__A ) __UpperCamelCase = """""" __UpperCamelCase = flatten_dict(__A ,sep=""".""" ) __UpperCamelCase = pt_model.state_dict() # keep track of unexpected & missing keys __UpperCamelCase = [] __UpperCamelCase = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): __UpperCamelCase = flax_key_tuple.split(""".""" ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: __UpperCamelCase = flax_key_tuple_array[:-1] + ["""weight"""] __UpperCamelCase = jnp.transpose(__A ,(3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": __UpperCamelCase = flax_key_tuple_array[:-1] + ["""weight"""] __UpperCamelCase = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": __UpperCamelCase = flax_key_tuple_array[:-1] + ["""weight"""] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(__A ): __UpperCamelCase = ( flax_key_tuple_string.replace("""_0""" ,""".0""" ) .replace("""_1""" ,""".1""" ) .replace("""_2""" ,""".2""" ) .replace("""_3""" ,""".3""" ) .replace("""_4""" ,""".4""" ) .replace("""_5""" ,""".5""" ) .replace("""_6""" ,""".6""" ) .replace("""_7""" ,""".7""" ) .replace("""_8""" ,""".8""" ) .replace("""_9""" ,""".9""" ) ) __UpperCamelCase = """.""".join(__A ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." ) else: # add weight to pytorch dict __UpperCamelCase = np.asarray(__A ) if not isinstance(__A ,np.ndarray ) else flax_tensor __UpperCamelCase = torch.from_numpy(__A ) # remove from missing keys missing_keys.remove(__A ) else: # weight is not expected by PyTorch model unexpected_keys.append(__A ) pt_model.load_state_dict(__A ) # re-transform missing_keys to list __UpperCamelCase = list(__A ) if len(__A ) > 0: logger.warning( """Some weights of the Flax model were not used when initializing the PyTorch model""" f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" """ (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This""" f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" """ to be exactly identical (e.g. initializing a BertForSequenceClassification model from a""" """ FlaxBertForSequenceClassification model).""" ) if len(__A ) > 0: logger.warning( f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" """ use it for predictions and inference.""" ) return pt_model
349
'''simple docstring''' import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html a__ : List[str] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class UpperCAmelCase__ : __SCREAMING_SNAKE_CASE = PegasusConfig __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = '''gelu''' def __init__( self , lowercase , lowercase=1_3 , lowercase=7 , lowercase=True , lowercase=False , lowercase=9_9 , lowercase=3_2 , lowercase=5 , lowercase=4 , lowercase=3_7 , lowercase=0.1 , lowercase=0.1 , lowercase=2_0 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Optional[Any]: __UpperCamelCase = parent __UpperCamelCase = batch_size __UpperCamelCase = seq_length __UpperCamelCase = is_training __UpperCamelCase = use_labels __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = eos_token_id __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id def __lowerCamelCase ( self ) -> str: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __UpperCamelCase = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCamelCase = np.concatenate([input_ids, eos_tensor] , axis=1 ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCamelCase = prepare_pegasus_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , decoder_attention_mask=lowercase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase ) -> Any: __UpperCamelCase = 2_0 __UpperCamelCase = model_class_name(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] ) __UpperCamelCase , __UpperCamelCase = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCamelCase = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __UpperCamelCase = model.init_cache(decoder_input_ids.shape[0] , lowercase , lowercase ) __UpperCamelCase = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCamelCase = model.decode( decoder_input_ids[:, :-1] , lowercase , decoder_attention_mask=lowercase , past_key_values=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCamelCase = model.decode( decoder_input_ids[:, -1:] , lowercase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowercase , decoder_position_ids=lowercase , ) __UpperCamelCase = model.decode(lowercase , lowercase , decoder_attention_mask=lowercase ) __UpperCamelCase = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def _lowercase ( __A ,__A ,__A ,__A=None ,__A=None ,): '''simple docstring''' if attention_mask is None: __UpperCamelCase = np.not_equal(__A ,config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __UpperCamelCase = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape ,dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ).astype(np.inta ), ] ,axis=-1 ,) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class UpperCAmelCase__ ( UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __SCREAMING_SNAKE_CASE = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = FlaxPegasusModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase ) def __lowerCamelCase ( self ) -> List[Any]: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowercase , lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = self._prepare_for_class(lowercase , lowercase ) __UpperCamelCase = model_class(lowercase ) @jax.jit def encode_jitted(lowercase , lowercase=None , **lowercase ): return model.encode(input_ids=lowercase , attention_mask=lowercase ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = encode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCamelCase = model_class(lowercase ) __UpperCamelCase = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) __UpperCamelCase = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(lowercase , lowercase , lowercase ): return model.decode( decoder_input_ids=lowercase , decoder_attention_mask=lowercase , encoder_outputs=lowercase , ) with self.subTest("""JIT Enabled""" ): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCamelCase = decode_jitted(**lowercase ).to_tuple() self.assertEqual(len(lowercase ) , len(lowercase ) ) for jitted_output, output in zip(lowercase , lowercase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __lowerCamelCase ( self ) -> Dict: for model_class_name in self.all_model_classes: __UpperCamelCase = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=lowercase ) __UpperCamelCase = np.ones((1, 1) ) __UpperCamelCase = model(lowercase ) self.assertIsNotNone(lowercase ) @slow def __lowerCamelCase ( self ) -> str: __UpperCamelCase = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) __UpperCamelCase = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] __UpperCamelCase = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] __UpperCamelCase = tokenizer(lowercase , return_tensors="""np""" , truncation=lowercase , max_length=5_1_2 , padding=lowercase ) __UpperCamelCase = model.generate(**lowercase , num_beams=2 ).sequences __UpperCamelCase = tokenizer.batch_decode(lowercase , skip_special_tokens=lowercase ) assert tgt_text == decoded
349
1
'''simple docstring''' import requests from bsa import BeautifulSoup def _lowercase ( __A = "AAPL" ): '''simple docstring''' __UpperCamelCase = f"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" __UpperCamelCase = BeautifulSoup(requests.get(__A ).text ,"""html.parser""" ) __UpperCamelCase = """My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" ,class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
349
'''simple docstring''' import pytest a__ : List[str] = '__dummy_dataset1__' a__ : Optional[int] = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def _lowercase ( ): '''simple docstring''' return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = dataset_loading_script_name __UpperCamelCase = tmp_path / """datasets""" / script_name script_dir.mkdir(parents=__A ) __UpperCamelCase = script_dir / f"{script_name}.py" with open(__A ,"""w""" ) as f: f.write(__A ) return str(__A )
349
1
'''simple docstring''' import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase=None , lowercase=True , lowercase=None , **lowercase ) -> Union[str, Any]: __UpperCamelCase = parent __UpperCamelCase = config_class __UpperCamelCase = has_text_modality __UpperCamelCase = kwargs __UpperCamelCase = common_properties def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.config_class(**self.inputs_dict ) __UpperCamelCase = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(lowercase , lowercase ) , msg=f"`{prop}` does not exist" ) # Test that config has the common properties as setter for idx, name in enumerate(lowercase ): try: setattr(lowercase , lowercase , lowercase ) self.parent.assertEqual( getattr(lowercase , lowercase ) , lowercase , msg=f"`{name} value {idx} expected, but was {getattr(lowercase , lowercase )}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(lowercase ): try: __UpperCamelCase = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(lowercase , lowercase ) , lowercase , msg=f"`{name} value {idx} expected, but was {getattr(lowercase , lowercase )}" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = self.config_class(**self.inputs_dict ) __UpperCamelCase = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = os.path.join(lowercase , """config.json""" ) config_first.to_json_file(lowercase ) __UpperCamelCase = self.config_class.from_json_file(lowercase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(lowercase ) __UpperCamelCase = self.config_class.from_pretrained(lowercase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.config_class(**self.inputs_dict ) __UpperCamelCase = """test""" with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = os.path.join(lowercase , lowercase ) config_first.save_pretrained(lowercase ) __UpperCamelCase = self.config_class.from_pretrained(lowercase , subfolder=lowercase ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) __UpperCamelCase = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def __lowerCamelCase ( self ) -> List[str]: if self.config_class.is_composition: return __UpperCamelCase = self.config_class() self.parent.assertIsNotNone(lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = copy.deepcopy(lowercase ) __UpperCamelCase = self.config_class(**lowercase ) __UpperCamelCase = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(lowercase , lowercase ) != value: wrong_values.append((key, getattr(lowercase , lowercase ), value) ) if len(lowercase ) > 0: __UpperCamelCase = """\n""".join([f"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values] ) raise ValueError(f"The following keys were not properly set in the config:\n{errors}" ) def __lowerCamelCase ( self ) -> List[Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
349
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConfig, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaForPreTraining, WavaVecaProcessor, logging, ) from transformers.models.wavaveca.modeling_wavaveca import WavaVecaForSequenceClassification logging.set_verbosity_info() a__ : Any = logging.get_logger(__name__) a__ : Optional[int] = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'adapter_layer': 'encoder.layers.*.adapter_layer', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', 'pooling_layer.linear': 'projector', 'pooling_layer.projection': 'classifier', } a__ : List[str] = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'projector', 'classifier', ] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} with open(__A ,"""r""" ) as file: for line_number, line in enumerate(__A ): __UpperCamelCase = line.strip() if line: __UpperCamelCase = line.split() __UpperCamelCase = line_number __UpperCamelCase = words[0] __UpperCamelCase = value return result def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' for attribute in key.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = getattr(__A ,__A ).shape elif weight_type is not None and weight_type == "param": __UpperCamelCase = hf_pointer for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = shape_pointer.shape # let's reduce dimension __UpperCamelCase = value[0] 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 == "param": for attribute in hf_param_name.split(""".""" ): __UpperCamelCase = getattr(__A ,__A ) __UpperCamelCase = value else: __UpperCamelCase = value logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = None for param_key in PARAM_MAPPING.keys(): if full_name.endswith(__A ): __UpperCamelCase = PARAM_MAPPING[full_name.split(""".""" )[-1]] __UpperCamelCase = """param""" if weight_type is not None and weight_type != "param": __UpperCamelCase = """.""".join([key, weight_type] ) elif weight_type is not None and weight_type == "param": __UpperCamelCase = """.""".join([key, hf_param_name] ) else: __UpperCamelCase = key __UpperCamelCase = value if """lm_head""" in full_key else value[0] a__ : Dict = { 'W_a': 'linear_1.weight', 'W_b': 'linear_2.weight', 'b_a': 'linear_1.bias', 'b_b': 'linear_2.bias', 'ln_W': 'norm.weight', 'ln_b': 'norm.bias', } def _lowercase ( __A ,__A ,__A=None ,__A=None ): '''simple docstring''' __UpperCamelCase = False for key, mapped_key in MAPPING.items(): __UpperCamelCase = """wav2vec2.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __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: # TODO: don't match quantizer.weight_proj __UpperCamelCase = """weight""" else: __UpperCamelCase = None if hf_dict is not None: rename_dict(__A ,__A ,__A ,__A ,__A ) else: set_recursively(__A ,__A ,__A ,__A ,__A ) return is_used return is_used def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = [] __UpperCamelCase = fairseq_model.state_dict() __UpperCamelCase = hf_model.wavaveca.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase = False if "conv_layers" in name: load_conv_layer( __A ,__A ,__A ,__A ,hf_model.config.feat_extract_norm == """group""" ,) __UpperCamelCase = True else: __UpperCamelCase = load_wavaveca_layer(__A ,__A ,__A ) if not is_used: unused_weights.append(__A ) logger.warning(f"Unused weights: {unused_weights}" ) def _lowercase ( __A ,__A ,__A ,__A ,__A ): '''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 _lowercase ( __A ,__A ,__A=None ,__A=None ,__A=True ,__A=False ): '''simple docstring''' if config_path is not None: __UpperCamelCase = WavaVecaConfig.from_pretrained(__A ) else: __UpperCamelCase = WavaVecaConfig() if is_seq_class: __UpperCamelCase = read_txt_into_dict(__A ) __UpperCamelCase = idalabel __UpperCamelCase = WavaVecaForSequenceClassification(__A ) __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) feature_extractor.save_pretrained(__A ) elif is_finetuned: if dict_path: __UpperCamelCase = Dictionary.load(__A ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase = target_dict.pad_index __UpperCamelCase = target_dict.bos_index __UpperCamelCase = target_dict.eos_index __UpperCamelCase = len(target_dict.symbols ) __UpperCamelCase = os.path.join(__A ,"""vocab.json""" ) if not os.path.isdir(__A ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__A ) ) return os.makedirs(__A ,exist_ok=__A ) __UpperCamelCase = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCamelCase = 0 __UpperCamelCase = 1 with open(__A ,"""w""" ,encoding="""utf-8""" ) as vocab_handle: json.dump(__A ,__A ) __UpperCamelCase = WavaVecaCTCTokenizer( __A ,unk_token=target_dict.unk_word ,pad_token=target_dict.pad_word ,bos_token=target_dict.bos_word ,eos_token=target_dict.eos_word ,word_delimiter_token="""|""" ,do_lower_case=__A ,) __UpperCamelCase = True if config.feat_extract_norm == """layer""" else False __UpperCamelCase = WavaVecaFeatureExtractor( feature_size=1 ,sampling_rate=16_000 ,padding_value=0 ,do_normalize=__A ,return_attention_mask=__A ,) __UpperCamelCase = WavaVecaProcessor(feature_extractor=__A ,tokenizer=__A ) processor.save_pretrained(__A ) __UpperCamelCase = WavaVecaForCTC(__A ) else: __UpperCamelCase = WavaVecaForPreTraining(__A ) if is_finetuned or is_seq_class: __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] ,arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __UpperCamelCase = argparse.Namespace(task="""audio_pretraining""" ) __UpperCamelCase = fairseq.tasks.setup_task(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ,task=__A ) __UpperCamelCase = model[0].eval() recursively_load_weights(__A ,__A ,not is_finetuned ) hf_wavavec.save_pretrained(__A ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) parser.add_argument( '--is_seq_class', action='store_true', help='Whether the model to convert is a fine-tuned sequence classification model or not', ) a__ : Optional[int] = parser.parse_args() a__ : str = not args.not_finetuned and not args.is_seq_class convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, is_finetuned, args.is_seq_class, )
349
1
'''simple docstring''' def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = (boundary[1] - boundary[0]) / steps __UpperCamelCase = boundary[0] __UpperCamelCase = boundary[1] __UpperCamelCase = make_points(__A ,__A ,__A ) __UpperCamelCase = 0.0 y += (h / 2.0) * f(__A ) for i in x_i: # print(i) y += h * f(__A ) y += (h / 2.0) * f(__A ) return y def _lowercase ( __A ,__A ,__A ): '''simple docstring''' __UpperCamelCase = a + h while x < (b - h): yield x __UpperCamelCase = x + h def _lowercase ( __A ): # enter your function here '''simple docstring''' __UpperCamelCase = (x - 0) * (x - 0) return y def _lowercase ( ): '''simple docstring''' __UpperCamelCase = 0.0 # Lower bound of integration __UpperCamelCase = 1.0 # Upper bound of integration __UpperCamelCase = 10.0 # define number of steps or resolution __UpperCamelCase = [a, b] # define boundary of integration __UpperCamelCase = method_a(__A ,__A ) print(f"y = {y}" ) if __name__ == "__main__": main()
349
'''simple docstring''' from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCAmelCase__ : def __init__( self , lowercase , ) -> Union[str, Any]: __UpperCamelCase = parent __UpperCamelCase = 1_3 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = 9_9 __UpperCamelCase = 3_2 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 3_7 __UpperCamelCase = """gelu""" __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 5_1_2 __UpperCamelCase = 1_6 __UpperCamelCase = 2 __UpperCamelCase = 0.02 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = None def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = None if self.use_input_mask: __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: __UpperCamelCase = TFDistilBertModel(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]: __UpperCamelCase = TFDistilBertForMaskedLM(config=lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = TFDistilBertForQuestionAnswering(config=lowercase ) __UpperCamelCase = { """input_ids""": input_ids, """attention_mask""": input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Tuple: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForSequenceClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: __UpperCamelCase = self.num_choices __UpperCamelCase = TFDistilBertForMultipleChoice(lowercase ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(lowercase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[int]: __UpperCamelCase = self.num_labels __UpperCamelCase = TFDistilBertForTokenClassification(lowercase ) __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} __UpperCamelCase = model(lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.prepare_config_and_inputs() ((__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase) , (__UpperCamelCase)) = config_and_inputs __UpperCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCAmelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): __SCREAMING_SNAKE_CASE = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __SCREAMING_SNAKE_CASE = ( { '''feature-extraction''': TFDistilBertModel, '''fill-mask''': TFDistilBertForMaskedLM, '''question-answering''': TFDistilBertForQuestionAnswering, '''text-classification''': TFDistilBertForSequenceClassification, '''token-classification''': TFDistilBertForTokenClassification, '''zero-shot''': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = TFDistilBertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=lowercase , dim=3_7 ) def __lowerCamelCase ( self ) -> Any: self.config_tester.run_common_tests() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def __lowerCamelCase ( self ) -> int: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) @slow def __lowerCamelCase ( self ) -> Tuple: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): __UpperCamelCase = TFDistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @require_tf class UpperCAmelCase__ ( unittest.TestCase): @slow def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) __UpperCamelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) __UpperCamelCase = model(lowercase )[0] __UpperCamelCase = [1, 6, 7_6_8] self.assertEqual(output.shape , lowercase ) __UpperCamelCase = tf.constant( [ [ [0.19_261_885, -0.13_732_955, 0.4_119_799], [0.22_150_156, -0.07_422_661, 0.39_037_204], [0.22_756_018, -0.0_896_414, 0.3_701_467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase , atol=1E-4 )
349
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = StableDiffusionKDiffusionPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) sd_pipe.set_scheduler("""sample_euler""" ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=9.0 , num_inference_steps=2_0 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __UpperCamelCase = np.array([0.0_447, 0.0_492, 0.0_468, 0.0_408, 0.0_383, 0.0_408, 0.0_354, 0.0_380, 0.0_339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) sd_pipe.set_scheduler("""sample_euler""" ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=9.0 , num_inference_steps=2_0 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __UpperCamelCase = np.array([0.1_237, 0.1_320, 0.1_438, 0.1_359, 0.1_390, 0.1_132, 0.1_277, 0.1_175, 0.1_112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def __lowerCamelCase ( self ) -> List[Any]: __UpperCamelCase = StableDiffusionKDiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) sd_pipe.set_scheduler("""sample_dpmpp_2m""" ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=7.5 , num_inference_steps=1_5 , output_type="""np""" , use_karras_sigmas=lowercase , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __UpperCamelCase = np.array( [0.11_381_689, 0.12_112_921, 0.1_389_457, 0.12_549_606, 0.1_244_964, 0.10_831_517, 0.11_562_866, 0.10_867_816, 0.10_499_048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
349
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def _lowercase ( __A ,__A ): '''simple docstring''' return math.sqrt(sum(pow(a - b ,2 ) for a, b in zip(__A ,__A ) ) ) def _lowercase ( __A ,__A ): '''simple docstring''' if dataset.ndim != value_array.ndim: __UpperCamelCase = ( """Wrong input data's dimensions... """ f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(__A ) try: if dataset.shape[1] != value_array.shape[1]: __UpperCamelCase = ( """Wrong input data's shape... """ f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(__A ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("""Wrong shape""" ) if dataset.dtype != value_array.dtype: __UpperCamelCase = ( """Input data have different datatype... """ f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(__A ) __UpperCamelCase = [] for value in value_array: __UpperCamelCase = euclidean(__A ,dataset[0] ) __UpperCamelCase = dataset[0].tolist() for dataset_value in dataset[1:]: __UpperCamelCase = euclidean(__A ,__A ) if dist > temp_dist: __UpperCamelCase = temp_dist __UpperCamelCase = dataset_value.tolist() answer.append([vector, dist] ) return answer def _lowercase ( __A ,__A ): '''simple docstring''' return np.dot(__A ,__A ) / (norm(__A ) * norm(__A )) if __name__ == "__main__": import doctest doctest.testmod()
349
1
'''simple docstring''' def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = len(__A ) __UpperCamelCase = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __UpperCamelCase = True # sum is not zero and set is empty then false for i in range(1 ,required_sum + 1 ): __UpperCamelCase = False for i in range(1 ,arr_len + 1 ): for j in range(1 ,required_sum + 1 ): if arr[i - 1] > j: __UpperCamelCase = subset[i - 1][j] if arr[i - 1] <= j: __UpperCamelCase = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
349
'''simple docstring''' from datetime import datetime import requests def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = """https://downloadgram.net/wp-json/wppress/video-downloader/video?url=""" __UpperCamelCase = requests.get(base_url + url ).json()[0]["""urls"""][0]["""src"""] return requests.get(__A ).content if __name__ == "__main__": a__ : int = input('Enter Video/IGTV url: ').strip() a__ : int = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4''' with open(file_name, 'wb') as fp: fp.write(download_video(url)) print(f'''Done. Video saved to disk as {file_name}.''')
349
1
'''simple docstring''' import requests a__ : Dict = 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=' def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["""articles"""] ,1 ): print(f"{i}.) {article['title']}" ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='<Your BBC News API key goes here>')
349
'''simple docstring''' import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowercase ( __A ,__A=False ): '''simple docstring''' try: __UpperCamelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __UpperCamelCase = default else: # KEY is set, convert it to True or False. try: __UpperCamelCase = strtobool(__A ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no." ) return _value a__ : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) a__ : Union[str, Any] = parse_flag_from_env('RUN_REMOTE', default=False) a__ : Any = parse_flag_from_env('RUN_LOCAL', default=True) a__ : List[Any] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a__ : Optional[int] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a__ : Optional[int] = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a__ : Optional[Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a__ : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a__ : str = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a__ : str = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a__ : Tuple = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowercase ( __A ): '''simple docstring''' try: import faiss # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires faiss""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import regex # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires regex""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import elasticsearch # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires elasticsearch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import sqlalchemy # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires sqlalchemy""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TORCH_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires PyTorch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TF_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires TensorFlow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.JAX_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires JAX""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.PIL_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires Pillow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import transformers # noqa F401 except ImportError: return unittest.skip("""test requires transformers""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import tiktoken # noqa F401 except ImportError: return unittest.skip("""test requires tiktoken""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import spacy # noqa F401 except ImportError: return unittest.skip("""test requires spacy""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' def _require_spacy_model(__A ): try: import spacy # noqa F401 spacy.load(__A ) except ImportError: return unittest.skip("""test requires spacy""" )(__A ) except OSError: return unittest.skip("""test requires spacy model '{}'""".format(__A ) )(__A ) else: return test_case return _require_spacy_model def _lowercase ( __A ): '''simple docstring''' try: import pyspark # noqa F401 except ImportError: return unittest.skip("""test requires pyspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import joblibspark # noqa F401 except ImportError: return unittest.skip("""test requires joblibspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_slow_tests or _run_slow_tests == 0: __UpperCamelCase = unittest.skip("""test is slow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_local_tests or _run_local_tests == 0: __UpperCamelCase = unittest.skip("""test is local""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_packaged_tests or _run_packaged_tests == 0: __UpperCamelCase = unittest.skip("""test is packaged""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_remote_tests or _run_remote_tests == 0: __UpperCamelCase = unittest.skip("""test requires remote""" )(__A ) return test_case def _lowercase ( *__A ): '''simple docstring''' def decorate(cls ): for name, fn in cls.__dict__.items(): if callable(__A ) and name.startswith("""test""" ): for decorator in decorators: __UpperCamelCase = decorator(__A ) setattr(cls ,__A ,__A ) return cls return decorate class UpperCAmelCase__ ( UpperCAmelCase_): pass class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 @contextmanager def _lowercase ( __A=OfflineSimulationMode.CONNECTION_FAILS ,__A=1E-16 ): '''simple docstring''' __UpperCamelCase = requests.Session().request def timeout_request(__A ,__A ,__A ,**__A ): # Change the url to an invalid url so that the connection hangs __UpperCamelCase = """https://10.255.255.1""" if kwargs.get("""timeout""" ) is None: raise RequestWouldHangIndefinitelyError( f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) __UpperCamelCase = timeout try: return online_request(__A ,__A ,**__A ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __UpperCamelCase = url __UpperCamelCase = e.args[0] __UpperCamelCase = (max_retry_error.args[0].replace("""10.255.255.1""" ,f"OfflineMock[{url}]" ),) __UpperCamelCase = (max_retry_error,) raise def raise_connection_error(__A ,__A ,**__A ): raise requests.ConnectionError("""Offline mode is enabled.""" ,request=__A ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("""requests.Session.send""" ,__A ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("""requests.Session.request""" ,__A ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,__A ): yield else: raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" ) @contextmanager def _lowercase ( *__A ,**__A ): '''simple docstring''' __UpperCamelCase = str(Path().resolve() ) with tempfile.TemporaryDirectory(*__A ,**__A ) as tmp_dir: try: os.chdir(__A ) yield finally: os.chdir(__A ) @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowercase ( __A ,__A ): '''simple docstring''' return deepcopy(__A ).integers(0 ,100 ,10 ).tolist() == deepcopy(__A ).integers(0 ,100 ,10 ).tolist() def _lowercase ( __A ): '''simple docstring''' import decorator from requests.exceptions import HTTPError def _wrapper(__A ,*__A ,**__A ): try: return func(*__A ,**__A ) except HTTPError as err: if str(__A ).startswith("""500""" ) or str(__A ).startswith("""502""" ): pytest.xfail(str(__A ) ) raise err return decorator.decorator(_wrapper ,__A ) class UpperCAmelCase__ : def __init__( self , lowercase , lowercase , lowercase ) -> str: __UpperCamelCase = returncode __UpperCamelCase = stdout __UpperCamelCase = stderr async def _lowercase ( __A ,__A ): '''simple docstring''' while True: __UpperCamelCase = await stream.readline() if line: callback(__A ) else: break async def _lowercase ( __A ,__A=None ,__A=None ,__A=None ,__A=False ,__A=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(__A ) ) __UpperCamelCase = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=__A ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=__A ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __UpperCamelCase = [] __UpperCamelCase = [] def tee(__A ,__A ,__A ,__A="" ): __UpperCamelCase = line.decode("""utf-8""" ).rstrip() sink.append(__A ) if not quiet: print(__A ,__A ,file=__A ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __A : tee(__A ,__A ,sys.stdout ,label="""stdout:""" ) ), _read_stream(p.stderr ,lambda __A : tee(__A ,__A ,sys.stderr ,label="""stderr:""" ) ), ] ,timeout=__A ,) return _RunOutput(await p.wait() ,__A ,__A ) def _lowercase ( __A ,__A=None ,__A=None ,__A=180 ,__A=False ,__A=True ): '''simple docstring''' __UpperCamelCase = asyncio.get_event_loop() __UpperCamelCase = loop.run_until_complete( _stream_subprocess(__A ,env=__A ,stdin=__A ,timeout=__A ,quiet=__A ,echo=__A ) ) __UpperCamelCase = """ """.join(__A ) if result.returncode > 0: __UpperCamelCase = """\n""".join(result.stderr ) raise RuntimeError( f"'{cmd_str}' failed with returncode {result.returncode}\n\n" f"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f"'{cmd_str}' produced no output." ) return result def _lowercase ( ): '''simple docstring''' __UpperCamelCase = os.environ.get("""PYTEST_XDIST_WORKER""" ,"""gw0""" ) __UpperCamelCase = re.sub(R"""^gw""" ,"""""" ,__A ,0 ,re.M ) return int(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = 29_500 __UpperCamelCase = pytest_xdist_worker_id() return port + uniq_delta
349
1
'''simple docstring''' import asyncio import os import re import sys import tempfile import unittest from contextlib import contextmanager from copy import deepcopy from distutils.util import strtobool from enum import Enum from importlib.util import find_spec from pathlib import Path from unittest.mock import patch import pyarrow as pa import pytest import requests from packaging import version from datasets import config if config.PY_VERSION < version.parse('3.8'): import importlib_metadata else: import importlib.metadata as importlib_metadata def _lowercase ( __A ,__A=False ): '''simple docstring''' try: __UpperCamelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __UpperCamelCase = default else: # KEY is set, convert it to True or False. try: __UpperCamelCase = strtobool(__A ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(f"If set, {key} must be yes or no." ) return _value a__ : Optional[Any] = parse_flag_from_env('RUN_SLOW', default=False) a__ : Union[str, Any] = parse_flag_from_env('RUN_REMOTE', default=False) a__ : Any = parse_flag_from_env('RUN_LOCAL', default=True) a__ : List[Any] = parse_flag_from_env('RUN_PACKAGED', default=True) # Compression a__ : Optional[int] = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4') a__ : Optional[int] = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr') a__ : Optional[Any] = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard') # Audio a__ : List[Any] = pytest.mark.skipif( # On Windows and OS X, soundfile installs sndfile find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'), reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ', ) # Beam a__ : str = pytest.mark.skipif( not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'), reason='test requires apache-beam and a compatible dill version', ) # Dill-cloudpickle compatibility a__ : str = pytest.mark.skipif( config.DILL_VERSION <= version.parse('0.3.2'), reason='test requires dill>0.3.2 for cloudpickle compatibility', ) # Windows a__ : Tuple = pytest.mark.skipif( sys.platform == 'win32', reason='test should not be run on Windows', ) def _lowercase ( __A ): '''simple docstring''' try: import faiss # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires faiss""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import regex # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires regex""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import elasticsearch # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires elasticsearch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import sqlalchemy # noqa except ImportError: __UpperCamelCase = unittest.skip("""test requires sqlalchemy""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TORCH_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires PyTorch""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.TF_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires TensorFlow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.JAX_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires JAX""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not config.PIL_AVAILABLE: __UpperCamelCase = unittest.skip("""test requires Pillow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' try: import transformers # noqa F401 except ImportError: return unittest.skip("""test requires transformers""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import tiktoken # noqa F401 except ImportError: return unittest.skip("""test requires tiktoken""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import spacy # noqa F401 except ImportError: return unittest.skip("""test requires spacy""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' def _require_spacy_model(__A ): try: import spacy # noqa F401 spacy.load(__A ) except ImportError: return unittest.skip("""test requires spacy""" )(__A ) except OSError: return unittest.skip("""test requires spacy model '{}'""".format(__A ) )(__A ) else: return test_case return _require_spacy_model def _lowercase ( __A ): '''simple docstring''' try: import pyspark # noqa F401 except ImportError: return unittest.skip("""test requires pyspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' try: import joblibspark # noqa F401 except ImportError: return unittest.skip("""test requires joblibspark""" )(__A ) else: return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_slow_tests or _run_slow_tests == 0: __UpperCamelCase = unittest.skip("""test is slow""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_local_tests or _run_local_tests == 0: __UpperCamelCase = unittest.skip("""test is local""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_packaged_tests or _run_packaged_tests == 0: __UpperCamelCase = unittest.skip("""test is packaged""" )(__A ) return test_case def _lowercase ( __A ): '''simple docstring''' if not _run_remote_tests or _run_remote_tests == 0: __UpperCamelCase = unittest.skip("""test requires remote""" )(__A ) return test_case def _lowercase ( *__A ): '''simple docstring''' def decorate(cls ): for name, fn in cls.__dict__.items(): if callable(__A ) and name.startswith("""test""" ): for decorator in decorators: __UpperCamelCase = decorator(__A ) setattr(cls ,__A ,__A ) return cls return decorate class UpperCAmelCase__ ( UpperCAmelCase_): pass class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 2 @contextmanager def _lowercase ( __A=OfflineSimulationMode.CONNECTION_FAILS ,__A=1E-16 ): '''simple docstring''' __UpperCamelCase = requests.Session().request def timeout_request(__A ,__A ,__A ,**__A ): # Change the url to an invalid url so that the connection hangs __UpperCamelCase = """https://10.255.255.1""" if kwargs.get("""timeout""" ) is None: raise RequestWouldHangIndefinitelyError( f"Tried a call to {url} in offline mode with no timeout set. Please set a timeout." ) __UpperCamelCase = timeout try: return online_request(__A ,__A ,**__A ) except Exception as e: # The following changes in the error are just here to make the offline timeout error prettier __UpperCamelCase = url __UpperCamelCase = e.args[0] __UpperCamelCase = (max_retry_error.args[0].replace("""10.255.255.1""" ,f"OfflineMock[{url}]" ),) __UpperCamelCase = (max_retry_error,) raise def raise_connection_error(__A ,__A ,**__A ): raise requests.ConnectionError("""Offline mode is enabled.""" ,request=__A ) if mode is OfflineSimulationMode.CONNECTION_FAILS: with patch("""requests.Session.send""" ,__A ): yield elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT: # inspired from https://stackoverflow.com/a/904609 with patch("""requests.Session.request""" ,__A ): yield elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1: with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,__A ): yield else: raise ValueError("""Please use a value from the OfflineSimulationMode enum.""" ) @contextmanager def _lowercase ( *__A ,**__A ): '''simple docstring''' __UpperCamelCase = str(Path().resolve() ) with tempfile.TemporaryDirectory(*__A ,**__A ) as tmp_dir: try: os.chdir(__A ) yield finally: os.chdir(__A ) @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase." @contextmanager def _lowercase ( ): '''simple docstring''' import gc gc.collect() __UpperCamelCase = pa.total_allocated_bytes() yield assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase." def _lowercase ( __A ,__A ): '''simple docstring''' return deepcopy(__A ).integers(0 ,100 ,10 ).tolist() == deepcopy(__A ).integers(0 ,100 ,10 ).tolist() def _lowercase ( __A ): '''simple docstring''' import decorator from requests.exceptions import HTTPError def _wrapper(__A ,*__A ,**__A ): try: return func(*__A ,**__A ) except HTTPError as err: if str(__A ).startswith("""500""" ) or str(__A ).startswith("""502""" ): pytest.xfail(str(__A ) ) raise err return decorator.decorator(_wrapper ,__A ) class UpperCAmelCase__ : def __init__( self , lowercase , lowercase , lowercase ) -> str: __UpperCamelCase = returncode __UpperCamelCase = stdout __UpperCamelCase = stderr async def _lowercase ( __A ,__A ): '''simple docstring''' while True: __UpperCamelCase = await stream.readline() if line: callback(__A ) else: break async def _lowercase ( __A ,__A=None ,__A=None ,__A=None ,__A=False ,__A=False ): '''simple docstring''' if echo: print("""\nRunning: """ ,""" """.join(__A ) ) __UpperCamelCase = await asyncio.create_subprocess_exec( cmd[0] ,*cmd[1:] ,stdin=__A ,stdout=asyncio.subprocess.PIPE ,stderr=asyncio.subprocess.PIPE ,env=__A ,) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __UpperCamelCase = [] __UpperCamelCase = [] def tee(__A ,__A ,__A ,__A="" ): __UpperCamelCase = line.decode("""utf-8""" ).rstrip() sink.append(__A ) if not quiet: print(__A ,__A ,file=__A ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ _read_stream(p.stdout ,lambda __A : tee(__A ,__A ,sys.stdout ,label="""stdout:""" ) ), _read_stream(p.stderr ,lambda __A : tee(__A ,__A ,sys.stderr ,label="""stderr:""" ) ), ] ,timeout=__A ,) return _RunOutput(await p.wait() ,__A ,__A ) def _lowercase ( __A ,__A=None ,__A=None ,__A=180 ,__A=False ,__A=True ): '''simple docstring''' __UpperCamelCase = asyncio.get_event_loop() __UpperCamelCase = loop.run_until_complete( _stream_subprocess(__A ,env=__A ,stdin=__A ,timeout=__A ,quiet=__A ,echo=__A ) ) __UpperCamelCase = """ """.join(__A ) if result.returncode > 0: __UpperCamelCase = """\n""".join(result.stderr ) raise RuntimeError( f"'{cmd_str}' failed with returncode {result.returncode}\n\n" f"The combined stderr from workers follows:\n{stderr}" ) # check that the subprocess actually did run and produced some output, should the test rely on # the remote side to do the testing if not result.stdout and not result.stderr: raise RuntimeError(f"'{cmd_str}' produced no output." ) return result def _lowercase ( ): '''simple docstring''' __UpperCamelCase = os.environ.get("""PYTEST_XDIST_WORKER""" ,"""gw0""" ) __UpperCamelCase = re.sub(R"""^gw""" ,"""""" ,__A ,0 ,re.M ) return int(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = 29_500 __UpperCamelCase = pytest_xdist_worker_id() return port + uniq_delta
349
'''simple docstring''' import re def _lowercase ( __A ): '''simple docstring''' return [char.split() for char in re.split(R"""[^ a-z A-Z 0-9 \s]""" ,str_ )] def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = split_input(str_ ) return "".join( ["""""".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _lowercase ( __A ,__A ,__A ): '''simple docstring''' try: __UpperCamelCase = split_input(__A ) if upper: __UpperCamelCase = """""".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __UpperCamelCase = """""".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _lowercase ( __A ): '''simple docstring''' return to_simple_case(__A ) def _lowercase ( __A ): '''simple docstring''' try: __UpperCamelCase = to_simple_case(__A ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""_""" ) def _lowercase ( __A ,__A ): '''simple docstring''' return to_complex_case(__A ,__A ,"""-""" ) if __name__ == "__main__": __import__('doctest').testmod()
349
1
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = 0 def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32""" ) self.assertIsInstance(lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[Any]: with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = Path(lowercase ) / """preprocessor_config.json""" __UpperCamelCase = Path(lowercase ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(lowercase , """w""" ) ) __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase ) self.assertIsInstance(lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[str]: # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = Path(lowercase ) / """preprocessor_config.json""" __UpperCamelCase = Path(lowercase ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(lowercase , """w""" ) ) __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase ) self.assertIsInstance(lowercase , lowercase ) def __lowerCamelCase ( self ) -> List[Any]: with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = CLIPConfig() # Create a dummy config file with image_proceesor_type __UpperCamelCase = Path(lowercase ) / """preprocessor_config.json""" __UpperCamelCase = Path(lowercase ) / """config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(lowercase , """w""" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase ).to_dict() config_dict.pop("""image_processor_type""" ) __UpperCamelCase = CLIPImageProcessor(**lowercase ) # save in new folder model_config.save_pretrained(lowercase ) config.save_pretrained(lowercase ) __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase ) # make sure private variable is not incorrectly saved __UpperCamelCase = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(lowercase , lowercase ) def __lowerCamelCase ( self ) -> int: with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = Path(lowercase ) / """preprocessor_config.json""" json.dump( {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""} , open(lowercase , """w""" ) , ) __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase ) self.assertIsInstance(lowercase , lowercase ) def __lowerCamelCase ( self ) -> Union[str, Any]: with self.assertRaisesRegex( lowercase , """clip-base is not a local folder and is not a valid model identifier""" ): __UpperCamelCase = AutoImageProcessor.from_pretrained("""clip-base""" ) def __lowerCamelCase ( self ) -> Union[str, Any]: with self.assertRaisesRegex( lowercase , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase , revision="""aaaaaa""" ) def __lowerCamelCase ( self ) -> Tuple: with self.assertRaisesRegex( lowercase , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): __UpperCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model""" ) def __lowerCamelCase ( self ) -> Union[str, Any]: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(lowercase ): __UpperCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowercase ): __UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=lowercase ) __UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=lowercase ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(lowercase ) __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase , trust_remote_code=lowercase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , """NewImageProcessor""" ) def __lowerCamelCase ( self ) -> Any: try: AutoConfig.register("""custom""" , lowercase ) AutoImageProcessor.register(lowercase , lowercase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowercase ): AutoImageProcessor.register(lowercase , lowercase ) with tempfile.TemporaryDirectory() as tmpdirname: __UpperCamelCase = Path(lowercase ) / """preprocessor_config.json""" __UpperCamelCase = Path(lowercase ) / """config.json""" json.dump( {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""} , open(lowercase , """w""" ) , ) json.dump({"""model_type""": """clip"""} , open(lowercase , """w""" ) ) __UpperCamelCase = CustomImageProcessor.from_pretrained(lowercase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(lowercase ) __UpperCamelCase = AutoImageProcessor.from_pretrained(lowercase ) self.assertIsInstance(lowercase , lowercase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCamelCase ( self ) -> List[str]: class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = True try: AutoConfig.register("""custom""" , lowercase ) AutoImageProcessor.register(lowercase , lowercase ) # If remote code is not set, the default is to use local __UpperCamelCase = AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor""" ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=lowercase ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __UpperCamelCase = AutoImageProcessor.from_pretrained( """hf-internal-testing/test_dynamic_image_processor""" , trust_remote_code=lowercase ) self.assertEqual(image_processor.__class__.__name__ , """NewImageProcessor""" ) self.assertTrue(not hasattr(lowercase , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
349
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __lowerCamelCase ( self ) -> int: __UpperCamelCase = 1 __UpperCamelCase = 3 __UpperCamelCase = (3_2, 3_2) __UpperCamelCase = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowercase ) return image @property def __lowerCamelCase ( self ) -> Dict: torch.manual_seed(0 ) __UpperCamelCase = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) return model @property def __lowerCamelCase ( self ) -> List[str]: torch.manual_seed(0 ) __UpperCamelCase = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) return model @property def __lowerCamelCase ( self ) -> Optional[int]: torch.manual_seed(0 ) __UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(lowercase ) @property def __lowerCamelCase ( self ) -> Tuple: def extract(*lowercase , **lowercase ): class UpperCAmelCase__ : def __init__( self ) -> Tuple: __UpperCamelCase = torch.ones([0] ) def __lowerCamelCase ( self , lowercase ) -> List[str]: self.pixel_values.to(lowercase ) return self return Out() return extract def __lowerCamelCase ( self ) -> Any: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Tuple: __UpperCamelCase = """cpu""" # ensure determinism for the device-dependent torch.Generator __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe([prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" ) __UpperCamelCase = output.images __UpperCamelCase = torch.Generator(device=lowercase ).manual_seed(0 ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="""np""" , return_dict=lowercase , )[0] __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __UpperCamelCase = np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Union[str, Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained( """hf-internal-testing/tiny-stable-diffusion-lms-pipe""" , safety_checker=lowercase ) assert isinstance(lowercase , lowercase ) assert isinstance(pipe.scheduler , lowercase ) assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowercase ) __UpperCamelCase = StableDiffusionPipeline.from_pretrained(lowercase ) # sanity check that the pipeline still works assert pipe.safety_checker is None __UpperCamelCase = pipe("""example prompt""" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __lowerCamelCase ( self ) -> Optional[int]: __UpperCamelCase = self.dummy_cond_unet __UpperCamelCase = PNDMScheduler(skip_prk_steps=lowercase ) __UpperCamelCase = self.dummy_vae __UpperCamelCase = self.dummy_text_encoder __UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) # put models in fp16 __UpperCamelCase = unet.half() __UpperCamelCase = vae.half() __UpperCamelCase = bert.half() # make sure here that pndm scheduler skips prk __UpperCamelCase = StableDiffusionPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """A painting of a squirrel eating a burger""" __UpperCamelCase = sd_pipe([prompt] , num_inference_steps=2 , output_type="""np""" ).images assert image.shape == (1, 6_4, 6_4, 3) @nightly @require_torch_gpu class UpperCAmelCase__ ( unittest.TestCase): def __lowerCamelCase ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self ) -> Dict: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle""" """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with""" """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and""" """ children from bahnhof zoo, detailed """ ) __UpperCamelCase = 4_0_0_3_6_6_0_3_4_6 __UpperCamelCase = 7 # without safety guidance (sld_guidance_scale = 0) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" , safety_checker=lowercase ) __UpperCamelCase = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = """padme amidala taking a bath artwork, safe for work, no nudity""" __UpperCamelCase = 2_7_3_4_9_7_1_7_5_5 __UpperCamelCase = 7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = [0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443] assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self ) -> Optional[Any]: __UpperCamelCase = StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5""" ) __UpperCamelCase = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) __UpperCamelCase = ( """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.""" """ leyendecker""" ) __UpperCamelCase = 1_0_4_4_3_5_5_2_3_4 __UpperCamelCase = 1_2 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=0 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 __UpperCamelCase = torch.manual_seed(lowercase ) __UpperCamelCase = sd_pipe( [prompt] , generator=lowercase , guidance_scale=lowercase , num_inference_steps=5_0 , output_type="""np""" , width=5_1_2 , height=5_1_2 , sld_guidance_scale=2_0_0_0 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) __UpperCamelCase = output.images __UpperCamelCase = image[0, -3:, -3:, -1] __UpperCamelCase = np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561] ) assert image.shape == (1, 5_1_2, 5_1_2, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
349
1
'''simple docstring''' # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys a__ : Optional[int] = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') a__ : str = subprocess.check_output(f'''git diff --name-only {fork_point_sha}'''.split()).decode('utf-8').split() a__ : List[str] = '|'.join(sys.argv[1:]) a__ : List[str] = re.compile(Rf'''^({joined_dirs}).*?\.py$''') a__ : int = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
349
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> str: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> int: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> List[Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Dict: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> str: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> int: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) class UpperCAmelCase__ ( metaclass=UpperCAmelCase_): __SCREAMING_SNAKE_CASE = ['''flax'''] def __init__( self , *lowercase , **lowercase ) -> Any: requires_backends(self , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def __lowerCamelCase ( cls , *lowercase , **lowercase ) -> List[str]: requires_backends(cls , ["""flax"""] )
349
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[Any] = {'vocab_file': 'sentencepiece.model'} a__ : Tuple = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } a__ : List[str] = { 'google/rembert': 2_5_6, } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , lowercase , lowercase=False , lowercase=True , lowercase=True , lowercase="[CLS]" , lowercase="[SEP]" , lowercase="[UNK]" , lowercase="[SEP]" , lowercase="[PAD]" , lowercase="[CLS]" , lowercase="[MASK]" , **lowercase , ) -> Optional[Any]: super().__init__( do_lower_case=lowercase , remove_space=lowercase , keep_accents=lowercase , bos_token=lowercase , eos_token=lowercase , unk_token=lowercase , sep_token=lowercase , pad_token=lowercase , cls_token=lowercase , mask_token=lowercase , **lowercase , ) __UpperCamelCase = do_lower_case __UpperCamelCase = remove_space __UpperCamelCase = keep_accents __UpperCamelCase = vocab_file __UpperCamelCase = spm.SentencePieceProcessor() self.sp_model.Load(lowercase ) @property def __lowerCamelCase ( self ) -> int: return len(self.sp_model ) def __lowerCamelCase ( self ) -> List[str]: __UpperCamelCase = {self.convert_ids_to_tokens(lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: __UpperCamelCase = self.__dict__.copy() __UpperCamelCase = None return state def __setstate__( self , lowercase ) -> Union[str, Any]: __UpperCamelCase = d __UpperCamelCase = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def __lowerCamelCase ( self , lowercase , lowercase=False ) -> List[Any]: __UpperCamelCase = self.sp_model.EncodeAsPieces(lowercase ) return pieces def __lowerCamelCase ( self , lowercase ) -> Optional[int]: return self.sp_model.PieceToId(lowercase ) def __lowerCamelCase ( self , lowercase ) -> int: return self.sp_model.IdToPiece(lowercase ) def __lowerCamelCase ( self , lowercase ) -> Union[str, Any]: __UpperCamelCase = self.sp_model.decode_pieces(lowercase ) return out_string def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __UpperCamelCase = [self.sep_token_id] __UpperCamelCase = [self.cls_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 __lowerCamelCase ( self , lowercase , lowercase = None , lowercase = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( """You should not supply a second sequence if the provided sequence of """ """ids is already formatted with special tokens for the model.""" ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(lowercase )) + [1] + ([0] * len(lowercase )) + [1] return [1] + ([0] * len(lowercase )) + [1] def __lowerCamelCase ( self , lowercase , lowercase = None ) -> List[int]: __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 __lowerCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: if not os.path.isdir(lowercase ): logger.error("""Vocabulary path ({}) should be a directory""".format(lowercase ) ) return __UpperCamelCase = os.path.join( lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase ): copyfile(self.vocab_file , lowercase ) return (out_vocab_file,)
349
'''simple docstring''' import logging import os from .state import PartialState class UpperCAmelCase__ ( logging.LoggerAdapter): @staticmethod def __lowerCamelCase ( lowercase ) -> Dict: __UpperCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __lowerCamelCase ( self , lowercase , lowercase , *lowercase , **lowercase ) -> List[str]: if PartialState._shared_state == {}: raise RuntimeError( """You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.""" ) __UpperCamelCase = kwargs.pop("""main_process_only""" , lowercase ) __UpperCamelCase = kwargs.pop("""in_order""" , lowercase ) if self.isEnabledFor(lowercase ): if self._should_log(lowercase ): __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) elif in_order: __UpperCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __UpperCamelCase , __UpperCamelCase = self.process(lowercase , lowercase ) self.logger.log(lowercase , lowercase , *lowercase , **lowercase ) state.wait_for_everyone() def _lowercase ( __A ,__A = None ): '''simple docstring''' if log_level is None: __UpperCamelCase = os.environ.get("""ACCELERATE_LOG_LEVEL""" ,__A ) __UpperCamelCase = logging.getLogger(__A ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__A ,{} )
349
1
'''simple docstring''' 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 a__ : Any = logging.get_logger(__name__) a__ : Tuple = { 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = '''yolos''' def __init__( self , lowercase=7_6_8 , lowercase=1_2 , lowercase=1_2 , lowercase=3_0_7_2 , lowercase="gelu" , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=1E-12 , lowercase=[5_1_2, 8_6_4] , lowercase=1_6 , lowercase=3 , lowercase=True , lowercase=1_0_0 , lowercase=True , lowercase=False , lowercase=1 , lowercase=5 , lowercase=2 , lowercase=5 , lowercase=2 , lowercase=0.1 , **lowercase , ) -> Union[str, Any]: super().__init__(**lowercase ) __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 = initializer_range __UpperCamelCase = layer_norm_eps __UpperCamelCase = image_size __UpperCamelCase = patch_size __UpperCamelCase = num_channels __UpperCamelCase = qkv_bias __UpperCamelCase = num_detection_tokens __UpperCamelCase = use_mid_position_embeddings __UpperCamelCase = auxiliary_loss # Hungarian matcher __UpperCamelCase = class_cost __UpperCamelCase = bbox_cost __UpperCamelCase = giou_cost # Loss coefficients __UpperCamelCase = bbox_loss_coefficient __UpperCamelCase = giou_loss_coefficient __UpperCamelCase = eos_coefficient class UpperCAmelCase__ ( UpperCAmelCase_): __SCREAMING_SNAKE_CASE = version.parse('''1.11''') @property def __lowerCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __lowerCamelCase ( self ) -> float: return 1E-4 @property def __lowerCamelCase ( self ) -> int: return 1_2
349
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a__ : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase__ : def __init__( self ) -> Any: __UpperCamelCase = False def __lowerCamelCase ( self , lowercase , lowercase , lowercase , lowercase ) -> str: if not self.initialized: __UpperCamelCase = RagRetriever( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = True def __lowerCamelCase ( self ) -> Optional[Any]: self.retriever.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.retriever._main_retrieve(lowercase , lowercase ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase__ ( UpperCAmelCase_): def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase=None ) -> List[Any]: if index is not None and index.is_initialized() and len(lowercase ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you'll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , index=lowercase , init_retrieval=lowercase , ) __UpperCamelCase = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(lowercase , lowercase , lowercase , lowercase ) for worker in self.retrieval_workers ] ) def __lowerCamelCase ( self ) -> Dict: logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCamelCase ( self , lowercase , lowercase ) -> List[str]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCamelCase = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCamelCase , __UpperCamelCase = ray.get(random_worker.retrieve.remote(lowercase , lowercase ) ) else: __UpperCamelCase , __UpperCamelCase = self._main_retrieve(lowercase , lowercase ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase=None , **lowercase ) -> Any: return super(lowercase , cls ).get_tokenizers(lowercase , lowercase , **lowercase ) @classmethod def __lowerCamelCase ( cls , lowercase , lowercase , lowercase=None , **lowercase ) -> int: __UpperCamelCase = kwargs.pop("""config""" , lowercase ) or RagConfig.from_pretrained(lowercase , **lowercase ) __UpperCamelCase = RagTokenizer.from_pretrained(lowercase , config=lowercase ) __UpperCamelCase = rag_tokenizer.question_encoder __UpperCamelCase = rag_tokenizer.generator if indexed_dataset is not None: __UpperCamelCase = """custom""" __UpperCamelCase = CustomHFIndex(config.retrieval_vector_size , lowercase ) else: __UpperCamelCase = cls._build_index(lowercase ) return cls( lowercase , question_encoder_tokenizer=lowercase , generator_tokenizer=lowercase , retrieval_workers=lowercase , index=lowercase , )
349
1