Any:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[str] = None\n\t\t\t\t\t\t\tif \"feature_extractor\" in kwargs:\n\t\t\t\t\t\t\t\t\t\t\twarnings.warn(\n\t\t\t\t\t\t\t\t\t\t\t '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''\n\t\t\t\t\t\t\t\t\t\t\t ''' instead.''' ,\t\t\t\t\t\t\t__magic_name__ ,\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = kwargs.pop('''feature_extractor''' )\n\n\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[Any] = image_processor if image_processor is not None else feature_extractor\n\t\t\t\t\t\t\tif image_processor is None:\n\t\t\t\t\t\t\t\t\t\t\traise ValueError('''You need to specify an `image_processor`.''' )\n\t\t\t\t\t\t\tif tokenizer is None:\n\t\t\t\t\t\t\t\t\t\t\traise ValueError('''You need to specify a `tokenizer`.''' )\n\n\t\t\t\t\t\t\tsuper().__init__(__magic_name__ ,\t\t\t\t\t\t\t__magic_name__ )\n\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[Any] = self.image_processor\n\n\n\n\n\n\n\t\t\tdef __call__(self ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = True ,\t\t\t\t\t\t\t__magic_name__ = False ,\t\t\t\t\t\t\t__magic_name__ = False ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = 0 ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t__magic_name__ = False ,\t\t\t\t\t\t\t__magic_name__ = False ,\t\t\t\t\t\t\t__magic_name__ = False ,\t\t\t\t\t\t\t__magic_name__ = False ,\t\t\t\t\t\t\t__magic_name__ = True ,\t\t\t\t\t\t\t__magic_name__ = None ,\t\t\t\t\t\t\t**__magic_name__ ,\t\t\t\t\t\t\t)\t\t\t\t\t-> str:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\tif text is None and images is None:\n\t\t\t\t\t\t\t\t\t\t\traise ValueError('''You have to specify either text or images. Both cannot be none.''' )\n\n\t\t\t\t\t\t\tif text is not None:\n\t\t\t\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = self.tokenizer(\n\t\t\t\t\t\t\t\t\t\t\t text=__magic_name__ ,\t\t\t\t\t\t\tadd_special_tokens=__magic_name__ ,\t\t\t\t\t\t\tpadding=__magic_name__ ,\t\t\t\t\t\t\ttruncation=__magic_name__ ,\t\t\t\t\t\t\tmax_length=__magic_name__ ,\t\t\t\t\t\t\tstride=__magic_name__ ,\t\t\t\t\t\t\tpad_to_multiple_of=__magic_name__ ,\t\t\t\t\t\t\treturn_token_type_ids=__magic_name__ ,\t\t\t\t\t\t\treturn_attention_mask=__magic_name__ ,\t\t\t\t\t\t\treturn_overflowing_tokens=__magic_name__ ,\t\t\t\t\t\t\treturn_special_tokens_mask=__magic_name__ ,\t\t\t\t\t\t\treturn_offsets_mapping=__magic_name__ ,\t\t\t\t\t\t\treturn_length=__magic_name__ ,\t\t\t\t\t\t\tverbose=__magic_name__ ,\t\t\t\t\t\t\treturn_tensors=__magic_name__ ,\t\t\t\t\t\t\t**__magic_name__ ,\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif images is not None:\n\t\t\t\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = self.image_processor(\n\t\t\t\t\t\t\t\t\t\t\t __magic_name__ ,\t\t\t\t\t\t\treturn_image_mask=__magic_name__ ,\t\t\t\t\t\t\treturn_codebook_pixels=__magic_name__ ,\t\t\t\t\t\t\treturn_tensors=__magic_name__ ,\t\t\t\t\t\t\t**__magic_name__ ,\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\tif text is not None and images is not None:\n\t\t\t\t\t\t\t\t\t\t\tencoding.update(__magic_name__ )\n\t\t\t\t\t\t\t\t\t\t\treturn encoding\n\t\t\t\t\t\t\telif text is not None:\n\t\t\t\t\t\t\t\t\t\t\treturn encoding\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\treturn BatchEncoding(data=dict(**__magic_name__ ) ,\t\t\t\t\t\t\ttensor_type=__magic_name__ )\n\n\n\n\n\n\n\t\t\tdef lowerCamelCase (self ,\t\t\t\t\t\t\t*__magic_name__ ,\t\t\t\t\t\t\t**__magic_name__ )\t\t\t\t\t-> List[Any]:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\treturn self.tokenizer.batch_decode(*__magic_name__ ,\t\t\t\t\t\t\t**__magic_name__ )\n\n\n\n\n\n\n\t\t\tdef lowerCamelCase (self ,\t\t\t\t\t\t\t*__magic_name__ ,\t\t\t\t\t\t\t**__magic_name__ )\t\t\t\t\t-> int:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\treturn self.tokenizer.decode(*__magic_name__ ,\t\t\t\t\t\t\t**__magic_name__ )\n\n\n\n\n\n\n\t\t\t@property\n\t\t\tdef lowerCamelCase (self )\t\t\t\t\t-> Any:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = self.tokenizer.model_input_names\n\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = self.image_processor.model_input_names\n\t\t\t\t\t\t\treturn list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )\n\n\n\n\n\n\n\t\t\t@property\n\t\t\tdef lowerCamelCase (self )\t\t\t\t\t-> Dict:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\twarnings.warn(\n\t\t\t\t\t\t\t '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' ,\t\t\t\t\t\t\t__magic_name__ ,\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn self.image_processor_class\n\n\n\n\n\n\n\t\t\t@property\n\t\t\tdef lowerCamelCase (self )\t\t\t\t\t-> Dict:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\twarnings.warn(\n\t\t\t\t\t\t\t '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' ,\t\t\t\t\t\t\t__magic_name__ ,\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn self.image_processor\n"},"code_codestyle":{"kind":"number","value":353,"string":"353"},"style_context":{"kind":"string","value":"\n\n\n\n\n\nimport argparse\nimport logging\nimport os\nfrom datetime import datetime\n\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.utils.data import DataLoader, RandomSampler, TensorDataset\nfrom tqdm import tqdm\n\nfrom transformers import GPTaLMHeadModel\n\n\nlowerCAmelCase_ = logging.getLogger(__name__)\n\n\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t( _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\t\t->\t\t\t\t\t\tint:\n\n\n\n\n\n\n\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\tif os.path.exists(_UpperCamelCase\t\t\t):\n\t\t\t\t\t\t\t\tif os.path.exists(os.path.join(_UpperCamelCase\t\t\t, '''config.json'''\t\t\t)\t\t\t) and os.path.isfile(\n\t\t\t\t\t\t\t\t os.path.join(_UpperCamelCase\t\t\t, '''config.json'''\t\t\t)\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\tos.remove(os.path.join(_UpperCamelCase\t\t\t, '''config.json'''\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\tif os.path.exists(os.path.join(_UpperCamelCase\t\t\t, '''pytorch_model.bin'''\t\t\t)\t\t\t) and os.path.isfile(\n\t\t\t\t\t\t\t\t os.path.join(_UpperCamelCase\t\t\t, '''pytorch_model.bin'''\t\t\t)\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\tos.remove(os.path.join(_UpperCamelCase\t\t\t, '''pytorch_model.bin'''\t\t\t)\t\t\t)\n\t\t\t\telse:\n\t\t\t\t\t\t\t\tos.makedirs(_UpperCamelCase\t\t\t)\n\t\t\t\tmodel.save_pretrained(_UpperCamelCase\t\t\t)\n\n\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t( _UpperCamelCase\t\t\t, _UpperCamelCase=False\t\t\t)\t\t->\t\t\t\t\t\tOptional[int]:\n\n\n\n\n\n\n\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: List[Any] = 2\n\t\t\t\tif unlogit:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = torch.pow(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[Any] = p * torch.log(_UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = 0\n\t\t\t\treturn -plogp.sum(dim=-1\t\t\t)\n\n\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t( _UpperCamelCase\t\t\t)\t\t->\t\t\t\t\t\tint:\n\n\n\n\n\n\n\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\tlogger.info('''lv, h >\\t''' + '''\\t'''.join(f'''{x + 1}''' for x in range(len(_UpperCamelCase\t\t\t)\t\t\t)\t\t\t)\t\t\t)\n\t\t\t\tfor row in range(len(_UpperCamelCase\t\t\t)\t\t\t):\n\t\t\t\t\t\t\t\tif tensor.dtype != torch.long:\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(f'''layer {row + 1}:\\t''' + '''\\t'''.join(f'''{x:.5f}''' for x in tensor[row].cpu().data\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(f'''layer {row + 1}:\\t''' + '''\\t'''.join(f'''{x:d}''' for x in tensor[row].cpu().data\t\t\t)\t\t\t)\n\n\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t( _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase=True\t\t\t, _UpperCamelCase=True\t\t\t, _UpperCamelCase=None\t\t\t, _UpperCamelCase=False\t\t\t)\t\t->\t\t\t\t\t\tUnion[str, Any]:\n\n\n\n\n\n\n\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: int = model.config.num_hidden_layers, model.config.num_attention_heads\n\t\t\t\tsnake_case_\t\t\t\t\t\t: int = torch.zeros(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t).to(args.device\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[int] = torch.zeros(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t).to(args.device\t\t\t)\n\n\t\t\t\tif head_mask is None:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = torch.ones(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t).to(args.device\t\t\t)\n\n\t\t\t\thead_mask.requires_grad_(requires_grad=_UpperCamelCase\t\t\t)\n\t\t\t\t# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch\n\t\t\t\tif actually_pruned:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = None\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = 0.0\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = 0.0\n\t\t\t\tfor step, inputs in enumerate(tqdm(_UpperCamelCase\t\t\t, desc='''Iteration'''\t\t\t, disable=args.local_rank not in [-1, 0]\t\t\t)\t\t\t):\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = tuple(t.to(args.device\t\t\t) for t in inputs\t\t\t)\n\t\t\t\t\t\t\t\t((snake_case_) ,\t\t\t\t\t\t\t)\t\t\t\t\t\t: Union[str, Any] = inputs\n\n\t\t\t\t\t\t\t\t# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[str] = model(_UpperCamelCase\t\t\t, labels=_UpperCamelCase\t\t\t, head_mask=_UpperCamelCase\t\t\t)\n\t\t\t\t\t\t\t\t# (loss), lm_logits, presents, (all hidden_states), (attentions)\n\t\t\t\t\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: int = (\n\t\t\t\t\t\t\t\t outputs[0],\n\t\t\t\t\t\t\t\t outputs[1],\n\t\t\t\t\t\t\t\t outputs[-1],\n\t\t\t\t\t\t\t\t) # Loss and logits are the first, attention the last\n\t\t\t\t\t\t\t\tloss.backward() # Backpropagate to populate the gradients in the head mask\n\t\t\t\t\t\t\t\ttotal_loss += loss.detach().cpu().numpy()\n\t\t\t\t\t\t\t\tif compute_entropy:\n\t\t\t\t\t\t\t\t\t\t\t\tfor layer, attn in enumerate(_UpperCamelCase\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = entropy(attn.detach()\t\t\t, _UpperCamelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tattn_entropy[layer] += masked_entropy.sum(-1\t\t\t).sum(0\t\t\t).sum(0\t\t\t).detach()\n\n\t\t\t\t\t\t\t\tif compute_importance:\n\t\t\t\t\t\t\t\t\t\t\t\thead_importance += head_mask.grad.abs().detach()\n\t\t\t\t\t\t\t\ttot_tokens += torch.ones_like(_UpperCamelCase\t\t\t).float().detach().sum().data\n\n\t\t\t\t# Normalize\n\t\t\t\tattn_entropy /= tot_tokens\n\t\t\t\thead_importance /= tot_tokens\n\t\t\t\t# Layerwise importance normalization\n\t\t\t\tif not args.dont_normalize_importance_by_layer:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = 2\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = torch.pow(torch.pow(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t).sum(-1\t\t\t)\t\t\t, 1 / exponent\t\t\t)\n\t\t\t\t\t\t\t\thead_importance /= norm_by_layer.unsqueeze(-1\t\t\t) + 1E-20\n\n\t\t\t\tif not args.dont_normalize_global_importance:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())\n\n\t\t\t\t# Print matrices\n\t\t\t\tif compute_entropy:\n\t\t\t\t\t\t\t\tlogger.info('''Attention entropies'''\t\t\t)\n\t\t\t\t\t\t\t\tprint_ad_tensor(_UpperCamelCase\t\t\t)\n\t\t\t\tif compute_importance:\n\t\t\t\t\t\t\t\tlogger.info('''Head importance scores'''\t\t\t)\n\t\t\t\t\t\t\t\tprint_ad_tensor(_UpperCamelCase\t\t\t)\n\t\t\t\tlogger.info('''Head ranked by importance scores'''\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[int] = torch.zeros(head_importance.numel()\t\t\t, dtype=torch.long\t\t\t, device=args.device\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = torch.arange(\n\t\t\t\t head_importance.numel()\t\t\t, device=args.device\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = head_ranks.view_as(_UpperCamelCase\t\t\t)\n\t\t\t\tprint_ad_tensor(_UpperCamelCase\t\t\t)\n\t\t\t\treturn attn_entropy, head_importance, total_loss\n\n\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t( _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\t\t->\t\t\t\t\t\tOptional[int]:\n\n\n\n\n\n\n\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[int] = compute_heads_importance(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, compute_entropy=_UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = 1 / loss # instead of downsteam score use the LM loss\n\t\t\t\tlogger.info('''Pruning: original score: %f, threshold: %f'''\t\t\t, _UpperCamelCase\t\t\t, original_score * args.masking_threshold\t\t\t)\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = torch.ones_like(_UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = max(1\t\t\t, int(new_head_mask.numel() * args.masking_amount\t\t\t)\t\t\t)\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: List[Any] = original_score\n\t\t\t\twhile current_score >= original_score * args.masking_threshold:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[str] = new_head_mask.clone().detach() # save current head mask\n\t\t\t\t\t\t\t\t# heads from least important to most - keep only not-masked heads\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[Any] = float('''Inf'''\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[Any] = head_importance.view(-1\t\t\t).sort()[1]\n\n\t\t\t\t\t\t\t\tif len(_UpperCamelCase\t\t\t) <= num_to_mask:\n\t\t\t\t\t\t\t\t\t\t\t\tprint('''BREAK BY num_to_mask'''\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\t# mask heads\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[int] = current_heads_to_mask[:num_to_mask]\n\t\t\t\t\t\t\t\tlogger.info('''Heads to mask: %s'''\t\t\t, str(current_heads_to_mask.tolist()\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[Any] = new_head_mask.view(-1\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: int = 0.0\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[Any] = new_head_mask.view_as(_UpperCamelCase\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[str] = new_head_mask.clone().detach()\n\t\t\t\t\t\t\t\tprint_ad_tensor(_UpperCamelCase\t\t\t)\n\n\t\t\t\t\t\t\t\t# Compute metric and head importance again\n\t\t\t\t\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: str = compute_heads_importance(\n\t\t\t\t\t\t\t\t _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, compute_entropy=_UpperCamelCase\t\t\t, head_mask=_UpperCamelCase\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = 1 / loss\n\t\t\t\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t\t\t '''Masking: current score: %f, remaining heads %d (%.1f percents)'''\t\t\t, _UpperCamelCase\t\t\t, new_head_mask.sum()\t\t\t, new_head_mask.sum() / new_head_mask.numel() * 100\t\t\t, )\n\n\t\t\t\tlogger.info('''Final head mask'''\t\t\t)\n\t\t\t\tprint_ad_tensor(_UpperCamelCase\t\t\t)\n\t\t\t\tnp.save(os.path.join(args.output_dir\t\t\t, '''head_mask.npy'''\t\t\t)\t\t\t, head_mask.detach().cpu().numpy()\t\t\t)\n\n\t\t\t\treturn head_mask\n\n\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t( _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\t\t->\t\t\t\t\t\tstr:\n\n\n\n\n\n\n\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: str = datetime.now()\n\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[Any] = compute_heads_importance(\n\t\t\t\t _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, compute_entropy=_UpperCamelCase\t\t\t, compute_importance=_UpperCamelCase\t\t\t, head_mask=_UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = 1 / loss\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = datetime.now() - before_time\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: int = sum(p.numel() for p in model.parameters()\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = {\n\t\t\t\t layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_UpperCamelCase\t\t\t)\t\t\t)\n\t\t\t\t}\n\n\t\t\t\tfor k, v in heads_to_prune.items():\n\t\t\t\t\t\t\t\tif isinstance(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = [\n\t\t\t\t\t\t\t\t\t\t\t\t v,\n\t\t\t\t\t\t\t\t\t\t\t\t]\n\n\t\t\t\tassert sum(len(_UpperCamelCase\t\t\t) for h in heads_to_prune.values()\t\t\t) == (1 - head_mask.long()).sum().item()\n\t\t\t\tmodel.prune_heads(_UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = sum(p.numel() for p in model.parameters()\t\t\t)\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = datetime.now()\n\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_ ,\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = compute_heads_importance(\n\t\t\t\t _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, compute_entropy=_UpperCamelCase\t\t\t, compute_importance=_UpperCamelCase\t\t\t, head_mask=_UpperCamelCase\t\t\t, actually_pruned=_UpperCamelCase\t\t\t, )\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = 1 / loss\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Optional[Any] = datetime.now() - before_time\n\n\t\t\t\tlogger.info(\n\t\t\t\t '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'''\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, pruned_num_params / original_num_params * 100\t\t\t, )\n\t\t\t\tlogger.info('''Pruning: score with masking: %f score with pruning: %f'''\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\n\t\t\t\tlogger.info('''Pruning: speed ratio (original timing / new timing): %f percents'''\t\t\t, original_time / new_time * 100\t\t\t)\n\t\t\t\tsave_model(_UpperCamelCase\t\t\t, args.output_dir\t\t\t)\n\n\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t( )\t\t->\t\t\t\t\t\tOptional[int]:\n\n\n\n\n\n\n\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = argparse.ArgumentParser()\n\t\t\t\t# Required parameters\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--data_dir'''\t\t\t, default=_UpperCamelCase\t\t\t, type=_UpperCamelCase\t\t\t, required=_UpperCamelCase\t\t\t, help='''The input data dir. Should contain the .tsv files (or other data files) for the task.'''\t\t\t, )\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--model_name_or_path'''\t\t\t, default=_UpperCamelCase\t\t\t, type=_UpperCamelCase\t\t\t, required=_UpperCamelCase\t\t\t, help='''Path to pretrained model or model identifier from huggingface.co/models'''\t\t\t, )\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--output_dir'''\t\t\t, default=_UpperCamelCase\t\t\t, type=_UpperCamelCase\t\t\t, required=_UpperCamelCase\t\t\t, help='''The output directory where the model predictions and checkpoints will be written.'''\t\t\t, )\n\n\t\t\t\t# Other parameters\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--config_name'''\t\t\t, default=''''''\t\t\t, type=_UpperCamelCase\t\t\t, help='''Pretrained config name or path if not the same as model_name_or_path'''\t\t\t, )\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--tokenizer_name'''\t\t\t, default=''''''\t\t\t, type=_UpperCamelCase\t\t\t, help='''Pretrained tokenizer name or path if not the same as model_name_or_path'''\t\t\t, )\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--cache_dir'''\t\t\t, default=_UpperCamelCase\t\t\t, type=_UpperCamelCase\t\t\t, help='''Where do you want to store the pre-trained models downloaded from s3'''\t\t\t, )\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--data_subset'''\t\t\t, type=_UpperCamelCase\t\t\t, default=-1\t\t\t, help='''If > 0: limit the data to a subset of data_subset instances.'''\t\t\t)\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--overwrite_output_dir'''\t\t\t, action='''store_true'''\t\t\t, help='''Whether to overwrite data in output directory'''\t\t\t)\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--overwrite_cache'''\t\t\t, action='''store_true'''\t\t\t, help='''Overwrite the cached training and evaluation sets'''\t\t\t)\n\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--dont_normalize_importance_by_layer'''\t\t\t, action='''store_true'''\t\t\t, help='''Don\\'t normalize importance score by layers'''\t\t\t)\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--dont_normalize_global_importance'''\t\t\t, action='''store_true'''\t\t\t, help='''Don\\'t normalize all importance scores between 0 and 1'''\t\t\t, )\n\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--try_masking'''\t\t\t, action='''store_true'''\t\t\t, help='''Whether to try to mask head until a threshold of accuracy.'''\t\t\t)\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--masking_threshold'''\t\t\t, default=0.9\t\t\t, type=_UpperCamelCase\t\t\t, help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'''\t\t\t, )\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--masking_amount'''\t\t\t, default=0.1\t\t\t, type=_UpperCamelCase\t\t\t, help='''Amount to heads to masking at each masking step.'''\t\t\t)\n\t\t\t\tparser.add_argument('''--metric_name'''\t\t\t, default='''acc'''\t\t\t, type=_UpperCamelCase\t\t\t, help='''Metric to use for head masking.'''\t\t\t)\n\n\t\t\t\tparser.add_argument(\n\t\t\t\t '''--max_seq_length'''\t\t\t, default=128\t\t\t, type=_UpperCamelCase\t\t\t, help=(\n\t\t\t\t '''The maximum total input sequence length after WordPiece tokenization. \\n'''\n\t\t\t\t '''Sequences longer than this will be truncated, sequences shorter padded.'''\n\t\t\t\t )\t\t\t, )\n\t\t\t\tparser.add_argument('''--batch_size'''\t\t\t, default=1\t\t\t, type=_UpperCamelCase\t\t\t, help='''Batch size.'''\t\t\t)\n\n\t\t\t\tparser.add_argument('''--seed'''\t\t\t, type=_UpperCamelCase\t\t\t, default=42\t\t\t)\n\t\t\t\tparser.add_argument('''--local_rank'''\t\t\t, type=_UpperCamelCase\t\t\t, default=-1\t\t\t, help='''local_rank for distributed training on gpus'''\t\t\t)\n\t\t\t\tparser.add_argument('''--no_cuda'''\t\t\t, action='''store_true'''\t\t\t, help='''Whether not to use CUDA when available'''\t\t\t)\n\t\t\t\tparser.add_argument('''--server_ip'''\t\t\t, type=_UpperCamelCase\t\t\t, default=''''''\t\t\t, help='''Can be used for distant debugging.'''\t\t\t)\n\t\t\t\tparser.add_argument('''--server_port'''\t\t\t, type=_UpperCamelCase\t\t\t, default=''''''\t\t\t, help='''Can be used for distant debugging.'''\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = parser.parse_args()\n\n\t\t\t\tif args.server_ip and args.server_port:\n\t\t\t\t\t\t\t\t# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script\n\t\t\t\t\t\t\t\timport ptvsd\n\n\t\t\t\t\t\t\t\tprint('''Waiting for debugger attach'''\t\t\t)\n\t\t\t\t\t\t\t\tptvsd.enable_attach(address=(args.server_ip, args.server_port)\t\t\t, redirect_output=_UpperCamelCase\t\t\t)\n\t\t\t\t\t\t\t\tptvsd.wait_for_attach()\n\n\t\t\t\t# Setup devices and distributed training\n\t\t\t\tif args.local_rank == -1 or args.no_cuda:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu'''\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Tuple = 0 if args.no_cuda else torch.cuda.device_count()\n\t\t\t\telse:\n\t\t\t\t\t\t\t\ttorch.cuda.set_device(args.local_rank\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[str] = torch.device('''cuda'''\t\t\t, args.local_rank\t\t\t)\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Union[str, Any] = 1\n\t\t\t\t\t\t\t\ttorch.distributed.init_process_group(backend='''nccl'''\t\t\t) # Initializes the distributed backend\n\n\t\t\t\t# Setup logging\n\t\t\t\tlogging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN\t\t\t)\n\t\t\t\tlogger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device\t\t\t, args.n_gpu\t\t\t, bool(args.local_rank != -1\t\t\t)\t\t\t)\t\t\t)\n\n\t\t\t\tsnake_case_\t\t\t\t\t\t: int = GPTaLMHeadModel.from_pretrained(args.model_name_or_path\t\t\t)\n\n\t\t\t\t# Distributed and parallel training\n\t\t\t\tmodel.to(args.device\t\t\t)\n\t\t\t\tif args.local_rank != -1:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = nn.parallel.DistributedDataParallel(\n\t\t\t\t\t\t\t\t _UpperCamelCase\t\t\t, device_ids=[args.local_rank]\t\t\t, output_device=args.local_rank\t\t\t, find_unused_parameters=_UpperCamelCase\t\t\t)\n\t\t\t\telif args.n_gpu > 1:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: Dict = nn.DataParallel(_UpperCamelCase\t\t\t)\n\n\t\t\t\t# Print/save training arguments\n\t\t\t\tos.makedirs(args.output_dir\t\t\t, exist_ok=_UpperCamelCase\t\t\t)\n\t\t\t\ttorch.save(_UpperCamelCase\t\t\t, os.path.join(args.output_dir\t\t\t, '''run_args.bin'''\t\t\t)\t\t\t)\n\t\t\t\tlogger.info('''Training/evaluation parameters %s'''\t\t\t, _UpperCamelCase\t\t\t)\n\n\t\t\t\t# Prepare dataset\n\t\t\t\tsnake_case_\t\t\t\t\t\t: str = np.concatenate(\n\t\t\t\t [\n\t\t\t\t np.loadtxt(args.data_dir\t\t\t, dtype=np.intaa\t\t\t),\n\t\t\t\t ]\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = (torch.from_numpy(_UpperCamelCase\t\t\t),)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: Any = TensorDataset(*_UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: List[str] = RandomSampler(_UpperCamelCase\t\t\t)\n\t\t\t\tsnake_case_\t\t\t\t\t\t: int = DataLoader(_UpperCamelCase\t\t\t, sampler=_UpperCamelCase\t\t\t, batch_size=args.batch_size\t\t\t)\n\n\t\t\t\t# Compute head entropy and importance score\n\t\t\t\tcompute_heads_importance(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\n\n\t\t\t\t# Try head masking (set heads to zero until the score goes under a threshole)\n\t\t\t\t# and head pruning (remove masked heads and see the effect on the network)\n\t\t\t\tif args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:\n\t\t\t\t\t\t\t\tsnake_case_\t\t\t\t\t\t: List[str] = mask_heads(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\n\t\t\t\t\t\t\t\tprune_heads(_UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t, _UpperCamelCase\t\t\t)\n\n\nif __name__ == \"__main__\":\n\tmain()\n"},"style_context_codestyle":{"kind":"number","value":279,"string":"279"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":210,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\nimport argparse\r\n\r\nimport torch\r\nfrom torch import nn\r\n\r\nfrom transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef SCREAMING_SNAKE_CASE_\t\t\t\t\t\t(\t\t\t__A :\t\t\tOptional[Any]\t\t\t\t)\t->\t\tDict:\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n a_\t\t\t\t\t:\t\tDict\t\t\t\t\t\t\t= [\r\n 'encoder.version',\r\n 'decoder.version',\r\n 'model.encoder.version',\r\n 'model.decoder.version',\r\n 'decoder.output_projection.weight',\r\n '_float_tensor',\r\n 'encoder.embed_positions._float_tensor',\r\n 'decoder.embed_positions._float_tensor',\r\n ]\r\n for k in ignore_keys:\r\n state_dict.pop(__A , __A\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef SCREAMING_SNAKE_CASE_\t\t\t\t\t\t(\t\t\t__A :\t\t\tstr\t\t\t\t)\t->\t\tOptional[int]:\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n a_\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t\t\t= list(s_dict.keys()\t\t\t\t)\r\n for key in keys:\r\n if \"transformer_layers\" in key:\r\n a_\t\t\t\t\t:\t\tTuple\t\t\t\t\t\t\t= s_dict.pop(__A\t\t\t\t)\r\n elif \"subsample\" in key:\r\n a_\t\t\t\t\t:\t\tint\t\t\t\t\t\t\t= s_dict.pop(__A\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef SCREAMING_SNAKE_CASE_\t\t\t\t\t\t(\t\t\t__A :\t\t\tOptional[Any]\t\t\t\t)\t->\t\tDict:\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n a_\t\t\t\t\t\t\t,\t\ta_\t\t\t\t\t:\t\tList[Any]\t\t\t\t\t\t\t= emb.weight.shape\r\n a_\t\t\t\t\t:\t\tOptional[Any]\t\t\t\t\t\t\t= nn.Linear(__A , __A , bias=__A\t\t\t\t)\r\n a_\t\t\t\t\t:\t\tList[Any]\t\t\t\t\t\t\t= emb.weight.data\r\n return lin_layer\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef SCREAMING_SNAKE_CASE_\t\t\t\t\t\t(\t\t\t__A :\t\t\tList[Any] , __A :\t\t\tList[str]\t\t\t\t)\t->\t\tList[Any]:\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n a_\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t\t\t= torch.load(__A , map_location='cpu'\t\t\t\t)\r\n a_\t\t\t\t\t:\t\tList[str]\t\t\t\t\t\t\t= mam_aaa['args']\r\n a_\t\t\t\t\t:\t\tUnion[str, Any]\t\t\t\t\t\t\t= mam_aaa['model']\r\n a_\t\t\t\t\t:\t\tOptional[Any]\t\t\t\t\t\t\t= state_dict['decoder.output_projection.weight']\r\n\r\n remove_ignore_keys_(__A\t\t\t\t)\r\n rename_keys(__A\t\t\t\t)\r\n\r\n a_\t\t\t\t\t:\t\tint\t\t\t\t\t\t\t= state_dict['decoder.embed_tokens.weight'].shape[0]\r\n\r\n a_\t\t\t\t\t:\t\tDict\t\t\t\t\t\t\t= args.share_decoder_input_output_embed\r\n\r\n a_\t\t\t\t\t:\t\tTuple\t\t\t\t\t\t\t= [int(__A\t\t\t\t) for i in args.conv_kernel_sizes.split(','\t\t\t\t)]\r\n a_\t\t\t\t\t:\t\tUnion[str, Any]\t\t\t\t\t\t\t= SpeechaTextConfig(\r\n vocab_size=__A , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , num_conv_layers=len(__A\t\t\t\t) , conv_channels=args.conv_channels , conv_kernel_sizes=__A , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=__A , num_beams=5 , max_length=2_00 , use_cache=__A , decoder_start_token_id=2 , early_stopping=__A , )\r\n\r\n a_\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t\t\t= SpeechaTextForConditionalGeneration(__A\t\t\t\t)\r\n a_\t\t\t\t\t\t\t,\t\ta_\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t\t\t= model.model.load_state_dict(__A , strict=__A\t\t\t\t)\r\n if len(__A\t\t\t\t) > 0 and not set(__A\t\t\t\t) <= {\r\n \"encoder.embed_positions.weights\",\r\n \"decoder.embed_positions.weights\",\r\n }:\r\n raise ValueError(\r\n 'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,'\r\n F\"\"\" but all the following weights are missing {missing}\"\"\"\t\t\t\t)\r\n\r\n if tie_embeds:\r\n a_\t\t\t\t\t:\t\tDict\t\t\t\t\t\t\t= make_linear_from_emb(model.model.decoder.embed_tokens\t\t\t\t)\r\n else:\r\n a_\t\t\t\t\t:\t\tDict\t\t\t\t\t\t\t= lm_head_weights\r\n\r\n model.save_pretrained(__A\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n UpperCAmelCase_ : int \t\t\t\t\t= argparse.ArgumentParser()\r\n # Required parameters\r\n parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.')\r\n parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')\r\n UpperCAmelCase_ : str \t\t\t\t\t= parser.parse_args()\r\n convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":32,"string":"32"},"style_context":{"kind":"string","value":"from __future__ import annotations\r\n\r\nimport sys\r\nfrom collections import deque\r\nfrom typing import Generic, TypeVar\r\n\r\nUpperCamelCase \t\t\t\t\t\t\t=\t\t\t\t\t\tTypeVar('''T''')\r\n\r\n\r\n\r\nclass snake_case_ (\t\tGeneric[T] ):\r\n __A\t:\t\tdeque[T] # Cache store of keys\r\n __A\t:\t\tset[T] # References of the keys in cache\r\n __A\t:\t\tint =\t\t\t\t10 # Maximum capacity of cache\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __init__( self\t\t\t\t: Union[str, Any]\t,\t\t\t\t\t\tlowercase_\t\t\t\t: int )\t\t\t\t\t->\t\t\t\t\t\tNone:\r\n lowercase__ : int \t\t\t\t\t=\t\t\t\tdeque()\r\n lowercase__ : str \t\t\t\t\t=\t\t\t\tset()\r\n if not n:\r\n lowercase__ : str \t\t\t\t\t=\t\t\t\tsys.maxsize\r\n elif n < 0:\r\n raise ValueError(\"n should be an integer greater than 0.\" )\r\n else:\r\n lowercase__ : List[Any] \t\t\t\t\t=\t\t\t\tn\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __UpperCamelCase ( self\t\t\t\t: Dict\t,\t\t\t\t\t\tlowercase_\t\t\t\t: T )\t\t\t\t\t->\t\t\t\t\t\tNone:\r\n if x not in self.key_reference:\r\n if len(self.dq_store ) == LRUCache._MAX_CAPACITY:\r\n lowercase__ : Dict \t\t\t\t\t=\t\t\t\tself.dq_store.pop()\r\n self.key_reference.remove(lowercase_ )\r\n else:\r\n self.dq_store.remove(lowercase_ )\r\n\r\n self.dq_store.appendleft(lowercase_ )\r\n self.key_reference.add(lowercase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __UpperCamelCase ( self\t\t\t\t: Dict )\t\t\t\t\t->\t\t\t\t\t\tNone:\r\n for k in self.dq_store:\r\n print(lowercase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __repr__( self\t\t\t\t: Optional[int] )\t\t\t\t\t->\t\t\t\t\t\tstr:\r\n return F'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}'''\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import doctest\r\n\r\n doctest.testmod()\r\n\r\n UpperCamelCase \t\t\t\t\t\t\t=\t\t\t\t\t\tLRUCache(4)\r\n lru_cache.refer('''A''')\r\n lru_cache.refer(2)\r\n lru_cache.refer(3)\r\n lru_cache.refer('''A''')\r\n lru_cache.refer(4)\r\n lru_cache.refer(5)\r\n lru_cache.display()\r\n\r\n print(lru_cache)\r\n assert str(lru_cache) == \"LRUCache(4) => [5, 4, 'A', 3]\"\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":87,"string":"87"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":211,"cells":{"code":{"kind":"string","value":"'''simple docstring'''\n\n\n\n\n\n\nimport json\nfrom typing import TYPE_CHECKING, List, Optional, Tuple\n\nfrom tokenizers import pre_tokenizers\n\nfrom ...tokenization_utils_base import BatchEncoding\nfrom ...tokenization_utils_fast import PreTrainedTokenizerFast\nfrom ...utils import logging\nfrom .tokenization_gpta import GPTaTokenizer\n\n\nif TYPE_CHECKING:\n from transformers.pipelines.conversational import Conversation\n\n\n__a\t\t\t\t\t\t = logging.get_logger(__name__)\n\n__a\t\t\t\t\t\t = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}\n\n__a\t\t\t\t\t\t = {\n 'vocab_file': {\n 'gpt2': 'https://huggingface.co/gpt2/resolve/main/vocab.json',\n 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/vocab.json',\n 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/vocab.json',\n 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/vocab.json',\n 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/vocab.json',\n },\n 'merges_file': {\n 'gpt2': 'https://huggingface.co/gpt2/resolve/main/merges.txt',\n 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/merges.txt',\n 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/merges.txt',\n 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/merges.txt',\n 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/merges.txt',\n },\n 'tokenizer_file': {\n 'gpt2': 'https://huggingface.co/gpt2/resolve/main/tokenizer.json',\n 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json',\n 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/tokenizer.json',\n 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json',\n 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/tokenizer.json',\n },\n}\n\n__a\t\t\t\t\t\t = {\n 'gpt2': 1_024,\n 'gpt2-medium': 1_024,\n 'gpt2-large': 1_024,\n 'gpt2-xl': 1_024,\n 'distilgpt2': 1_024,\n}\n\n\n\n\n\nclass A__\t\t\t\t\t\t\t(\tUpperCamelCase__ ):\n\n\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n\n\n UpperCamelCase_\t:\t\t\t\t\t\tList[Any] =\t\t\t\t\tVOCAB_FILES_NAMES\n UpperCamelCase_\t:\t\t\t\t\t\tOptional[int] =\t\t\t\t\tPRETRAINED_VOCAB_FILES_MAP\n UpperCamelCase_\t:\t\t\t\t\t\tAny =\t\t\t\t\tPRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n UpperCamelCase_\t:\t\t\t\t\t\tList[str] =\t\t\t\t\t['''input_ids''', '''attention_mask''']\n UpperCamelCase_\t:\t\t\t\t\t\tOptional[int] =\t\t\t\t\tGPTaTokenizer\n\n\n\n\n def __init__(\t\t\tself\t\t\t\t\t:\t\tAny\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tTuple=None\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tOptional[int]=None\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tOptional[int]=None\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tDict=\"<|endoftext|>\"\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tTuple=\"<|endoftext|>\"\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tList[str]=\"<|endoftext|>\"\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tList[Any]=False\t\t\t\t\t\t,\t\t\t\t\t**lowerCAmelCase__\t\t\t\t\t:\t\tstr\t\t\t\t\t\t,\t\t\t\t\t)\t-> Optional[Any]:\n\n\n\n\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n\n super().__init__(\n UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\ttokenizer_file=UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\tunk_token=UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\tbos_token=UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\teos_token=UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\tadd_prefix_space=UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\t**UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\t)\n\n _UpperCAmelCase\t\t\t\t\t\t\t: int\t\t\t\t\t\t\t= kwargs.pop(\"add_bos_token\"\t\t\t\t\t\t,\t\t\t\t\tUpperCamelCase_ )\n\n _UpperCAmelCase\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t= json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )\n if pre_tok_state.get(\"add_prefix_space\"\t\t\t\t\t\t,\t\t\t\t\tUpperCamelCase_ ) != add_prefix_space:\n _UpperCAmelCase\t\t\t\t\t\t\t: int\t\t\t\t\t\t\t= getattr(UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\tpre_tok_state.pop(\"type\" ) )\n _UpperCAmelCase\t\t\t\t\t\t\t: str\t\t\t\t\t\t\t= add_prefix_space\n _UpperCAmelCase\t\t\t\t\t\t\t: List[str]\t\t\t\t\t\t\t= pre_tok_class(**UpperCamelCase_ )\n\n _UpperCAmelCase\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t\t= add_prefix_space\n\n\n\n\n def _lowerCAmelCase\t\t(\t\t\tself\t\t\t\t\t:\t\tDict\t\t\t\t\t\t,\t\t\t\t\t*lowerCAmelCase__\t\t\t\t\t:\t\tint\t\t\t\t\t\t,\t\t\t\t\t**lowerCAmelCase__\t\t\t\t\t:\t\tOptional[Any] )\t-> BatchEncoding:\n\n\n\n\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n\n _UpperCAmelCase\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t= kwargs.get(\"is_split_into_words\"\t\t\t\t\t\t,\t\t\t\t\tUpperCamelCase_ )\n assert self.add_prefix_space or not is_split_into_words, (\n F\"\"\"You need to instantiate {self.__class__.__name__} with add_prefix_space=True \"\"\"\n \"to use it with pretokenized inputs.\"\n )\n\n return super()._batch_encode_plus(*UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\t**UpperCamelCase_ )\n\n\n\n\n def _lowerCAmelCase\t\t(\t\t\tself\t\t\t\t\t:\t\tTuple\t\t\t\t\t\t,\t\t\t\t\t*lowerCAmelCase__\t\t\t\t\t:\t\tint\t\t\t\t\t\t,\t\t\t\t\t**lowerCAmelCase__\t\t\t\t\t:\t\tint )\t-> BatchEncoding:\n\n\n\n\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n\n _UpperCAmelCase\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t\t= kwargs.get(\"is_split_into_words\"\t\t\t\t\t\t,\t\t\t\t\tUpperCamelCase_ )\n\n assert self.add_prefix_space or not is_split_into_words, (\n F\"\"\"You need to instantiate {self.__class__.__name__} with add_prefix_space=True \"\"\"\n \"to use it with pretokenized inputs.\"\n )\n\n return super()._encode_plus(*UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\t**UpperCamelCase_ )\n\n\n\n\n def _lowerCAmelCase\t\t(\t\t\tself\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tstr\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\tOptional[str] = None )\t-> Tuple[str]:\n\n\n\n\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n\n _UpperCAmelCase\t\t\t\t\t\t\t: Any\t\t\t\t\t\t\t= self._tokenizer.model.save(UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\tname=UpperCamelCase_ )\n return tuple(UpperCamelCase_ )\n\n\n\n\n def _lowerCAmelCase\t\t(\t\t\tself\t\t\t\t\t:\t\tint\t\t\t\t\t\t,\t\t\t\t\tlowerCAmelCase__\t\t\t\t\t:\t\t\"Conversation\" )\t-> List[int]:\n\n\n\n\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n\n _UpperCAmelCase\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t\t\t= []\n for is_user, text in conversation.iter_texts():\n input_ids.extend(self.encode(UpperCamelCase_\t\t\t\t\t\t,\t\t\t\t\tadd_special_tokens=UpperCamelCase_ ) + [self.eos_token_id] )\n\n if len(UpperCamelCase_ ) > self.model_max_length:\n _UpperCAmelCase\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t\t= input_ids[-self.model_max_length :]\n return input_ids"},"code_codestyle":{"kind":"number","value":354,"string":"354"},"style_context":{"kind":"string","value":"'''simple docstring'''\n\n\n\n\n\n\ndef __UpperCAmelCase ( a_:\tint, a_:\tint\t\t\t\t\t\t\t):\n if a < 0 or b < 0:\n raise ValueError(\"the value of both inputs must be positive\"\t\t\t\t\t\t\t)\n\n _UpperCAmelCase\t\t\t\t\t\t\t: List[str]\t\t\t\t\t\t\t= str(bin(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)[2:] # remove the leading \"0b\"\n _UpperCAmelCase\t\t\t\t\t\t\t: Any\t\t\t\t\t\t\t= str(bin(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)[2:] # remove the leading \"0b\"\n\n _UpperCAmelCase\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t= max(len(a_\t\t\t\t\t\t\t), len(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n\n return \"0b\" + \"\".join(\n str(int(char_a == \"1\" and char_b == \"1\"\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n for char_a, char_b in zip(a_binary.zfill(a_\t\t\t\t\t\t\t), b_binary.zfill(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()"},"style_context_codestyle":{"kind":"number","value":17,"string":"17"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":212,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport importlib\r\nimport json\r\nimport os\r\nfrom collections import OrderedDict\r\nfrom typing import Dict, Optional, Union\r\n\r\n# Build the list of all image processors\r\nfrom ...configuration_utils import PretrainedConfig\r\nfrom ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code\r\nfrom ...image_processing_utils import ImageProcessingMixin\r\nfrom ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging\r\nfrom .auto_factory import _LazyAutoMapping\r\nfrom .configuration_auto import (\r\n CONFIG_MAPPING_NAMES,\r\n AutoConfig,\r\n model_type_to_module_name,\r\n replace_list_option_in_docstrings,\r\n)\r\n\r\n\r\nUpperCamelCase \t\t\t\t=\tlogging.get_logger(__name__)\r\n\r\nUpperCamelCase \t\t\t\t=\tOrderedDict(\r\n [\r\n ('''align''', '''EfficientNetImageProcessor'''),\r\n ('''beit''', '''BeitImageProcessor'''),\r\n ('''bit''', '''BitImageProcessor'''),\r\n ('''blip''', '''BlipImageProcessor'''),\r\n ('''blip-2''', '''BlipImageProcessor'''),\r\n ('''bridgetower''', '''BridgeTowerImageProcessor'''),\r\n ('''chinese_clip''', '''ChineseCLIPImageProcessor'''),\r\n ('''clip''', '''CLIPImageProcessor'''),\r\n ('''clipseg''', '''ViTImageProcessor'''),\r\n ('''conditional_detr''', '''ConditionalDetrImageProcessor'''),\r\n ('''convnext''', '''ConvNextImageProcessor'''),\r\n ('''convnextv2''', '''ConvNextImageProcessor'''),\r\n ('''cvt''', '''ConvNextImageProcessor'''),\r\n ('''data2vec-vision''', '''BeitImageProcessor'''),\r\n ('''deformable_detr''', '''DeformableDetrImageProcessor'''),\r\n ('''deit''', '''DeiTImageProcessor'''),\r\n ('''deta''', '''DetaImageProcessor'''),\r\n ('''detr''', '''DetrImageProcessor'''),\r\n ('''dinat''', '''ViTImageProcessor'''),\r\n ('''donut-swin''', '''DonutImageProcessor'''),\r\n ('''dpt''', '''DPTImageProcessor'''),\r\n ('''efficientformer''', '''EfficientFormerImageProcessor'''),\r\n ('''efficientnet''', '''EfficientNetImageProcessor'''),\r\n ('''flava''', '''FlavaImageProcessor'''),\r\n ('''focalnet''', '''BitImageProcessor'''),\r\n ('''git''', '''CLIPImageProcessor'''),\r\n ('''glpn''', '''GLPNImageProcessor'''),\r\n ('''groupvit''', '''CLIPImageProcessor'''),\r\n ('''imagegpt''', '''ImageGPTImageProcessor'''),\r\n ('''instructblip''', '''BlipImageProcessor'''),\r\n ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''),\r\n ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''),\r\n ('''levit''', '''LevitImageProcessor'''),\r\n ('''mask2former''', '''Mask2FormerImageProcessor'''),\r\n ('''maskformer''', '''MaskFormerImageProcessor'''),\r\n ('''mgp-str''', '''ViTImageProcessor'''),\r\n ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''),\r\n ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''),\r\n ('''mobilevit''', '''MobileViTImageProcessor'''),\r\n ('''mobilevit''', '''MobileViTImageProcessor'''),\r\n ('''mobilevitv2''', '''MobileViTImageProcessor'''),\r\n ('''nat''', '''ViTImageProcessor'''),\r\n ('''oneformer''', '''OneFormerImageProcessor'''),\r\n ('''owlvit''', '''OwlViTImageProcessor'''),\r\n ('''perceiver''', '''PerceiverImageProcessor'''),\r\n ('''pix2struct''', '''Pix2StructImageProcessor'''),\r\n ('''poolformer''', '''PoolFormerImageProcessor'''),\r\n ('''regnet''', '''ConvNextImageProcessor'''),\r\n ('''resnet''', '''ConvNextImageProcessor'''),\r\n ('''sam''', '''SamImageProcessor'''),\r\n ('''segformer''', '''SegformerImageProcessor'''),\r\n ('''swiftformer''', '''ViTImageProcessor'''),\r\n ('''swin''', '''ViTImageProcessor'''),\r\n ('''swin2sr''', '''Swin2SRImageProcessor'''),\r\n ('''swinv2''', '''ViTImageProcessor'''),\r\n ('''table-transformer''', '''DetrImageProcessor'''),\r\n ('''timesformer''', '''VideoMAEImageProcessor'''),\r\n ('''tvlt''', '''TvltImageProcessor'''),\r\n ('''upernet''', '''SegformerImageProcessor'''),\r\n ('''van''', '''ConvNextImageProcessor'''),\r\n ('''videomae''', '''VideoMAEImageProcessor'''),\r\n ('''vilt''', '''ViltImageProcessor'''),\r\n ('''vit''', '''ViTImageProcessor'''),\r\n ('''vit_hybrid''', '''ViTHybridImageProcessor'''),\r\n ('''vit_mae''', '''ViTImageProcessor'''),\r\n ('''vit_msn''', '''ViTImageProcessor'''),\r\n ('''xclip''', '''CLIPImageProcessor'''),\r\n ('''yolos''', '''YolosImageProcessor'''),\r\n ]\r\n)\r\n\r\nUpperCamelCase \t\t\t\t=\t_LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)\r\n\r\ndef __lowerCamelCase\t\t\t(\t\tsnake_case__\t\t)\t\t\t\t\t\t\t-> int:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tfor module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():\r\n\t\t\t\t\t\t\t\t\t\t\t\tif class_name in extractors:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = model_type_to_module_name(_a\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = importlib.import_module(F'.{module_name}' ,\"\"\"transformers.models\"\"\"\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn getattr(_a ,_a\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\texcept AttributeError:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\r\n\r\n\t\t\t\t\t\tfor _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():\r\n\t\t\t\t\t\t\t\t\t\t\t\tif getattr(_a ,\"\"\"__name__\"\"\" ,_a\t\t) == class_name:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn extractor\r\n\r\n # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main\r\n # init and we return the proper dummy to get an appropriate error message.\r\n\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = importlib.import_module(\"\"\"transformers\"\"\"\t\t)\r\n\t\t\t\t\t\tif hasattr(_a ,_a\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn getattr(_a ,_a\t\t)\r\n\r\n\t\t\t\t\t\treturn None\r\n\r\ndef __lowerCamelCase\t\t\t(\t\tsnake_case__ ,snake_case__ = None ,snake_case__ = False ,snake_case__ = False ,snake_case__ = None ,snake_case__ = None ,snake_case__ = None ,snake_case__ = False ,**snake_case__ ,)\t\t\t\t\t\t\t-> Union[str, Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = get_file_from_repo(\r\n\t\t\t\t\t\t _a ,_a ,cache_dir=_a ,force_download=_a ,resume_download=_a ,proxies=_a ,use_auth_token=_a ,revision=_a ,local_files_only=_a ,)\r\n\t\t\t\t\t\tif resolved_config_file is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"Could not locate the image processor configuration file, will try to use the model config instead.\"\"\"\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn {}\r\n\r\n\t\t\t\t\t\twith open(_a ,encoding=\"\"\"utf-8\"\"\"\t\t) as reader:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn json.load(_a\t\t)\r\n\r\n\r\n\r\n\r\nclass __UpperCAmelCase\t\t:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef __init__(\tself: Optional[int] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\traise EnvironmentError(\r\n\t\t\t\t\t\t\t\t\t \"\"\"AutoImageProcessor is designed to be instantiated \"\"\"\r\n\t\t\t\t\t\t\t\t\t \"\"\"using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.\"\"\" )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t@classmethod\r\n\t\t\t@replace_list_option_in_docstrings(UpperCAmelCase_ )\r\n\t\t\tdef \t\t\t\t\t\t\tUpperCamelCase (\tcls: Optional[int] ,\tUpperCAmelCase_: List[str] ,\t**UpperCAmelCase_: List[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = kwargs.pop(\"\"\"config\"\"\" ,\tUpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = kwargs.pop(\"\"\"trust_remote_code\"\"\" ,\tUpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = True\r\n\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = ImageProcessingMixin.get_image_processor_dict(UpperCAmelCase_ ,\t**UpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = config_dict.get(\"\"\"image_processor_type\"\"\" ,\tUpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = None\r\n\t\t\t\t\t\t\t\t\tif \"AutoImageProcessor\" in config_dict.get(\"\"\"auto_map\"\"\" ,\t{} ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = config_dict[\"auto_map\"][\"AutoImageProcessor\"]\r\n\r\n\t\t\t\t\t\t\t\t\t# If we still don't have the image processor class, check if we're loading from a previous feature extractor config\r\n\t\t\t\t\t\t\t\t\t# and if so, infer the image processor class from there.\r\n\t\t\t\t\t\t\t\t\tif image_processor_class is None and image_processor_auto_map is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = config_dict.pop(\"\"\"feature_extractor_type\"\"\" ,\tUpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif feature_extractor_class is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.warning(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"Could not find image processor class in the image processor config or the model config. Loading\"\"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\" based on pattern matching with the model's feature extractor configuration.\"\"\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = feature_extractor_class.replace(\"\"\"FeatureExtractor\"\"\" ,\t\"\"\"ImageProcessor\"\"\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"AutoFeatureExtractor\" in config_dict.get(\"\"\"auto_map\"\"\" ,\t{} ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = config_dict[\"auto_map\"][\"AutoFeatureExtractor\"]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = feature_extractor_auto_map.replace(\"\"\"FeatureExtractor\"\"\" ,\t\"\"\"ImageProcessor\"\"\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.warning(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"Could not find image processor auto map in the image processor config or the model config.\"\"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\" Loading based on pattern matching with the model's feature extractor configuration.\"\"\" )\r\n\r\n # If we don't find the image processor class in the image processor config, let's try the model config.\r\n\t\t\t\t\t\t\t\t\tif image_processor_class is None and image_processor_auto_map is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(UpperCAmelCase_ ,\tUpperCAmelCase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = AutoConfig.from_pretrained(UpperCAmelCase_ ,\t**UpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# It could be in `config.image_processor_type``\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = getattr(UpperCAmelCase_ ,\t\"\"\"image_processor_type\"\"\" ,\tUpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif hasattr(UpperCAmelCase_ ,\t\"\"\"auto_map\"\"\" ) and \"AutoImageProcessor\" in config.auto_map:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = config.auto_map[\"AutoImageProcessor\"]\r\n\r\n\t\t\t\t\t\t\t\t\tif image_processor_class is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = image_processor_class_from_name(UpperCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = image_processor_auto_map is not None\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = image_processor_class is not None or type(UpperCAmelCase_ ) in IMAGE_PROCESSOR_MAPPING\r\n\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = resolve_trust_remote_code(\r\n\t\t\t\t\t\t\t\t\t UpperCAmelCase_ ,\tUpperCAmelCase_ ,\tUpperCAmelCase_ ,\tUpperCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\tif has_remote_code and trust_remote_code:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = get_class_from_dynamic_module(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCAmelCase_ ,\tUpperCAmelCase_ ,\t**UpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = kwargs.pop(\"\"\"code_revision\"\"\" ,\tUpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif os.path.isdir(UpperCAmelCase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timage_processor_class.register_for_auto_class()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn image_processor_class.from_dict(UpperCAmelCase_ ,\t**UpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\telif image_processor_class is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn image_processor_class.from_dict(UpperCAmelCase_ ,\t**UpperCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t# Last try: we use the IMAGE_PROCESSOR_MAPPING.\r\n\t\t\t\t\t\t\t\t\telif type(UpperCAmelCase_ ) in IMAGE_PROCESSOR_MAPPING:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t = IMAGE_PROCESSOR_MAPPING[type(UpperCAmelCase_ )]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn image_processor_class.from_dict(UpperCAmelCase_ ,\t**UpperCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t F'Unrecognized image processor in {pretrained_model_name_or_path}. Should have a '\r\n\t\t\t\t\t\t\t\t\t F'`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following '\r\n\t\t\t\t\t\t\t\t\t F'`model_type` keys in its {CONFIG_NAME}: {\", \".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}' )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t@staticmethod\r\n\t\t\tdef \t\t\t\t\t\t\tUpperCamelCase (\tUpperCAmelCase_: Dict ,\tUpperCAmelCase_: List[str] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\tIMAGE_PROCESSOR_MAPPING.register(UpperCAmelCase_ ,\tUpperCAmelCase_ )\r\n\r\n"},"code_codestyle":{"kind":"number","value":306,"string":"306"},"style_context":{"kind":"string","value":"\r\rfrom __future__ import annotations\r\rimport unittest\r\rfrom transformers import is_tf_available\rfrom transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow\r\r\rif is_tf_available():\r\t\t\timport tensorflow as tf\r\r\t\t\tfrom transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM\r\r\r\r\r\r\r@require_tf\r@require_sentencepiece\r@require_tokenizers\rclass _UpperCamelCase\t\t\t\t\t\t\t(\t\t\t\t\t\t\tunittest.TestCase ):\r\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\r\t\t\t@slow\r\t\t\tdef \t\t\t\t\t\t\t__UpperCamelCase (\tself\t\t\t\t\t\t\t: str\t\t)\t\t\t\t\t\t\t->\t\t\t\tList[str]:\r\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\t\t\t\tSCREAMING_SNAKE_CASE :\t\t\t\t\tOptional[Any] =\t\t\t\tTFAutoModelForSeqaSeqLM.from_pretrained(\"google/mt5-small\"\t\t)\r\t\t\t\tSCREAMING_SNAKE_CASE :\t\t\t\t\tList[str] =\t\t\t\tAutoTokenizer.from_pretrained(\"google/mt5-small\"\t\t)\r\r\t\t\t\tSCREAMING_SNAKE_CASE :\t\t\t\t\tTuple =\t\t\t\ttokenizer(\"Hello there\"\t\t\t\t\t,\t\t\t\t\treturn_tensors=\"tf\"\t\t).input_ids\r\t\t\t\tSCREAMING_SNAKE_CASE :\t\t\t\t\tOptional[Any] =\t\t\t\ttokenizer(\"Hi I am\"\t\t\t\t\t,\t\t\t\t\treturn_tensors=\"tf\"\t\t).input_ids\r\r\t\t\t\tSCREAMING_SNAKE_CASE :\t\t\t\t\tstr =\t\t\t\tmodel(a\t\t\t\t\t,\t\t\t\t\tlabels=a\t\t).loss\r\t\t\t\tSCREAMING_SNAKE_CASE :\t\t\t\t\tAny =\t\t\t\t-tf.math.reduce_mean(a\t\t).numpy()\r\r\t\t\t\tSCREAMING_SNAKE_CASE :\t\t\t\t\tUnion[str, Any] =\t\t\t\t-21.22_8168\r\t\t\t\tself.assertTrue(abs(mtf_score - EXPECTED_SCORE\t\t) < 2e-4\t\t)"},"style_context_codestyle":{"kind":"number","value":76,"string":"76"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":213,"cells":{"code":{"kind":"string","value":"\n\n\n\n\n\"\"\"simple docstring\"\"\"\n\n\nimport gc\nimport random\nimport unittest\n\nimport numpy as np\nimport torch\nfrom PIL import Image\n\nfrom diffusers import (\n DDIMScheduler,\n KandinskyVaaImgaImgPipeline,\n KandinskyVaaPriorPipeline,\n UNetaDConditionModel,\n VQModel,\n)\nfrom diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device\nfrom diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu\n\nfrom ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference\n\n\nenable_full_determinism()\n\n\nclass _lowerCamelCase (\t\t\t\t\ta_ ,\tunittest.TestCase\t\t\t\t\t\t):\n _lowerCamelCase :List[Any] \t\t\t\t= KandinskyVaaImgaImgPipeline\n _lowerCamelCase :Any \t\t\t\t= [\"image_embeds\", \"negative_image_embeds\", \"image\"]\n _lowerCamelCase :Any \t\t\t\t= [\n \"image_embeds\",\n \"negative_image_embeds\",\n \"image\",\n ]\n _lowerCamelCase :int \t\t\t\t= [\n \"generator\",\n \"height\",\n \"width\",\n \"strength\",\n \"guidance_scale\",\n \"num_inference_steps\",\n \"return_dict\",\n \"guidance_scale\",\n \"num_images_per_prompt\",\n \"output_type\",\n \"return_dict\",\n ]\n _lowerCamelCase :List[Any] \t\t\t\t= False\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n return 32\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tint )\t\t\t->\t\t\t\t\t\tOptional[int]:\n\n \"\"\"simple docstring\"\"\"\n return 32\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tList[Any]:\n\n \"\"\"simple docstring\"\"\"\n return self.time_input_dim\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tAny )\t\t\t->\t\t\t\t\t\tList[str]:\n\n \"\"\"simple docstring\"\"\"\n return self.time_input_dim * 4\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tAny )\t\t\t->\t\t\t\t\t\tAny:\n\n \"\"\"simple docstring\"\"\"\n return 1_00\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tAny )\t\t\t->\t\t\t\t\t\tAny:\n\n \"\"\"simple docstring\"\"\"\n torch.manual_seed(0 )\n\n lowerCAmelCase__ :\t\t\tOptional[int] =\t{\n \"\"\"in_channels\"\"\": 4,\n # Out channels is double in channels because predicts mean and variance\n \"\"\"out_channels\"\"\": 8,\n \"\"\"addition_embed_type\"\"\": \"\"\"image\"\"\",\n \"\"\"down_block_types\"\"\": (\"\"\"ResnetDownsampleBlock2D\"\"\", \"\"\"SimpleCrossAttnDownBlock2D\"\"\"),\n \"\"\"up_block_types\"\"\": (\"\"\"SimpleCrossAttnUpBlock2D\"\"\", \"\"\"ResnetUpsampleBlock2D\"\"\"),\n \"\"\"mid_block_type\"\"\": \"\"\"UNetMidBlock2DSimpleCrossAttn\"\"\",\n \"\"\"block_out_channels\"\"\": (self.block_out_channels_a, self.block_out_channels_a * 2),\n \"\"\"layers_per_block\"\"\": 1,\n \"\"\"encoder_hid_dim\"\"\": self.text_embedder_hidden_size,\n \"\"\"encoder_hid_dim_type\"\"\": \"\"\"image_proj\"\"\",\n \"\"\"cross_attention_dim\"\"\": self.cross_attention_dim,\n \"\"\"attention_head_dim\"\"\": 4,\n \"\"\"resnet_time_scale_shift\"\"\": \"\"\"scale_shift\"\"\",\n \"\"\"class_embed_type\"\"\": None,\n }\n\n lowerCAmelCase__ :\t\t\tAny =\tUNetaDConditionModel(**UpperCamelCase )\n return model\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tTuple:\n\n \"\"\"simple docstring\"\"\"\n return {\n \"block_out_channels\": [32, 64],\n \"down_block_types\": [\"DownEncoderBlock2D\", \"AttnDownEncoderBlock2D\"],\n \"in_channels\": 3,\n \"latent_channels\": 4,\n \"layers_per_block\": 1,\n \"norm_num_groups\": 8,\n \"norm_type\": \"spatial\",\n \"num_vq_embeddings\": 12,\n \"out_channels\": 3,\n \"up_block_types\": [\n \"AttnUpDecoderBlock2D\",\n \"UpDecoderBlock2D\",\n ],\n \"vq_embed_dim\": 4,\n }\n\n\n\n\n\n\n @property\n def \t_lowerCAmelCase (\t\tself :\t\tstr )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n torch.manual_seed(0 )\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tVQModel(**self.dummy_movq_kwargs )\n return model\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tTuple )\t\t\t->\t\t\t\t\t\tAny:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tList[Any] =\tself.dummy_unet\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tself.dummy_movq\n\n lowerCAmelCase__ :\t\t\tAny =\t{\n \"\"\"num_train_timesteps\"\"\": 10_00,\n \"\"\"beta_schedule\"\"\": \"\"\"linear\"\"\",\n \"\"\"beta_start\"\"\": 0.0_0085,\n \"\"\"beta_end\"\"\": 0.012,\n \"\"\"clip_sample\"\"\": False,\n \"\"\"set_alpha_to_one\"\"\": False,\n \"\"\"steps_offset\"\"\": 0,\n \"\"\"prediction_type\"\"\": \"\"\"epsilon\"\"\",\n \"\"\"thresholding\"\"\": False,\n }\n\n lowerCAmelCase__ :\t\t\tint =\tDDIMScheduler(**UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tTuple =\t{\n \"\"\"unet\"\"\": unet,\n \"\"\"scheduler\"\"\": scheduler,\n \"\"\"movq\"\"\": movq,\n }\n\n return components\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tTuple , UpperCamelCase :\t\tUnion[str, Any] , UpperCamelCase :\t\tDict=0 )\t\t\t->\t\t\t\t\t\tList[str]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tList[Any] =\tfloats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase )\n lowerCAmelCase__ :\t\t\tAny =\tfloats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(\n UpperCamelCase )\n # create init_image\n lowerCAmelCase__ :\t\t\tTuple =\tfloats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase )\n lowerCAmelCase__ :\t\t\tint =\timage.cpu().permute(0 , 2 , 3 , 1 )[0]\n lowerCAmelCase__ :\t\t\tTuple =\tImage.fromarray(np.uinta(UpperCamelCase ) ).convert(\"\"\"RGB\"\"\" ).resize((2_56, 2_56) )\n\n if str(UpperCamelCase ).startswith(\"\"\"mps\"\"\" ):\n lowerCAmelCase__ :\t\t\tDict =\ttorch.manual_seed(UpperCamelCase )\n else:\n lowerCAmelCase__ :\t\t\tint =\ttorch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase )\n lowerCAmelCase__ :\t\t\tOptional[int] =\t{\n \"\"\"image\"\"\": init_image,\n \"\"\"image_embeds\"\"\": image_embeds,\n \"\"\"negative_image_embeds\"\"\": negative_image_embeds,\n \"\"\"generator\"\"\": generator,\n \"\"\"height\"\"\": 64,\n \"\"\"width\"\"\": 64,\n \"\"\"num_inference_steps\"\"\": 10,\n \"\"\"guidance_scale\"\"\": 7.0,\n \"\"\"strength\"\"\": 0.2,\n \"\"\"output_type\"\"\": \"\"\"np\"\"\",\n }\n return inputs\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tstr )\t\t\t->\t\t\t\t\t\tUnion[str, Any]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tList[str] =\t\"\"\"cpu\"\"\"\n\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tself.get_dummy_components()\n\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tself.pipeline_class(**UpperCamelCase )\n lowerCAmelCase__ :\t\t\tTuple =\tpipe.to(UpperCamelCase )\n\n pipe.set_progress_bar_config(disable=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tpipe(**self.get_dummy_inputs(UpperCamelCase ) )\n lowerCAmelCase__ :\t\t\tList[str] =\toutput.images\n\n lowerCAmelCase__ :\t\t\tDict =\tpipe(\n **self.get_dummy_inputs(UpperCamelCase ) , return_dict=UpperCamelCase , )[0]\n\n lowerCAmelCase__ :\t\t\tOptional[Any] =\timage[0, -3:, -3:, -1]\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\timage_from_tuple[0, -3:, -3:, -1]\n\n assert image.shape == (1, 64, 64, 3)\n\n lowerCAmelCase__ :\t\t\tDict =\tnp.array(\n [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263] )\n assert (\n np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2\n ), f\"\"\" expected_slice {expected_slice}, but got {image_slice.flatten()}\"\"\"\n assert (\n np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2\n ), f\"\"\" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}\"\"\"\n\n\n\n\n\n\n@slow\n@require_torch_gpu\nclass _lowerCamelCase (\t\t\t\t\tunittest.TestCase\t\t\t\t\t\t):\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint )\t\t\t->\t\t\t\t\t\tList[str]:\n\n \"\"\"simple docstring\"\"\"\n super().tearDown()\n gc.collect()\n torch.cuda.empty_cache()\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[int] )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tstr =\tload_numpy(\n \"\"\"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\"\"\n \"\"\"/kandinskyv22/kandinskyv22_img2img_frog.npy\"\"\" )\n\n lowerCAmelCase__ :\t\t\tOptional[int] =\tload_image(\n \"\"\"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\"\" \"\"\"/kandinsky/cat.png\"\"\" )\n lowerCAmelCase__ :\t\t\tDict =\t\"\"\"A red cartoon frog, 4k\"\"\"\n\n lowerCAmelCase__ :\t\t\tOptional[int] =\tKandinskyVaaPriorPipeline.from_pretrained(\n \"\"\"kandinsky-community/kandinsky-2-2-prior\"\"\" , torch_dtype=torch.floataa )\n pipe_prior.to(UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tDict =\tKandinskyVaaImgaImgPipeline.from_pretrained(\n \"\"\"kandinsky-community/kandinsky-2-2-decoder\"\"\" , torch_dtype=torch.floataa )\n lowerCAmelCase__ :\t\t\tTuple =\tpipeline.to(UpperCamelCase )\n\n pipeline.set_progress_bar_config(disable=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tstr =\ttorch.Generator(device=\"\"\"cpu\"\"\" ).manual_seed(0 )\n lowerCAmelCase__ :\t\t\tList[str] =\tpipe_prior(\n UpperCamelCase , generator=UpperCamelCase , num_inference_steps=5 , negative_prompt=\"\"\"\"\"\" , ).to_tuple()\n\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tpipeline(\n image=UpperCamelCase , image_embeds=UpperCamelCase , negative_image_embeds=UpperCamelCase , generator=UpperCamelCase , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type=\"\"\"np\"\"\" , )\n\n lowerCAmelCase__ :\t\t\tOptional[int] =\toutput.images[0]\n\n assert image.shape == (7_68, 7_68, 3)\n\n assert_mean_pixel_difference(UpperCamelCase , UpperCamelCase )\n\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":360,"string":"360"},"style_context":{"kind":"string","value":"\n\n\n\n\n\"\"\"simple docstring\"\"\"\n\n\nfrom __future__ import annotations\n\nimport collections\nimport tempfile\nimport unittest\n\nimport numpy as np\n\nfrom transformers.testing_utils import require_tf, require_vision, slow\nfrom transformers.utils import is_tf_available, is_vision_available\n\nfrom ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask\nfrom ..bert.test_modeling_tf_bert import TFBertModelTester\nfrom ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester\nfrom ..deit.test_modeling_tf_deit import TFDeiTModelTester\nfrom ..roberta.test_modeling_tf_roberta import TFRobertaModelTester\nfrom ..vit.test_modeling_tf_vit import TFViTModelTester\n\n\nif is_tf_available():\n from transformers import (\n TFBertModel,\n TFCLIPVisionModel,\n TFDeiTModel,\n TFRobertaModel,\n TFVisionTextDualEncoderModel,\n TFViTModel,\n VisionTextDualEncoderConfig,\n )\n\nif is_vision_available():\n from PIL import Image\n\n from transformers import VisionTextDualEncoderProcessor\n\n\n\ndef \tlowercase_\t\t\t\t(\t\t\t__UpperCAmelCase\t\t\t\t)\t\t\t\t\t\t-> str:\n if isinstance(__UpperCAmelCase ,\t\tcollections.abc.Iterable\t\t\t\t):\n return x\n return (x, x)\n\n\n@require_tf\nclass _lowerCamelCase :\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tDict , UpperCamelCase :\t\tList[Any] , UpperCamelCase :\t\tint )\t\t\t->\t\t\t\t\t\tint:\n\n \"\"\"simple docstring\"\"\"\n pass\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tOptional[Any]:\n\n \"\"\"simple docstring\"\"\"\n pass\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tTuple )\t\t\t->\t\t\t\t\t\tList[Any]:\n\n \"\"\"simple docstring\"\"\"\n pass\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tstr , UpperCamelCase :\t\tTuple , UpperCamelCase :\t\tOptional[Any] , UpperCamelCase :\t\tList[Any] , UpperCamelCase :\t\tDict , UpperCamelCase :\t\tAny=None , **UpperCamelCase :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tstr:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tOptional[int] =\tVisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase , UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tDict =\tTFVisionTextDualEncoderModel(UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tList[Any] =\tmodel(input_ids=UpperCamelCase , pixel_values=UpperCamelCase , attention_mask=UpperCamelCase )\n\n self.assertEqual(output[\"\"\"text_embeds\"\"\"].shape , (input_ids.shape[0], config.projection_dim) )\n self.assertEqual(output[\"\"\"image_embeds\"\"\"].shape , (pixel_values.shape[0], config.projection_dim) )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint , UpperCamelCase :\t\tList[str] , UpperCamelCase :\t\tUnion[str, Any] , UpperCamelCase :\t\tTuple , UpperCamelCase :\t\tDict , UpperCamelCase :\t\tAny=None , **UpperCamelCase :\t\tUnion[str, Any] )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tOptional[int] =\tself.get_vision_text_model(UpperCamelCase , UpperCamelCase )\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tTFVisionTextDualEncoderModel(vision_model=UpperCamelCase , text_model=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tOptional[int] =\tmodel(input_ids=UpperCamelCase , pixel_values=UpperCamelCase , attention_mask=UpperCamelCase )\n\n self.assertEqual(output[\"\"\"text_embeds\"\"\"].shape , (input_ids.shape[0], model.config.projection_dim) )\n self.assertEqual(output[\"\"\"image_embeds\"\"\"].shape , (pixel_values.shape[0], model.config.projection_dim) )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[int] , UpperCamelCase :\t\tAny , UpperCamelCase :\t\tstr , UpperCamelCase :\t\tTuple , UpperCamelCase :\t\tUnion[str, Any] , UpperCamelCase :\t\tList[str]=None , **UpperCamelCase :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tAny:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tint =\tself.get_vision_text_model(UpperCamelCase , UpperCamelCase )\n lowerCAmelCase__ :\t\t\tDict =\t{\"\"\"vision_model\"\"\": vision_model, \"\"\"text_model\"\"\": text_model}\n lowerCAmelCase__ :\t\t\tOptional[int] =\tTFVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tmodel(input_ids=UpperCamelCase , pixel_values=UpperCamelCase , attention_mask=UpperCamelCase )\n\n self.assertEqual(output[\"\"\"text_embeds\"\"\"].shape , (input_ids.shape[0], model.config.projection_dim) )\n self.assertEqual(output[\"\"\"image_embeds\"\"\"].shape , (pixel_values.shape[0], model.config.projection_dim) )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint , UpperCamelCase :\t\tList[str] , UpperCamelCase :\t\tOptional[Any] , UpperCamelCase :\t\tAny , UpperCamelCase :\t\tList[str] , UpperCamelCase :\t\tTuple=None , **UpperCamelCase :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tAny:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tOptional[int] =\tself.get_vision_text_model(UpperCamelCase , UpperCamelCase )\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tTFVisionTextDualEncoderModel(vision_model=UpperCamelCase , text_model=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tList[Any] =\tmodel(input_ids=UpperCamelCase , pixel_values=UpperCamelCase , attention_mask=UpperCamelCase )\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\toutput[0].numpy()\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n model.save_pretrained(UpperCamelCase )\n lowerCAmelCase__ :\t\t\tstr =\tTFVisionTextDualEncoderModel.from_pretrained(UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tmodel(input_ids=UpperCamelCase , pixel_values=UpperCamelCase , attention_mask=UpperCamelCase )\n lowerCAmelCase__ :\t\t\tint =\tafter_output[0].numpy()\n lowerCAmelCase__ :\t\t\tTuple =\tnp.amax(np.abs(out_a - out_a ) )\n self.assertLessEqual(UpperCamelCase , 1E-5 )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint , UpperCamelCase :\t\tDict , UpperCamelCase :\t\tstr , UpperCamelCase :\t\tOptional[int] , UpperCamelCase :\t\tList[str] , UpperCamelCase :\t\tList[Any]=None , **UpperCamelCase :\t\tOptional[int] )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tstr =\tself.get_vision_text_model(UpperCamelCase , UpperCamelCase )\n lowerCAmelCase__ :\t\t\tint =\tTFVisionTextDualEncoderModel(vision_model=UpperCamelCase , text_model=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tDict =\tmodel(\n input_ids=UpperCamelCase , pixel_values=UpperCamelCase , attention_mask=UpperCamelCase , output_attentions=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tOptional[int] =\toutput.vision_model_output.attentions\n self.assertEqual(len(UpperCamelCase ) , vision_config.num_hidden_layers )\n\n # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)\n lowerCAmelCase__ :\t\t\tOptional[int] =\tto_atuple(vision_model.config.image_size )\n lowerCAmelCase__ :\t\t\tAny =\tto_atuple(vision_model.config.patch_size )\n lowerCAmelCase__ :\t\t\tList[str] =\t(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])\n lowerCAmelCase__ :\t\t\tTuple =\tnum_patches + 1\n self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) )\n\n lowerCAmelCase__ :\t\t\tList[str] =\toutput.text_model_output.attentions\n self.assertEqual(len(UpperCamelCase ) , text_config.num_hidden_layers )\n\n self.assertEqual(\n text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tUnion[str, Any] , UpperCamelCase :\t\tnp.ndarray , UpperCamelCase :\t\tnp.ndarray , UpperCamelCase :\t\tfloat )\t\t\t->\t\t\t\t\t\tOptional[Any]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tList[str] =\tnp.abs((a - b) ).max()\n self.assertLessEqual(UpperCamelCase , UpperCamelCase , f\"\"\"Difference between torch and flax is {diff} (>= {tol}).\"\"\" )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tstr )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tself.prepare_config_and_inputs()\n self.check_vision_text_dual_encoder_model(**UpperCamelCase )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tDict )\t\t\t->\t\t\t\t\t\tint:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tAny =\tself.prepare_config_and_inputs()\n self.check_model_from_pretrained_configs(**UpperCamelCase )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tTuple:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tOptional[int] =\tself.prepare_config_and_inputs()\n self.check_vision_text_dual_encoder_from_pretrained(**UpperCamelCase )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tAny )\t\t\t->\t\t\t\t\t\tstr:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tself.prepare_config_and_inputs()\n self.check_save_load(**UpperCamelCase )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[int] )\t\t\t->\t\t\t\t\t\tOptional[Any]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tOptional[int] =\tself.prepare_config_and_inputs()\n self.check_vision_text_output_attention(**UpperCamelCase )\n\n\n\n\n\n\n @slow\n def \t_lowerCAmelCase (\t\tself :\t\tstr )\t\t\t->\t\t\t\t\t\tList[str]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tList[str] =\tself.get_pretrained_model_and_inputs()\n\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tmodel_a(**UpperCamelCase )\n lowerCAmelCase__ :\t\t\tAny =\toutputs[0].numpy()\n\n with tempfile.TemporaryDirectory() as tmp_dirname:\n model_a.save_pretrained(UpperCamelCase )\n lowerCAmelCase__ :\t\t\tint =\tTFVisionTextDualEncoderModel.from_pretrained(UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tList[str] =\tmodel_a(**UpperCamelCase )\n lowerCAmelCase__ :\t\t\tDict =\tafter_outputs[0].numpy()\n lowerCAmelCase__ :\t\t\tList[str] =\tnp.amax(np.abs(out_a - out_a ) )\n self.assertLessEqual(UpperCamelCase , 1E-5 )\n\n\n\n\n\n\n@require_tf\nclass _lowerCamelCase (\t\t\t\t\ta_ ,\tunittest.TestCase\t\t\t\t\t\t):\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tDict =\tTFVisionTextDualEncoderModel.from_vision_text_pretrained(\n \"\"\"hf-internal-testing/tiny-random-vit\"\"\" , \"\"\"hf-internal-testing/tiny-random-bert\"\"\" )\n lowerCAmelCase__ :\t\t\tOptional[Any] =\t13\n lowerCAmelCase__ :\t\t\tList[str] =\tfloats_tensor(\n [\n batch_size,\n model.vision_model.config.num_channels,\n model.vision_model.config.image_size,\n model.vision_model.config.image_size,\n ] )\n lowerCAmelCase__ :\t\t\tDict =\tids_tensor([batch_size, 4] , model.text_model.config.vocab_size )\n lowerCAmelCase__ :\t\t\tOptional[Any] =\trandom_attention_mask([batch_size, 4] )\n lowerCAmelCase__ :\t\t\tDict =\t{\"\"\"pixel_values\"\"\": pixel_values, \"\"\"input_ids\"\"\": input_ids, \"\"\"attention_mask\"\"\": attention_mask}\n\n return model, inputs\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tAny , UpperCamelCase :\t\tUnion[str, Any] , UpperCamelCase :\t\tint )\t\t\t->\t\t\t\t\t\tstr:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tstr =\tTFViTModel(UpperCamelCase , name=\"\"\"vision_model\"\"\" )\n lowerCAmelCase__ :\t\t\tAny =\tTFBertModel(UpperCamelCase , name=\"\"\"text_model\"\"\" )\n return vision_model, text_model\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint )\t\t\t->\t\t\t\t\t\tDict:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tstr =\tTFViTModelTester(self )\n lowerCAmelCase__ :\t\t\tstr =\tTFBertModelTester(self )\n lowerCAmelCase__ :\t\t\tOptional[int] =\tvit_model_tester.prepare_config_and_inputs()\n lowerCAmelCase__ :\t\t\tList[Any] =\tbert_model_tester.prepare_config_and_inputs()\n\n lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tDict =\tvision_config_and_inputs\n\n (\n (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , \n ) :\t\t\tList[Any] =\ttext_config_and_inputs\n\n return {\n \"text_config\": text_config,\n \"vision_config\": vision_config,\n \"pixel_values\": pixel_values,\n \"attention_mask\": input_mask,\n \"input_ids\": input_ids,\n \"text_token_type_ids\": token_type_ids,\n \"text_sequence_labels\": sequence_labels,\n \"text_token_labels\": token_labels,\n \"text_choice_labels\": choice_labels,\n }\n\n\n\n\n\n\n@require_tf\nclass _lowerCamelCase (\t\t\t\t\ta_ ,\tunittest.TestCase\t\t\t\t\t\t):\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint )\t\t\t->\t\t\t\t\t\tstr:\n\n \"\"\"simple docstring\"\"\"\n # DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's\n # just reinitialize it.\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tTFVisionTextDualEncoderModel.from_vision_text_pretrained(\n \"\"\"Rocketknight1/tiny-random-deit-tf\"\"\" , \"\"\"hf-internal-testing/tiny-random-roberta\"\"\" )\n lowerCAmelCase__ :\t\t\tstr =\t13\n lowerCAmelCase__ :\t\t\tOptional[int] =\tfloats_tensor(\n [\n batch_size,\n model.vision_model.config.num_channels,\n model.vision_model.config.image_size,\n model.vision_model.config.image_size,\n ] )\n lowerCAmelCase__ :\t\t\tList[Any] =\tids_tensor([batch_size, 4] , model.text_model.config.vocab_size )\n lowerCAmelCase__ :\t\t\tOptional[Any] =\trandom_attention_mask([batch_size, 4] )\n lowerCAmelCase__ :\t\t\tList[Any] =\t{\"\"\"pixel_values\"\"\": pixel_values, \"\"\"input_ids\"\"\": input_ids, \"\"\"attention_mask\"\"\": attention_mask}\n\n return model, inputs\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[Any] , UpperCamelCase :\t\tUnion[str, Any] , UpperCamelCase :\t\tUnion[str, Any] , UpperCamelCase :\t\tOptional[Any] , UpperCamelCase :\t\tstr , UpperCamelCase :\t\tstr=None , **UpperCamelCase :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tint:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tList[Any] =\tself.get_vision_text_model(UpperCamelCase , UpperCamelCase )\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tTFVisionTextDualEncoderModel(vision_model=UpperCamelCase , text_model=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tmodel(\n input_ids=UpperCamelCase , pixel_values=UpperCamelCase , attention_mask=UpperCamelCase , output_attentions=UpperCamelCase )\n\n lowerCAmelCase__ :\t\t\tOptional[int] =\toutput.vision_model_output.attentions\n self.assertEqual(len(UpperCamelCase ) , vision_config.num_hidden_layers )\n\n # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)\n lowerCAmelCase__ :\t\t\tDict =\tto_atuple(vision_model.config.image_size )\n lowerCAmelCase__ :\t\t\tAny =\tto_atuple(vision_model.config.patch_size )\n lowerCAmelCase__ :\t\t\tDict =\t(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tnum_patches + 2\n self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) )\n\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\toutput.text_model_output.attentions\n self.assertEqual(len(UpperCamelCase ) , text_config.num_hidden_layers )\n\n self.assertEqual(\n text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , )\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tint , UpperCamelCase :\t\tAny , UpperCamelCase :\t\tstr )\t\t\t->\t\t\t\t\t\tList[Any]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tAny =\tTFDeiTModel(UpperCamelCase , name=\"\"\"vision_model\"\"\" )\n lowerCAmelCase__ :\t\t\tstr =\tTFRobertaModel(UpperCamelCase , name=\"\"\"text_model\"\"\" )\n return vision_model, text_model\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tList[str] )\t\t\t->\t\t\t\t\t\tstr:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tTFDeiTModelTester(self )\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tTFRobertaModelTester(self )\n lowerCAmelCase__ :\t\t\tOptional[int] =\tvit_model_tester.prepare_config_and_inputs()\n lowerCAmelCase__ :\t\t\tAny =\tbert_model_tester.prepare_config_and_inputs()\n\n lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tOptional[Any] =\tvision_config_and_inputs\n\n (\n (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , \n ) :\t\t\tstr =\ttext_config_and_inputs\n\n return {\n \"text_config\": text_config,\n \"vision_config\": vision_config,\n \"pixel_values\": pixel_values,\n \"attention_mask\": input_mask,\n \"input_ids\": input_ids,\n \"text_token_type_ids\": token_type_ids,\n \"text_sequence_labels\": sequence_labels,\n \"text_token_labels\": token_labels,\n \"text_choice_labels\": choice_labels,\n }\n\n\n\n\n\n\n@require_tf\nclass _lowerCamelCase (\t\t\t\t\ta_ ,\tunittest.TestCase\t\t\t\t\t\t):\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tList[str] )\t\t\t->\t\t\t\t\t\tTuple:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tUnion[str, Any] =\tTFVisionTextDualEncoderModel.from_vision_text_pretrained(\n \"\"\"Rocketknight1/tiny-random-clip-tf\"\"\" , \"\"\"hf-internal-testing/tiny-random-bert\"\"\" )\n lowerCAmelCase__ :\t\t\tAny =\t13\n lowerCAmelCase__ :\t\t\tList[str] =\tfloats_tensor(\n [\n batch_size,\n model.vision_model.config.num_channels,\n model.vision_model.config.image_size,\n model.vision_model.config.image_size,\n ] )\n lowerCAmelCase__ :\t\t\tOptional[Any] =\tids_tensor([batch_size, 4] , model.text_model.config.vocab_size )\n lowerCAmelCase__ :\t\t\tstr =\trandom_attention_mask([batch_size, 4] )\n lowerCAmelCase__ :\t\t\tList[str] =\t{\"\"\"pixel_values\"\"\": pixel_values, \"\"\"input_ids\"\"\": input_ids, \"\"\"attention_mask\"\"\": attention_mask}\n\n return model, inputs\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tstr , UpperCamelCase :\t\tstr , UpperCamelCase :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tAny:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tint =\tTFCLIPVisionModel(UpperCamelCase , name=\"\"\"vision_model\"\"\" )\n lowerCAmelCase__ :\t\t\tList[str] =\tTFBertModel(UpperCamelCase , name=\"\"\"text_model\"\"\" )\n return vision_model, text_model\n\n\n\n\n\n\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[Any] )\t\t\t->\t\t\t\t\t\tOptional[int]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tstr =\tTFCLIPVisionModelTester(self )\n lowerCAmelCase__ :\t\t\tint =\tTFBertModelTester(self )\n lowerCAmelCase__ :\t\t\tstr =\tclip_model_tester.prepare_config_and_inputs()\n lowerCAmelCase__ :\t\t\tOptional[int] =\tbert_model_tester.prepare_config_and_inputs()\n\n lowerCAmelCase__ , lowerCAmelCase__ :\t\t\tDict =\tvision_config_and_inputs\n\n (\n (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , (\n lowerCAmelCase__\n ) , \n ) :\t\t\tstr =\ttext_config_and_inputs\n\n return {\n \"text_config\": text_config,\n \"vision_config\": vision_config,\n \"pixel_values\": pixel_values,\n \"attention_mask\": input_mask,\n \"input_ids\": input_ids,\n \"text_token_type_ids\": token_type_ids,\n \"text_sequence_labels\": sequence_labels,\n \"text_token_labels\": token_labels,\n \"text_choice_labels\": choice_labels,\n }\n\n\n\n\n\n\n@require_vision\n@require_tf\nclass _lowerCamelCase (\t\t\t\t\tunittest.TestCase\t\t\t\t\t\t):\n\n\n\n\n\n\n @slow\n def \t_lowerCAmelCase (\t\tself :\t\tOptional[int] )\t\t\t->\t\t\t\t\t\tOptional[int]:\n\n \"\"\"simple docstring\"\"\"\n lowerCAmelCase__ :\t\t\tList[str] =\tTFVisionTextDualEncoderModel.from_pretrained(\n \"\"\"clip-italian/clip-italian\"\"\" , logit_scale_init_value=1.0 , from_pt=UpperCamelCase )\n lowerCAmelCase__ :\t\t\tAny =\tVisionTextDualEncoderProcessor.from_pretrained(\"\"\"clip-italian/clip-italian\"\"\" )\n\n lowerCAmelCase__ :\t\t\tAny =\tImage.open(\"\"\"./tests/fixtures/tests_samples/COCO/000000039769.png\"\"\" )\n lowerCAmelCase__ :\t\t\tTuple =\tprocessor(\n text=[\"\"\"una foto di un gatto\"\"\", \"\"\"una foto di un cane\"\"\"] , images=UpperCamelCase , padding=UpperCamelCase , return_tensors=\"\"\"np\"\"\" )\n\n lowerCAmelCase__ :\t\t\tTuple =\tmodel(**UpperCamelCase )\n\n # verify the logits\n self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) )\n self.assertEqual(\n outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , )\n\n lowerCAmelCase__ :\t\t\tList[Any] =\tnp.array([[1.228_4727, 0.310_4122]] )\n\n self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , UpperCamelCase , atol=1E-3 ) )\n\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":212,"string":"212"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":214,"cells":{"code":{"kind":"string","value":"import cva\rimport numpy as np\r\r\r\r\r\r\rclass \t\ta__\t\t\t\t\t\t:\r\r\t\t\t\t\tdef __init__( self : Any,_A : float,_A : int ):\r\r\r\r\r\r\r\r\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\t\t\t\t\t\t\tif k in (0.04, 0.06):\r\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tUnion[str, Any]\t\t\t\t = k\r\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tstr\t\t\t\t = window_size\r\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\traise ValueError(\"invalid k value\" )\r\r\t\t\t\t\tdef __str__( self : Union[str, Any] ):\r\r\r\r\r\r\r\r\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\t\t\t\t\t\t\treturn str(self.k )\r\r\r\r\r\r\r\t\t\t\t\tdef \t\t\t\t__UpperCamelCase ( self : Optional[int],_A : str ):\r\r\r\r\r\r\r\r\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tDict\t\t\t\t = cva.imread(_A,0 )\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :\t\tint\t\t\t\t = img.shape\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tlist[list[int]]\t\t\t\t = []\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tOptional[Any]\t\t\t\t = img.copy()\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tOptional[Any]\t\t\t\t = cva.cvtColor(_A,cva.COLOR_GRAY2RGB )\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ :\t\tList[Any]\t\t\t\t = np.gradient(_A )\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tstr\t\t\t\t = dx**2\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tOptional[Any]\t\t\t\t = dy**2\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tOptional[Any]\t\t\t\t = dx * dy\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tOptional[Any]\t\t\t\t = 0.04\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tstr\t\t\t\t = self.window_size // 2\r\t\t\t\t\t\t\tfor y in range(_A,h - offset ):\r\t\t\t\t\t\t\t\t\tfor x in range(_A,w - offset ):\r\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tUnion[str, Any]\t\t\t\t = ixx[\r\t\t\t\t\t\t\t\t\t\t\t y - offset : y + offset + 1, x - offset : x + offset + 1\r\t\t\t\t\t\t\t\t\t\t\t].sum()\r\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tint\t\t\t\t = iyy[\r\t\t\t\t\t\t\t\t\t\t\t y - offset : y + offset + 1, x - offset : x + offset + 1\r\t\t\t\t\t\t\t\t\t\t\t].sum()\r\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tOptional[int]\t\t\t\t = ixy[\r\t\t\t\t\t\t\t\t\t\t\t y - offset : y + offset + 1, x - offset : x + offset + 1\r\t\t\t\t\t\t\t\t\t\t\t].sum()\r\r\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tint\t\t\t\t = (wxx * wyy) - (wxy**2)\r\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tOptional[int]\t\t\t\t = wxx + wyy\r\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_ :\t\tList[Any]\t\t\t\t = det - k * (trace**2)\r\t\t\t\t\t\t\t\t\t\t\t# Can change the value\r\t\t\t\t\t\t\t\t\t\t\tif r > 0.5:\r\t\t\t\t\t\t\t\t\t\t\t\t\tcorner_list.append([x, y, r] )\r\t\t\t\t\t\t\t\t\t\t\t\t\tcolor_img.itemset((y, x, 0),0 )\r\t\t\t\t\t\t\t\t\t\t\t\t\tcolor_img.itemset((y, x, 1),0 )\r\t\t\t\t\t\t\t\t\t\t\t\t\tcolor_img.itemset((y, x, 2),255 )\r\t\t\t\t\t\t\treturn color_img, corner_list\r\r\rif __name__ == \"__main__\":\r\t\t__lowerCamelCase\t\t\t\t\t:\tOptional[int] = HarrisCorner(0.04, 3)\r\t\t__lowerCamelCase ,\t\t\t\t\t\t__lowerCamelCase\t\t\t\t\t:\tList[Any] = edge_detect.detect('''path_to_image''')\r\t\tcva.imwrite('''detect.png''', color_img)\r"},"code_codestyle":{"kind":"number","value":18,"string":"18"},"style_context":{"kind":"string","value":"import unittest\r\nfrom pathlib import Path\r\nfrom tempfile import TemporaryDirectory\r\n\r\nfrom transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available\r\nfrom transformers.models.gpta.tokenization_gpta import GPTaTokenizer\r\nfrom transformers.testing_utils import require_keras_nlp, require_tf, slow\r\n\r\n\r\nif is_tf_available():\r\n\t\t\t\t\timport tensorflow as tf\r\n\r\nif is_keras_nlp_available():\r\n\t\t\t\t\tfrom transformers.models.gpta import TFGPTaTokenizer\r\n\r\n\r\n__UpperCamelCase\t\t: Optional[Any]\t\t\t\t\t\t\t\t\t= ['gpt2']\r\n__UpperCamelCase\t\t: str\t\t\t\t\t\t\t\t\t= 'gpt2'\r\n\r\nif is_tf_available():\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tclass \t\t\t\t\tlowercase__\t\t\t\t\t\t( tf.Module):\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tdef __init__( self\t:\t\t\t\tOptional[Any] ,\t\tUpperCamelCase__\t:\t\t\t\tUnion[str, Any]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttokenizer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: int\t\t\t\t\t\t\t=\t\t\t\t\t\t\tAutoConfig.from_pretrained(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t=\t\t\t\t\t\t\tTFGPTaLMHeadModel.from_config(UpperCamelCase__\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t@tf.function(input_signature=(tf.TensorSpec((None,) ,\t\ttf.string ,\t\tname='''text'''\t\t\t\t\t\t),)\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\tdef __A ( self\t:\t\t\t\tstr ,\t\tUpperCamelCase__\t:\t\t\t\tint\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\tself.tokenizer(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttokenized['''input_ids'''].to_tensor()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Any\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf.cast(input_ids_dense > 0 ,\t\ttf.intaa\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\tself.model(input_ids=UpperCamelCase__ ,\t\tattention_mask=UpperCamelCase__\t\t\t\t\t\t)['''logits''']\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn outputs\r\n\r\n\r\n\r\n\r\n\r\n@require_tf\r\n@require_keras_nlp\r\nclass \t\t\t\t\tlowercase__\t\t\t\t\t\t( unittest.TestCase):\r\n\r\n\r\n\t\t\t\t\t\tdef __A ( self\t:\t\t\t\tint\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tsuper().setUp()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\t[GPTaTokenizer.from_pretrained(UpperCamelCase__\t\t\t\t\t\t) for checkpoint in (TOKENIZER_CHECKPOINTS)]\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str]\t\t\t\t\t\t\t=\t\t\t\t\t\t\t[TFGPTaTokenizer.from_pretrained(UpperCamelCase__\t\t\t\t\t\t) for checkpoint in TOKENIZER_CHECKPOINTS]\r\n\t\t\t\t\t\t\t\t\t\t\t\tassert len(self.tokenizers\t\t\t\t\t\t) == len(self.tf_tokenizers\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t=\t\t\t\t\t\t\t[\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''This is a straightforward English test sentence.''',\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''This one has some weird characters\\rto\\nsee\\r\\nif those\\u00E9break things.''',\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''Now we\\'re going to add some Chinese: 一 二 三 一二三''',\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''And some much more rare Chinese: 齉 堃 齉堃''',\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''Je vais aussi écrire en français pour tester les accents''',\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',\r\n\t\t\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t=\t\t\t\t\t\t\tlist(zip(self.test_sentences ,\t\tself.test_sentences[::-1]\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\tdef __A ( self\t:\t\t\t\tstr\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor tokenizer, tf_tokenizer in zip(self.tokenizers ,\t\tself.tf_tokenizers\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor test_inputs in self.test_sentences:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttokenizer([test_inputs] ,\t\treturn_tensors='''tf'''\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Any\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf_tokenizer([test_inputs]\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in python_outputs.keys():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# convert them to numpy to avoid messing with ragged tensors\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: int\t\t\t\t\t\t\t=\t\t\t\t\t\t\tpython_outputs[key].numpy()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: int\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf_outputs[key].numpy()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(tf.reduce_all(tf.cast(UpperCamelCase__ ,\t\ttf.intaa\t\t\t\t\t\t) == tf_outputs_values\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\t@slow\r\n\t\t\t\t\t\tdef __A ( self\t:\t\t\t\tOptional[Any]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor tf_tokenizer in self.tf_tokenizers:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf.function(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor test_inputs in self.test_sentences:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf.constant(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str]\t\t\t\t\t\t\t=\t\t\t\t\t\t\tcompiled_tokenizer(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf_tokenizer(UpperCamelCase__\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in eager_outputs.keys():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\t@slow\r\n\t\t\t\t\t\tdef __A ( self\t:\t\t\t\tOptional[int]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor tf_tokenizer in self.tf_tokenizers:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: str\t\t\t\t\t\t\t=\t\t\t\t\t\t\tModelToSave(tokenizer=UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf.convert_to_tensor([self.test_sentences[0]]\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\tmodel.serving(UpperCamelCase__\t\t\t\t\t\t) # Build model with some sample inputs\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith TemporaryDirectory() as tempdir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str]\t\t\t\t\t\t\t=\t\t\t\t\t\t\tPath(UpperCamelCase__\t\t\t\t\t\t) / '''saved.model'''\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttf.saved_model.save(UpperCamelCase__ ,\t\tUpperCamelCase__ ,\t\tsignatures={'''serving_default''': model.serving}\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: str\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf.saved_model.load(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: int\t\t\t\t\t\t\t=\t\t\t\t\t\t\tloaded_model.signatures['''serving_default'''](UpperCamelCase__\t\t\t\t\t\t)['''output_0''']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# We may see small differences because the loaded model is compiled, so we need an epsilon for the test\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(tf.reduce_all(out == loaded_output\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\t@slow\r\n\t\t\t\t\t\tdef __A ( self\t:\t\t\t\tList[str]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor tf_tokenizer in self.tf_tokenizers:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf.convert_to_tensor([self.test_sentences[0]]\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf_tokenizer(UpperCamelCase__\t\t\t\t\t\t) # Build model with some sample inputs\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf_tokenizer.get_config()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t=\t\t\t\t\t\t\tTFGPTaTokenizer.from_config(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: str\t\t\t\t\t\t\t=\t\t\t\t\t\t\tmodel_from_config(UpperCamelCase__\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in from_config_output.keys():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(tf.reduce_all(from_config_output[key] == out[key]\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\t\t\t\t\t\t@slow\r\n\t\t\t\t\t\tdef __A ( self\t:\t\t\t\tOptional[int]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor tf_tokenizer in self.tf_tokenizers:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# for the test to run\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t=\t\t\t\t\t\t\t12_3123\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor max_length in [3, 5, 1024]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf.convert_to_tensor([self.test_sentences[0]]\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t=\t\t\t\t\t\t\ttf_tokenizer(UpperCamelCase__ ,\t\tmax_length=UpperCamelCase__\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t=\t\t\t\t\t\t\tout['''input_ids'''].numpy().shape[1]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert out_length == max_length\r\n\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":182,"string":"182"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":215,"cells":{"code":{"kind":"string","value":"\r\r\r\r\r\r\r\"\"\"simple docstring\"\"\"\r\r\r\rfrom __future__ import annotations\r\rfrom decimal import Decimal\r\rfrom numpy import array\r\rdef \t\t\t_snake_case (\t\t\t\t\tlowerCamelCase__ : list[list[float]] ) -> list[list[float]]:\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=Decimal\r\r\t\t\t\t\t\t\t# Check if the provided matrix has 2 rows and 2 columns\r\t\t\t\t\t\t\t# since this implementation only works for 2x2 matrices\r\t\t\t\t\t\t\tif len(lowerCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Calculate the determinant of the matrix\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t=float(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif determinant == 0:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"This matrix has no inverse.\" )\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Creates a copy of the matrix with swapped positions of the elements\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t=[[0.0, 0.0], [0.0, 0.0]]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t\t,\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t=matrix[1][1], matrix[0][0]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t\t,\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t\t=-matrix[1][0], -matrix[0][1]\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Calculate the inverse of the matrix\r\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn [\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t [(float(d(lowerCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\r\t\t\t\t\t\t\telif (\r\t\t\t\t\t\t\t len(lowerCamelCase__ ) == 3\r\t\t\t\t\t\t\t and len(matrix[0] ) == 3\r\t\t\t\t\t\t\t and len(matrix[1] ) == 3\r\t\t\t\t\t\t\t and len(matrix[2] ) == 3\r\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Calculate the determinant of the matrix using Sarrus rule\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t\t=float(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t - (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ) )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif determinant == 0:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"This matrix has no inverse.\" )\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Creating cofactor matrix\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t=[\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t [d(0.0 ), d(0.0 ), d(0.0 )],\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t [d(0.0 ), d(0.0 ), d(0.0 )],\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t [d(0.0 ), d(0.0 ), d(0.0 )],\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t=(d(matrix[1][1] ) * d(matrix[2][2] )) - (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t d(matrix[1][2] ) * d(matrix[2][1] )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t=-(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=(d(matrix[1][0] ) * d(matrix[2][1] )) - (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t d(matrix[1][1] ) * d(matrix[2][0] )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t\t=-(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t=(d(matrix[0][0] ) * d(matrix[2][2] )) - (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t d(matrix[0][2] ) * d(matrix[2][0] )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t=-(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=(d(matrix[0][1] ) * d(matrix[1][2] )) - (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t d(matrix[0][2] ) * d(matrix[1][1] )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t=-(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] ))\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=(d(matrix[0][0] ) * d(matrix[1][1] )) - (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t d(matrix[0][1] ) * d(matrix[1][0] )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Transpose the cofactor matrix (Adjoint matrix)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t=array(lowerCamelCase__ )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor i in range(3 ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor j in range(3 ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t=cofactor_matrix[j][i]\r\r # Inverse of the matrix using the formula (1/determinant) * adjoint matrix\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tTuple\t\t\t\t\t\t\t\t\t=array(lowerCamelCase__ )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor i in range(3 ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor j in range(3 ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tinverse_matrix[i][j] /= d(lowerCamelCase__ )\r\r # Calculate the inverse of the matrix\r\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn [[float(d(lowerCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix]\r\t\t\t\t\t\t\traise ValueError(\"Please provide a matrix of size 2x2 or 3x3.\" )\r\r\r\r"},"code_codestyle":{"kind":"number","value":209,"string":"209"},"style_context":{"kind":"string","value":"\r\r\r\r\r\r\r\"\"\"simple docstring\"\"\"\r\r\r\rdef \t\t\t_snake_case (\t\t\t\t\tlowerCamelCase__ : Optional[Any] ) -> Optional[int]:\r\t\t\t\t\t\t\tif not head:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn True\r\t\t\t\t\t\t\t# split the list to two parts\r\t\t\t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t\t,\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t=head.next, head\r\t\t\t\t\t\t\twhile fast and fast.next:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t=fast.next.next\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t=slow.next\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tTuple\t\t\t\t\t\t\t\t\t=slow.next\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t=None # Don't forget here! But forget still works!\r\t\t\t\t\t\t\t# reverse the second part\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=None\r\t\t\t\t\t\t\twhile second:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t=second.next\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t=node\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t=second\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t=nxt\r\t\t\t\t\t\t\t# compare two parts\r\t\t\t\t\t\t\t# second part has the same or one less node\r\t\t\t\t\t\t\twhile node:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif node.val != head.val:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn False\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=node.next\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t=head.next\r\t\t\t\t\t\t\treturn True\r\rdef \t\t\t_snake_case (\t\t\t\t\tlowerCamelCase__ : str ) -> Optional[int]:\r\t\t\t\t\t\t\tif not head or not head.next:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn True\r\r\t\t\t\t\t\t\t# 1. Get the midpoint (slow)\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=head\r\t\t\t\t\t\t\twhile fast and fast.next:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t\t\t\t\t\t\t,\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t=fast.next.next, slow.next\r\r\t\t\t\t\t\t\t# 2. Push the second half into the stack\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t\t=[slow.val]\r\t\t\t\t\t\t\twhile slow.next:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t\t=slow.next\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tstack.append(slow.val )\r\r\t\t\t\t\t\t\t# 3. Comparison\r\t\t\t\t\t\t\twhile stack:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif stack.pop() != cur.val:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn False\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t=cur.next\r\r\t\t\t\t\t\t\treturn True\r\rdef \t\t\t_snake_case (\t\t\t\t\tlowerCamelCase__ : Dict ) -> Optional[Any]:\r\t\t\t\t\t\t\tif not head or not head.next:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn True\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t={}\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t\t=0\r\t\t\t\t\t\t\twhile head:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif head.val in d:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\td[head.val].append(lowerCamelCase__ )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t=[pos]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t=head.next\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tpos += 1\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t=pos - 1\r\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t=0\r\t\t\t\t\t\t\tfor v in d.values():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif len(lowerCamelCase__ ) % 2 != 0:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmiddle += 1\r\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase_\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t=0\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor i in range(0 ,\t\t\t\t\t\tlen(lowerCamelCase__ ) ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif v[i] + v[len(lowerCamelCase__ ) - 1 - step] != checksum:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn False\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstep += 1\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif middle > 1:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn False\r\t\t\t\t\t\t\treturn True\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":209,"string":"209"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":216,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef lowercase\t\t\t(\t\t\t\tA_ , A_ )-> float:\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n if mass < 0:\r\n raise ValueError(\"The mass of a body cannot be negative\" )\r\n return 0.5 * mass * abs(A_ ) * abs(A_ )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import doctest\r\n\r\n doctest.testmod(verbose=True)\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":40,"string":"40"},"style_context":{"kind":"string","value":"\n'''simple docstring'''\nfrom scipy.stats import spearmanr\n\nimport datasets\n\n\n__lowerCAmelCase \t\t\t\t\t\t\t= '\\nThe Spearman rank-order correlation coefficient is a measure of the\\nrelationship between two datasets. Like other correlation coefficients,\\nthis one varies between -1 and +1 with 0 implying no correlation.\\nPositive correlations imply that as data in dataset x increases, so\\ndoes data in dataset y. Negative correlations imply that as x increases,\\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\\n\\nUnlike the Pearson correlation, the Spearman correlation does not\\nassume that both datasets are normally distributed.\\n\\nThe p-value roughly indicates the probability of an uncorrelated system\\nproducing datasets that have a Spearman correlation at least as extreme\\nas the one computed from these datasets. The p-values are not entirely\\nreliable but are probably reasonable for datasets larger than 500 or so.\\n'\n\n__lowerCAmelCase \t\t\t\t\t\t\t= '\\nArgs:\\n predictions (`List[float]`): Predicted labels, as returned by a model.\\n references (`List[float]`): Ground truth labels.\\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\\n only the spearmanr score. Defaults to `False`.\\nReturns:\\n spearmanr (`float`): Spearman correlation coefficient.\\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\\nExamples:\\n Example 1:\\n >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\\n >>> print(results)\\n {\\'spearmanr\\': -0.7}\\n\\n Example 2:\\n >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\\n ... predictions=[10, 9, 2.5, 6, 4],\\n ... return_pvalue=True)\\n >>> print(results[\\'spearmanr\\'])\\n -0.7\\n >>> print(round(results[\\'spearmanr_pvalue\\'], 2))\\n 0.19\\n'\n\n__lowerCAmelCase \t\t\t\t\t\t\t= r'\\\\n@book{kokoska2000crc,\\n title={CRC standard probability and statistics tables and formulae},\\n author={Kokoska, Stephen and Zwillinger, Daniel},\\n year={2000},\\n publisher={Crc Press}\\n}\\n@article{2020SciPy-NMeth,\\n author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\\n Bright, Jonathan and {van der Walt}, St{\\'e}fan J. and\\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\\n Kern, Robert and Larson, Eric and Carey, C J and\\n Polat, {\\.I}lhan and Feng, Yu and Moore, Eric W. and\\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\\n Harris, Charles R. and Archibald, Anne M. and\\n Ribeiro, Ant{\\^o}nio H. and Pedregosa, Fabian and\\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\\n Computing in Python}},\\n journal = {Nature Methods},\\n year = {2020},\\n volume = {17},\\n pages = {261--272},\\n adsurl = {https://rdcu.be/b08Wh},\\n doi = {10.1038/s41592-019-0686-2},\\n}\\n'\n\n\n@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,\t\t\t\t\t\t\t_KWARGS_DESCRIPTION )\nclass \t\t\t_lowerCAmelCase ( datasets.Metric ):\n\n\n\n\n\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\t\t\t\t\t\t\tdef lowercase\t\t\t\t\t\t\t(self ) -> Optional[Any]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn datasets.MetricInfo(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"predictions\"\"\": datasets.Value(\"\"\"float\"\"\" ),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"references\"\"\": datasets.Value(\"\"\"float\"\"\" ),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t } ) , reference_urls=[\"\"\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html\"\"\"] , )\n\n\n\n\n\n\t\t\t\t\t\t\tdef lowercase\t\t\t\t\t\t\t(self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=False ) -> Optional[Any]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_snake_case = spearmanr(UpperCAmelCase , UpperCAmelCase )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif return_pvalue:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn {\"spearmanr\": results[0], \"spearmanr_pvalue\": results[1]}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn {\"spearmanr\": results[0]}"},"style_context_codestyle":{"kind":"number","value":341,"string":"341"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":217,"cells":{"code":{"kind":"string","value":"\r\r\r\r\r\r\"\"\"simple docstring\"\"\"\r\r\rdef SCREAMING_SNAKE_CASE_ (\tsnake_case : int\t\t\t\t\t\t, snake_case : int\t\t\t\t\t\t, snake_case : Tuple=False\t\t)->\t\tList[Any]:\r\r if isinstance(snake_case\t\t\t\t\t\t, snake_case\t\t) and isinstance(snake_case\t\t\t\t\t\t, snake_case\t\t):\r _lowerCamelCase = len(set_a.intersection(snake_case\t\t)\t\t)\r\r if alternative_union:\r _lowerCamelCase = len(snake_case\t\t) + len(snake_case\t\t)\r else:\r _lowerCamelCase = len(set_a.union(snake_case\t\t)\t\t)\r\r return intersection / union\r\r if isinstance(snake_case\t\t\t\t\t\t, (list, tuple)\t\t) and isinstance(snake_case\t\t\t\t\t\t, (list, tuple)\t\t):\r _lowerCamelCase = [element for element in set_a if element in set_b]\r\r if alternative_union:\r _lowerCamelCase = len(snake_case\t\t) + len(snake_case\t\t)\r return len(snake_case\t\t) / union\r else:\r _lowerCamelCase = set_a + [element for element in set_b if element not in set_a]\r return len(snake_case\t\t) / len(snake_case\t\t)\r\r return len(snake_case\t\t) / len(snake_case\t\t)\r return None\r\r\rif __name__ == \"__main__\":\r A_\t\t\t\t\t:\t\t\t\tDict \t\t\t\t\t\t\t={\"\"\"a\"\"\", \"\"\"b\"\"\", \"\"\"c\"\"\", \"\"\"d\"\"\", \"\"\"e\"\"\"}\r A_\t\t\t\t\t:\t\t\t\tList[str] \t\t\t\t\t\t\t={\"\"\"c\"\"\", \"\"\"d\"\"\", \"\"\"e\"\"\", \"\"\"f\"\"\", \"\"\"h\"\"\", \"\"\"i\"\"\"}\r print(jaccard_similarity(set_a, set_b))\r\r\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":365,"string":"365"},"style_context":{"kind":"string","value":"\n\n\n\n\n\n\"\"\"simple docstring\"\"\"\n\n\nimport copy\n\nfrom ...configuration_utils import PretrainedConfig\nfrom ...utils import logging\nfrom ..auto import CONFIG_MAPPING\n\n\nA_\t\t\t\t\t:\t\t\t\tint \t\t\t\t\t\t\t=logging.get_logger(__name__)\n\nA_\t\t\t\t\t:\t\t\t\tTuple \t\t\t\t\t\t\t={\n \"\"\"ut/deta\"\"\": \"\"\"https://huggingface.co/ut/deta/resolve/main/config.json\"\"\",\n}\n\n\n\n\n\n\n\nclass __a ( lowerCAmelCase__\t\t):\n SCREAMING_SNAKE_CASE__\t\t\t:\t\t\t\tint\t\t\t= \"deta\"\n SCREAMING_SNAKE_CASE__\t\t\t:\t\t\t\tUnion[str, Any]\t\t\t= {\n \"hidden_size\": \"d_model\",\n \"num_attention_heads\": \"encoder_attention_heads\",\n }\n\n\n\n def __init__(\tself ,\t\t\t\t\ta__=None ,\t\t\t\t\ta__=9_00 ,\t\t\t\t\ta__=20_48 ,\t\t\t\t\ta__=6 ,\t\t\t\t\ta__=20_48 ,\t\t\t\t\ta__=8 ,\t\t\t\t\ta__=6 ,\t\t\t\t\ta__=10_24 ,\t\t\t\t\ta__=8 ,\t\t\t\t\ta__=0.0 ,\t\t\t\t\ta__=True ,\t\t\t\t\ta__=\"relu\" ,\t\t\t\t\ta__=2_56 ,\t\t\t\t\ta__=0.1 ,\t\t\t\t\ta__=0.0 ,\t\t\t\t\ta__=0.0 ,\t\t\t\t\ta__=0.02 ,\t\t\t\t\ta__=1.0 ,\t\t\t\t\ta__=True ,\t\t\t\t\ta__=False ,\t\t\t\t\ta__=\"sine\" ,\t\t\t\t\ta__=5 ,\t\t\t\t\ta__=4 ,\t\t\t\t\ta__=4 ,\t\t\t\t\ta__=True ,\t\t\t\t\ta__=3_00 ,\t\t\t\t\ta__=True ,\t\t\t\t\ta__=True ,\t\t\t\t\ta__=1 ,\t\t\t\t\ta__=5 ,\t\t\t\t\ta__=2 ,\t\t\t\t\ta__=1 ,\t\t\t\t\ta__=1 ,\t\t\t\t\ta__=5 ,\t\t\t\t\ta__=2 ,\t\t\t\t\ta__=0.1 ,\t\t\t\t\ta__=0.25 ,\t\t\t\t\t**a__ ,\t\t\t\t\t):\n if backbone_config is None:\n logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' )\n _lowerCamelCase = CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] )\n else:\n if isinstance(a__ ,\t\t\t\t\ta__ ):\n _lowerCamelCase = backbone_config.pop('model_type' )\n _lowerCamelCase = CONFIG_MAPPING[backbone_model_type]\n _lowerCamelCase = config_class.from_dict(a__ )\n\n _lowerCamelCase = backbone_config\n _lowerCamelCase = num_queries\n _lowerCamelCase = max_position_embeddings\n _lowerCamelCase = d_model\n _lowerCamelCase = encoder_ffn_dim\n _lowerCamelCase = encoder_layers\n _lowerCamelCase = encoder_attention_heads\n _lowerCamelCase = decoder_ffn_dim\n _lowerCamelCase = decoder_layers\n _lowerCamelCase = decoder_attention_heads\n _lowerCamelCase = dropout\n _lowerCamelCase = attention_dropout\n _lowerCamelCase = activation_dropout\n _lowerCamelCase = activation_function\n _lowerCamelCase = init_std\n _lowerCamelCase = init_xavier_std\n _lowerCamelCase = encoder_layerdrop\n _lowerCamelCase = auxiliary_loss\n _lowerCamelCase = position_embedding_type\n # deformable attributes\n _lowerCamelCase = num_feature_levels\n _lowerCamelCase = encoder_n_points\n _lowerCamelCase = decoder_n_points\n _lowerCamelCase = two_stage\n _lowerCamelCase = two_stage_num_proposals\n _lowerCamelCase = with_box_refine\n _lowerCamelCase = assign_first_stage\n if two_stage is True and with_box_refine is False:\n raise ValueError('If two_stage is True, with_box_refine must be True.' )\n # Hungarian matcher\n _lowerCamelCase = class_cost\n _lowerCamelCase = bbox_cost\n _lowerCamelCase = giou_cost\n # Loss coefficients\n _lowerCamelCase = mask_loss_coefficient\n _lowerCamelCase = dice_loss_coefficient\n _lowerCamelCase = bbox_loss_coefficient\n _lowerCamelCase = giou_loss_coefficient\n _lowerCamelCase = eos_coefficient\n _lowerCamelCase = focal_alpha\n super().__init__(is_encoder_decoder=a__ ,\t\t\t\t\t**a__ )\n\n\n\n @property\n def \t\t\t\t\t\tsnake_case_ (\tself ):\n return self.encoder_attention_heads\n\n\n\n @property\n def \t\t\t\t\t\tsnake_case_ (\tself ):\n return self.d_model\n\n\n\n def \t\t\t\t\t\tsnake_case_ (\tself ):\n _lowerCamelCase = copy.deepcopy(self.__dict__ )\n _lowerCamelCase = self.backbone_config.to_dict()\n _lowerCamelCase = self.__class__.model_type\n return output\n\n\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":80,"string":"80"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":218,"cells":{"code":{"kind":"string","value":"\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\ndef \tlowercase__\t\t( snake_case_\t\t\t\t\t:list ,\t\t\t\t\t\tsnake_case_\t\t\t\t\t:list ,\t\t\t\t\t\tsnake_case_\t\t\t\t\t:int ):\r\n\tif len(snake_case_ ) != len(snake_case_ ):\r\n\t\traise ValueError('''The length of profit and weight must be same.''' )\r\n\tif max_weight <= 0:\r\n\t\traise ValueError('''max_weight must greater than zero.''' )\r\n\tif any(p < 0 for p in profit ):\r\n\t\traise ValueError('''Profit can not be negative.''' )\r\n\tif any(w < 0 for w in weight ):\r\n\t\traise ValueError('''Weight can not be negative.''' )\r\n\r\n\t# List created to store profit gained for the 1kg in case of each weight\r\n\t# respectively. Calculate and append profit/weight for each element.\r\n\t__UpperCAmelCase\t\t\t\t\t\t\t= [p / w for p, w in zip(snake_case_ ,\t\t\t\t\t\tsnake_case_ )]\r\n\r\n\t# Creating a copy of the list and sorting profit/weight in ascending order\r\n\t__UpperCAmelCase\t\t\t\t\t\t\t= sorted(snake_case_ )\r\n\r\n\t# declaring useful variables\r\n\t__UpperCAmelCase\t\t\t\t\t\t\t= len(snake_case_ )\r\n\t__UpperCAmelCase\t\t\t\t\t\t\t= 0\r\n\t__UpperCAmelCase\t\t\t\t\t\t\t= 0\r\n\t__UpperCAmelCase\t\t\t\t\t\t\t= 0\r\n\r\n\t# loop till the total weight do not reach max limit e.g. 15 kg and till i= weight[index]:\r\n\t\t\tlimit += weight[index]\r\n\t\t\t# Adding profit gained for the given weight 1 ===\r\n\t\t\t# weight[index]/weight[index]\r\n\t\t\tgain += 1 * profit[index]\r\n\t\telse:\r\n\t\t\t# Since the weight encountered is greater than limit, therefore take the\r\n\t\t\t# required number of remaining kgs and calculate profit for it.\r\n\t\t\t# weight remaining / weight[index]\r\n\t\t\tgain += (max_weight - limit) / weight[index] * profit[index]\r\n\t\t\tbreak\r\n\t\ti += 1\r\n\treturn gain\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\tprint(\r\n\t\t\t\t 'Input profits, weights, and then max_weight (all positive ints) separated by '\r\n\t\t\t\t 'spaces.'\r\n\t\t\t\t)\r\n\r\n\t\t\t\t_lowercase\t\t\t\t\t: str\t\t\t\t =\t\t[int(x) for x in input('Input profits separated by spaces: ').split()]\r\n\t\t\t\t_lowercase\t\t\t\t\t: str\t\t\t\t =\t\t[int(x) for x in input('Input weights separated by spaces: ').split()]\r\n\t\t\t\t_lowercase\t\t\t\t\t: Any\t\t\t\t =\t\tint(input('Max weight allowed: '))\r\n\r\n\t\t\t\t# Function Call\r\n\t\t\t\tcalc_profit(profit, weight, max_weight)\r\n"},"code_codestyle":{"kind":"number","value":332,"string":"332"},"style_context":{"kind":"string","value":"\nfrom typing import Optional\n\nimport torch\nimport torch.utils.checkpoint\nfrom torch import Tensor, nn\nfrom torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss\n\nfrom ...activations import ACTaFN\nfrom ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward\nfrom ...modeling_outputs import (\n BaseModelOutputWithNoAttention,\n BaseModelOutputWithPoolingAndNoAttention,\n ImageClassifierOutputWithNoAttention,\n)\nfrom ...modeling_utils import PreTrainedModel\nfrom ...utils import logging\nfrom .configuration_regnet import RegNetConfig\n\n\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\tlogging.get_logger(__name__)\n\n# General docstring\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\t\"\"\"RegNetConfig\"\"\"\n\n# Base docstring\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\t\"\"\"facebook/regnet-y-040\"\"\"\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\t[1, 1088, 7, 7]\n\n# Image classification docstring\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\t\"\"\"facebook/regnet-y-040\"\"\"\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\t\"\"\"tabby, tabby cat\"\"\"\n\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\t[\n \"\"\"facebook/regnet-y-040\"\"\",\n # See all regnet models at https://huggingface.co/models?filter=regnet\n]\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : str , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 3 , _UpperCAmelCase : int = 1 , _UpperCAmelCase : int = 1 , _UpperCAmelCase : Optional[str] = \"relu\" , )\t\t\t\t\t\t->\t\tOptional[Any]:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.Convad(\n\t\t\t\t\t\t\t\t\t\t\t _UpperCAmelCase , _UpperCAmelCase , kernel_size=_UpperCAmelCase , stride=_UpperCAmelCase , padding=kernel_size // 2 , groups=_UpperCAmelCase , bias=_UpperCAmelCase , )\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.BatchNormad(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tACTaFN[activation] if activation is not None else nn.Identity()\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : Tuple , _UpperCAmelCase : List[str]\t\t\t\t)\t\t\t\t\t\t->\t\tstr:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.convolution(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.normalization(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.activation(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn hidden_state\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : Union[str, Any] , _UpperCAmelCase : RegNetConfig\t\t\t\t)\t\t\t\t\t\t->\t\tAny:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tRegNetConvLayer(\n\t\t\t\t\t\t\t\t\t\t\t config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tconfig.num_channels\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : Optional[Any] , _UpperCAmelCase : Any\t\t\t\t)\t\t\t\t\t\t->\t\tUnion[str, Any]:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tpixel_values.shape[1]\n\t\t\t\t\t\t\t\t\t\t\tif num_channels != self.num_channels:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.embedder(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn hidden_state\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : List[str] , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 2\t\t\t\t)\t\t\t\t\t\t->\t\tOptional[int]:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.Convad(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , stride=_UpperCAmelCase , bias=_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.BatchNormad(_UpperCAmelCase\t\t\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : int , _UpperCAmelCase : Tensor\t\t\t\t)\t\t\t\t\t\t->\t\tTensor:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.convolution(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.normalization(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn hidden_state\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : int , _UpperCAmelCase : int , _UpperCAmelCase : int\t\t\t\t)\t\t\t\t\t\t->\t\tstr:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.AdaptiveAvgPoolad((1, 1)\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.Sequential(\n\t\t\t\t\t\t\t\t\t\t\t nn.Convad(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1\t\t\t\t) , nn.ReLU() , nn.Convad(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1\t\t\t\t) , nn.Sigmoid() , )\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : str , _UpperCAmelCase : Dict\t\t\t\t)\t\t\t\t\t\t->\t\tstr:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.pooler(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.attention(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\thidden_state * attention\n\t\t\t\t\t\t\t\t\t\t\treturn hidden_state\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : Optional[int] , _UpperCAmelCase : RegNetConfig , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 1\t\t\t\t)\t\t\t\t\t\t->\t\tTuple:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tin_channels != out_channels or stride != 1\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tmax(1 , out_channels // config.groups_width\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\t RegNetShortCut(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase\t\t\t\t) if should_apply_shortcut else nn.Identity()\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.Sequential(\n\t\t\t\t\t\t\t\t\t\t\t RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=config.hidden_act\t\t\t\t) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase , groups=_UpperCAmelCase , activation=config.hidden_act\t\t\t\t) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=_UpperCAmelCase\t\t\t\t) , )\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tACTaFN[config.hidden_act]\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : List[str] , _UpperCAmelCase : Tuple\t\t\t\t)\t\t\t\t\t\t->\t\tList[Any]:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\thidden_state\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.layer(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.shortcut(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\thidden_state += residual\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.activation(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn hidden_state\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : Union[str, Any] , _UpperCAmelCase : RegNetConfig , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 1\t\t\t\t)\t\t\t\t\t\t->\t\tOptional[Any]:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tin_channels != out_channels or stride != 1\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tmax(1 , out_channels // config.groups_width\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\t RegNetShortCut(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase\t\t\t\t) if should_apply_shortcut else nn.Identity()\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.Sequential(\n\t\t\t\t\t\t\t\t\t\t\t RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=config.hidden_act\t\t\t\t) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase , groups=_UpperCAmelCase , activation=config.hidden_act\t\t\t\t) , RegNetSELayer(_UpperCAmelCase , reduced_channels=int(round(in_channels / 4\t\t\t\t)\t\t\t\t)\t\t\t\t) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=_UpperCAmelCase\t\t\t\t) , )\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tACTaFN[config.hidden_act]\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : Tuple , _UpperCAmelCase : Any\t\t\t\t)\t\t\t\t\t\t->\t\tList[str]:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\thidden_state\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.layer(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.shortcut(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\thidden_state += residual\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.activation(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn hidden_state\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : List[Any] , _UpperCAmelCase : RegNetConfig , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 2 , _UpperCAmelCase : int = 2 , )\t\t\t\t\t\t->\t\tDict:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tRegNetXLayer if config.layer_type == 'x' else RegNetYLayer\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.Sequential(\n\t\t\t\t\t\t\t\t\t\t\t # downsampling is done in the first layer with stride of 2\n\t\t\t\t\t\t\t\t\t\t\t layer(\n\t\t\t\t\t\t\t\t\t\t\t _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase , ) , *[layer(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase\t\t\t\t) for _ in range(depth - 1\t\t\t\t)] , )\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : Any , _UpperCAmelCase : str\t\t\t\t)\t\t\t\t\t\t->\t\tint:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.layers(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn hidden_state\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tnn.Module\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : Any , _UpperCAmelCase : RegNetConfig\t\t\t\t)\t\t\t\t\t\t->\t\tint:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.ModuleList([]\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input\n\t\t\t\t\t\t\t\t\t\t\tself.stages.append(\n\t\t\t\t\t\t\t\t\t\t\t RegNetStage(\n\t\t\t\t\t\t\t\t\t\t\t _UpperCAmelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , )\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tzip(config.hidden_sizes , config.hidden_sizes[1:]\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\tfor (in_channels, out_channels), depth in zip(_UpperCAmelCase , config.depths[1:]\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.stages.append(RegNetStage(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , depth=_UpperCAmelCase\t\t\t\t)\t\t\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : int , _UpperCAmelCase : Tensor , _UpperCAmelCase : bool = False , _UpperCAmelCase : bool = True\t\t\t\t)\t\t\t\t\t\t->\t\tBaseModelOutputWithNoAttention:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t() if output_hidden_states else None\n\n\t\t\t\t\t\t\t\t\t\t\tfor stage_module in self.stages:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif output_hidden_states:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\thidden_states + (hidden_state,)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tstage_module(_UpperCAmelCase\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif output_hidden_states:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\thidden_states + (hidden_state,)\n\n\t\t\t\t\t\t\t\t\t\t\tif not return_dict:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn tuple(v for v in [hidden_state, hidden_states] if v is not None\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\treturn BaseModelOutputWithNoAttention(last_hidden_state=_UpperCAmelCase , hidden_states=_UpperCAmelCase\t\t\t\t)\n\n\n\n\n\n\nclass \tA__ (\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t):\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t:\t\t\t\t\t\tOptional[Any] \t\t\t=\t\t\t\t\t\t\tRegNetConfig\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t:\t\t\t\t\t\tOptional[int] \t\t\t=\t\t\t\t\t\t\t\"regnet\"\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t:\t\t\t\t\t\tDict \t\t\t=\t\t\t\t\t\t\t\"pixel_values\"\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t:\t\t\t\t\t\tList[str] \t\t\t=\t\t\t\t\t\t\tTrue\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : Any , _UpperCAmelCase : Any\t\t\t\t)\t\t\t\t\t\t->\t\tDict:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tif isinstance(_UpperCAmelCase , nn.Convad\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu'\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\telif isinstance(_UpperCAmelCase , (nn.BatchNormad, nn.GroupNorm)\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnn.init.constant_(module.weight , 1\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnn.init.constant_(module.bias , 0\t\t\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Optional[Any]=False\t\t\t\t)\t\t\t\t\t\t->\t\tDict:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tif isinstance(_UpperCAmelCase , _UpperCAmelCase\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tvalue\n\n\n\n\n\n\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\tr\"\"\"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\nSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t=\t\t\t\tr\"\"\"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n@add_start_docstrings(\n \"The bare RegNet model outputting raw features without any specific head on top.\" ,\t\t\t\t\t\tlowerCAmelCase__ ,\t\t\t\t\t\t)\n# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet\nclass \tA__ (\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : List[Any] , _UpperCAmelCase : Any\t\t\t\t)\t\t\t\t\t\t->\t\tstr:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tconfig\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tRegNetEmbeddings(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tRegNetEncoder(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.AdaptiveAvgPoolad((1, 1)\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t# Initialize weights and apply final processing\n\t\t\t\t\t\t\t\t\t\t\tself.post_init()\n\n\n\n\n\n\t\t\t\t\t\t\t@add_start_docstrings_to_model_forward(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t@add_code_sample_docstrings(\n\t\t\t\t\t\t\t checkpoint=_CHECKPOINT_FOR_DOC , output_type=_UpperCAmelCase , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , )\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : Tuple , _UpperCAmelCase : Tensor , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[bool] = None\t\t\t\t)\t\t\t\t\t\t->\t\tBaseModelOutputWithPoolingAndNoAttention:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\t output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\treturn_dict if return_dict is not None else self.config.use_return_dict\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.embedder(_UpperCAmelCase\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.encoder(\n\t\t\t\t\t\t\t\t\t\t\t _UpperCAmelCase , output_hidden_states=_UpperCAmelCase , return_dict=_UpperCAmelCase\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tencoder_outputs[0]\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.pooler(_UpperCAmelCase\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif not return_dict:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn (last_hidden_state, pooled_output) + encoder_outputs[1:]\n\n\t\t\t\t\t\t\t\t\t\t\treturn BaseModelOutputWithPoolingAndNoAttention(\n\t\t\t\t\t\t\t\t\t\t\t last_hidden_state=_UpperCAmelCase , pooler_output=_UpperCAmelCase , hidden_states=encoder_outputs.hidden_states , )\n\n\n\n\n\n\n@add_start_docstrings(\n \"\\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\\n ImageNet.\\n \" ,\t\t\t\t\t\tlowerCAmelCase__ ,\t\t\t\t\t\t)\n# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet\nclass \tA__ (\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self : str , _UpperCAmelCase : List[Any]\t\t\t\t)\t\t\t\t\t\t->\t\tTuple:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tconfig.num_labels\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tRegNetModel(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t# classification head\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tnn.Sequential(\n\t\t\t\t\t\t\t\t\t\t\t nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels\t\t\t\t) if config.num_labels > 0 else nn.Identity() , )\n\t\t\t\t\t\t\t\t\t\t\t# initialize weights and apply final processing\n\t\t\t\t\t\t\t\t\t\t\tself.post_init()\n\n\n\n\n\n\t\t\t\t\t\t\t@add_start_docstrings_to_model_forward(_UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t@add_code_sample_docstrings(\n\t\t\t\t\t\t\t checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_UpperCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )\n\t\t\t\t\t\t\tdef \t\t\ta__ ( self : List[Any] , _UpperCAmelCase : Optional[torch.FloatTensor] = None , _UpperCAmelCase : Optional[torch.LongTensor] = None , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[bool] = None , )\t\t\t\t\t\t->\t\tImageClassifierOutputWithNoAttention:\n\n\n\n\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\treturn_dict if return_dict is not None else self.config.use_return_dict\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.regnet(_UpperCAmelCase , output_hidden_states=_UpperCAmelCase , return_dict=_UpperCAmelCase\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\toutputs.pooler_output if return_dict else outputs[1]\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tself.classifier(_UpperCAmelCase\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tNone\n\n\t\t\t\t\t\t\t\t\t\t\tif labels is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif self.config.problem_type is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif self.num_labels == 1:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t'regression'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t'single_label_classification'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t'multi_label_classification'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif self.config.problem_type == \"regression\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tMSELoss()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif self.num_labels == 1:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tloss_fct(logits.squeeze() , labels.squeeze()\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tloss_fct(_UpperCAmelCase , _UpperCAmelCase\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif self.config.problem_type == \"single_label_classification\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tCrossEntropyLoss()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tloss_fct(logits.view(-1 , self.num_labels\t\t\t\t) , labels.view(-1\t\t\t\t)\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif self.config.problem_type == \"multi_label_classification\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tBCEWithLogitsLoss()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\tloss_fct(_UpperCAmelCase , _UpperCAmelCase\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif not return_dict:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowercase\t\t\t\t\t\t\t\t=\t\t\t\t\t(logits,) + outputs[2:]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn (loss,) + output if loss is not None else output\n\n\t\t\t\t\t\t\t\t\t\t\treturn ImageClassifierOutputWithNoAttention(loss=_UpperCAmelCase , logits=_UpperCAmelCase , hidden_states=outputs.hidden_states\t\t\t\t)\n\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":325,"string":"325"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":219,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\nimport gc\r\nimport unittest\r\n\r\nimport numpy as np\r\nimport torch\r\n\r\nfrom diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel\r\nfrom diffusers.utils import slow, torch_device\r\nfrom diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps\r\n\r\nfrom ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS\r\nfrom ..test_pipelines_common import PipelineTesterMixin\r\n\r\n\r\nenable_full_determinism()\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass UpperCamelCase (\t\t\t\t\t\tlowercase__ , unittest.TestCase ):\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n lowercase :\t\tUnion[str, Any] =DanceDiffusionPipeline\r\n lowercase :\t\tDict =UNCONDITIONAL_AUDIO_GENERATION_PARAMS\r\n lowercase :\t\tList[str] =PipelineTesterMixin.required_optional_params - {\r\n \"\"\"callback\"\"\",\r\n \"\"\"latents\"\"\",\r\n \"\"\"callback_steps\"\"\",\r\n \"\"\"output_type\"\"\",\r\n \"\"\"num_images_per_prompt\"\"\",\r\n }\r\n lowercase :\t\tDict =UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS\r\n lowercase :\t\tAny =False\r\n lowercase :\t\tAny =False\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n torch.manual_seed(0\t\t\t\t\t\t)\r\n lowercase_ :List[str]\t = UNetaDModel(\r\n block_out_channels=(32, 32, 64)\t\t\t\t,\t\t\t\t\t\t\textra_in_channels=16\t\t\t\t,\t\t\t\t\t\t\tsample_size=512\t\t\t\t,\t\t\t\t\t\t\tsample_rate=1_6000\t\t\t\t,\t\t\t\t\t\t\tin_channels=2\t\t\t\t,\t\t\t\t\t\t\tout_channels=2\t\t\t\t,\t\t\t\t\t\t\tflip_sin_to_cos=UpperCamelCase_\t\t\t\t,\t\t\t\t\t\t\tuse_timestep_embedding=UpperCamelCase_\t\t\t\t,\t\t\t\t\t\t\ttime_embedding_type='''fourier'''\t\t\t\t,\t\t\t\t\t\t\tmid_block_type='''UNetMidBlock1D'''\t\t\t\t,\t\t\t\t\t\t\tdown_block_types=('''DownBlock1DNoSkip''', '''DownBlock1D''', '''AttnDownBlock1D''')\t\t\t\t,\t\t\t\t\t\t\tup_block_types=('''AttnUpBlock1D''', '''UpBlock1D''', '''UpBlock1DNoSkip''')\t\t\t\t,\t\t\t\t\t\t\t)\r\n lowercase_ :Optional[Any]\t = IPNDMScheduler()\r\n\r\n lowercase_ :int\t = {\r\n '''unet''': unet,\r\n '''scheduler''': scheduler,\r\n }\r\n return components\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t,\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t,\t\t\t\t\t\t\tUpperCamelCase_=0\t\t\t\t\t\t):\r\n if str(UpperCamelCase_\t\t\t\t\t\t).startswith('''mps'''\t\t\t\t\t\t):\r\n lowercase_ :Union[str, Any]\t = torch.manual_seed(UpperCamelCase_\t\t\t\t\t\t)\r\n else:\r\n lowercase_ :Tuple\t = torch.Generator(device=UpperCamelCase_\t\t\t\t\t\t).manual_seed(UpperCamelCase_\t\t\t\t\t\t)\r\n lowercase_ :List[Any]\t = {\r\n '''batch_size''': 1,\r\n '''generator''': generator,\r\n '''num_inference_steps''': 4,\r\n }\r\n return inputs\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n lowercase_ :Dict\t = '''cpu''' # ensure determinism for the device-dependent torch.Generator\r\n lowercase_ :Optional[int]\t = self.get_dummy_components()\r\n lowercase_ :str\t = DanceDiffusionPipeline(**UpperCamelCase_\t\t\t\t\t\t)\r\n lowercase_ :List[str]\t = pipe.to(UpperCamelCase_\t\t\t\t\t\t)\r\n pipe.set_progress_bar_config(disable=UpperCamelCase_\t\t\t\t\t\t)\r\n\r\n lowercase_ :str\t = self.get_dummy_inputs(UpperCamelCase_\t\t\t\t\t\t)\r\n lowercase_ :Tuple\t = pipe(**UpperCamelCase_\t\t\t\t\t\t)\r\n lowercase_ :Optional[int]\t = output.audios\r\n\r\n lowercase_ :Optional[int]\t = audio[0, -3:, -3:]\r\n\r\n assert audio.shape == (1, 2, components[\"unet\"].sample_size)\r\n lowercase_ :List[str]\t = np.array([-0.7265, 1.0000, -0.8388, 0.1175, 0.9498, -1.0000]\t\t\t\t\t\t)\r\n assert np.abs(audio_slice.flatten() - expected_slice\t\t\t\t\t\t).max() < 1E-2\r\n @skip_mps\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n return super().test_save_load_local()\r\n @skip_mps\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3\t\t\t\t\t\t)\r\n @skip_mps\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n return super().test_save_load_optional_components()\r\n @skip_mps\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n return super().test_attention_slicing_forward_pass()\r\n\r\n\r\n\r\n\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n super().test_inference_batch_single_identical(expected_max_diff=3E-3\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n@slow\r\n@require_torch_gpu\r\nclass UpperCamelCase (\t\t\t\t\t\tunittest.TestCase ):\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n # clean up the VRAM after each test\r\n super().tearDown()\r\n gc.collect()\r\n torch.cuda.empty_cache()\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n lowercase_ :str\t = torch_device\r\n\r\n lowercase_ :Optional[int]\t = DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k'''\t\t\t\t\t\t)\r\n lowercase_ :List[str]\t = pipe.to(UpperCamelCase_\t\t\t\t\t\t)\r\n pipe.set_progress_bar_config(disable=UpperCamelCase_\t\t\t\t\t\t)\r\n\r\n lowercase_ :Union[str, Any]\t = torch.manual_seed(0\t\t\t\t\t\t)\r\n lowercase_ :List[Any]\t = pipe(generator=UpperCamelCase_\t\t\t\t,\t\t\t\t\t\t\tnum_inference_steps=100\t\t\t\t,\t\t\t\t\t\t\taudio_length_in_s=4.096\t\t\t\t\t\t)\r\n lowercase_ :Tuple\t = output.audios\r\n\r\n lowercase_ :Tuple\t = audio[0, -3:, -3:]\r\n\r\n assert audio.shape == (1, 2, pipe.unet.sample_size)\r\n lowercase_ :int\t = np.array([-0.0192, -0.0231, -0.0318, -0.0059, 0.0002, -0.0020]\t\t\t\t\t\t)\r\n\r\n assert np.abs(audio_slice.flatten() - expected_slice\t\t\t\t\t\t).max() < 1E-2\r\n\r\n\r\n\r\n\r\n def \t\t\t\t\t\tUpperCamelCase\t\t\t\t\t( self\t\t\t\t\t\t):\r\n lowercase_ :Tuple\t = torch_device\r\n\r\n lowercase_ :Any\t = DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k'''\t\t\t\t,\t\t\t\t\t\t\ttorch_dtype=torch.floataa\t\t\t\t\t\t)\r\n lowercase_ :List[str]\t = pipe.to(UpperCamelCase_\t\t\t\t\t\t)\r\n pipe.set_progress_bar_config(disable=UpperCamelCase_\t\t\t\t\t\t)\r\n\r\n lowercase_ :Union[str, Any]\t = torch.manual_seed(0\t\t\t\t\t\t)\r\n lowercase_ :Tuple\t = pipe(generator=UpperCamelCase_\t\t\t\t,\t\t\t\t\t\t\tnum_inference_steps=100\t\t\t\t,\t\t\t\t\t\t\taudio_length_in_s=4.096\t\t\t\t\t\t)\r\n lowercase_ :Optional[Any]\t = output.audios\r\n\r\n lowercase_ :Optional[int]\t = audio[0, -3:, -3:]\r\n\r\n assert audio.shape == (1, 2, pipe.unet.sample_size)\r\n lowercase_ :int\t = np.array([-0.0367, -0.0488, -0.0771, -0.0525, -0.0444, -0.0341]\t\t\t\t\t\t)\r\n\r\n assert np.abs(audio_slice.flatten() - expected_slice\t\t\t\t\t\t).max() < 1E-2\r\n\r\n"},"code_codestyle":{"kind":"number","value":355,"string":"355"},"style_context":{"kind":"string","value":"\r\n\r\n\r\nfrom itertools import count\r\n\r\n\r\n\r\n\r\ndef UpperCamelCase ( _a = 5_0\t\t\t\t\t\t) ->\t\t\t\t\t\t\tint:\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n lowercase_ :Dict\t = [1] * min_block_length\r\n\r\n for n in count(_a\t\t\t\t\t\t):\r\n fill_count_functions.append(1\t\t\t\t\t\t)\r\n\r\n for block_length in range(_a ,\t\t\t\t\t\tn + 1\t\t\t\t\t\t):\r\n for block_start in range(n - block_length\t\t\t\t\t\t):\r\n fill_count_functions[n] += fill_count_functions[\r\n n - block_start - block_length - 1\r\n ]\r\n\r\n fill_count_functions[n] += 1\r\n\r\n if fill_count_functions[n] > 1_0_0_0_0_0_0:\r\n break\r\n\r\n return n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(f\"{solution() = }\")\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":252,"string":"252"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":220,"cells":{"code":{"kind":"string","value":"\r\r\rimport inspect\rfrom typing import List, Optional, Tuple, Union\r\rimport numpy as np\rimport PIL\rimport torch\rimport torch.utils.checkpoint\r\rfrom ...models import UNetaDModel, VQModel\rfrom ...schedulers import (\r DDIMScheduler,\r DPMSolverMultistepScheduler,\r EulerAncestralDiscreteScheduler,\r EulerDiscreteScheduler,\r LMSDiscreteScheduler,\r PNDMScheduler,\r)\rfrom ...utils import PIL_INTERPOLATION, randn_tensor\rfrom ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput\rdef \t\t\t\t__lowerCamelCase\t\t\t\t\t\t( UpperCAmelCase_\t\t\t\t\t\t:\t\tDict\t\t\t\t\t\t):\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r\r\r\r a\t\t\t\t\t\t\t,\t\t\t\ta\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= image.size\r a\t\t\t\t\t\t\t,\t\t\t\ta\t\t\t\t\t\t:Optional[Any] \t\t\t\t\t\t\t= (x - x % 32 for x in (w, h)) # resize to integer multiple of 32\r a\t\t\t\t\t\t:str \t\t\t\t\t\t\t= image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos''']\t\t\t\t\t\t)\r a\t\t\t\t\t\t:Union[str, Any] \t\t\t\t\t\t\t= np.array(UpperCAmelCase_\t\t\t\t\t\t).astype(np.floataa\t\t\t\t\t\t) / 255.0\r a\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= image[None].transpose(0 , 3 , 1 , 2\t\t\t\t\t\t)\r a\t\t\t\t\t\t:str \t\t\t\t\t\t\t= torch.from_numpy(UpperCAmelCase_\t\t\t\t\t\t)\r return 2.0 * image - 1.0\r\r\r\r\r\r\r\rclass \t\t_snake_case ( _snake_case\t\t\t\t\t\t\t):\r\r\r\r\r def __init__(\t\tself\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, ):\r super().__init__()\r self.register_modules(vqvae=_lowerCamelCase\t\t\t\t\t, unet=_lowerCamelCase\t\t\t\t\t, scheduler=_lowerCamelCase )\r\r\r\r\r @torch.no_grad()\r def __call__(\t\tself\t\t\t\t\t, _lowerCamelCase = None\t\t\t\t\t, _lowerCamelCase = 1\t\t\t\t\t, _lowerCamelCase = 100\t\t\t\t\t, _lowerCamelCase = 0.0\t\t\t\t\t, _lowerCamelCase = None\t\t\t\t\t, _lowerCamelCase = \"pil\"\t\t\t\t\t, _lowerCamelCase = True\t\t\t\t\t, ):\r if isinstance(_lowerCamelCase\t\t\t\t\t, PIL.Image.Image ):\r a\t\t\t\t\t\t:List[str] \t\t\t\t\t\t\t= 1\r elif isinstance(_lowerCamelCase\t\t\t\t\t, torch.Tensor ):\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= image.shape[0]\r else:\r raise ValueError(F'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_lowerCamelCase )}''' )\r\r if isinstance(_lowerCamelCase\t\t\t\t\t, PIL.Image.Image ):\r a\t\t\t\t\t\t:Dict \t\t\t\t\t\t\t= preprocess(_lowerCamelCase )\r\r a\t\t\t\t\t\t\t,\t\t\t\ta\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= image.shape[-2:]\r\r # in_channels should be 6: 3 for latents, 3 for low resolution image\r a\t\t\t\t\t\t:Dict \t\t\t\t\t\t\t= (batch_size, self.unet.config.in_channels // 2, height, width)\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= next(self.unet.parameters() ).dtype\r\r a\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= randn_tensor(_lowerCamelCase\t\t\t\t\t, generator=_lowerCamelCase\t\t\t\t\t, device=self.device\t\t\t\t\t, dtype=_lowerCamelCase )\r\r a\t\t\t\t\t\t:Optional[Any] \t\t\t\t\t\t\t= image.to(device=self.device\t\t\t\t\t, dtype=_lowerCamelCase )\r\r # set timesteps and move to the correct device\r self.scheduler.set_timesteps(_lowerCamelCase\t\t\t\t\t, device=self.device )\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= self.scheduler.timesteps\r\r # scale the initial noise by the standard deviation required by the scheduler\r a\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= latents * self.scheduler.init_noise_sigma\r\r # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.\r # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.\r # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502\r # and should be between [0, 1]\r a\t\t\t\t\t\t:Any \t\t\t\t\t\t\t= '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )\r a\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= {}\r if accepts_eta:\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= eta\r\r for t in self.progress_bar(_lowerCamelCase ):\r # concat latents and low resolution image in the channel dimension.\r a\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= torch.cat([latents, image]\t\t\t\t\t, dim=1 )\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= self.scheduler.scale_model_input(_lowerCamelCase\t\t\t\t\t, _lowerCamelCase )\r # predict the noise residual\r a\t\t\t\t\t\t:Union[str, Any] \t\t\t\t\t\t\t= self.unet(_lowerCamelCase\t\t\t\t\t, _lowerCamelCase ).sample\r # compute the previous noisy sample x_t -> x_t-1\r a\t\t\t\t\t\t:Optional[Any] \t\t\t\t\t\t\t= self.scheduler.step(_lowerCamelCase\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, **_lowerCamelCase ).prev_sample\r\r # decode the image latents with the VQVAE\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= self.vqvae.decode(_lowerCamelCase ).sample\r a\t\t\t\t\t\t:Optional[Any] \t\t\t\t\t\t\t= torch.clamp(_lowerCamelCase\t\t\t\t\t, -1.0\t\t\t\t\t, 1.0 )\r a\t\t\t\t\t\t:List[Any] \t\t\t\t\t\t\t= image / 2 + 0.5\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= image.cpu().permute(0\t\t\t\t\t, 2\t\t\t\t\t, 3\t\t\t\t\t, 1 ).numpy()\r\r if output_type == \"pil\":\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= self.numpy_to_pil(_lowerCamelCase )\r\r if not return_dict:\r return (image,)\r\r return ImagePipelineOutput(images=_lowerCamelCase )\r\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":94,"string":"94"},"style_context":{"kind":"string","value":"\r\r\rimport os\rfrom shutil import copyfile\rfrom typing import Any, Dict, List, Optional, Tuple\r\rimport sentencepiece as spm\r\rfrom ...tokenization_utils import AddedToken, PreTrainedTokenizer\rfrom ...utils import logging\r\r\rsnake_case\t\t\t\t: Dict \t\t\t\t= logging.get_logger(__name__)\r\rsnake_case\t\t\t\t: Tuple \t\t\t\t= '''▁'''\r\rsnake_case\t\t\t\t: Any \t\t\t\t= {'''vocab_file''': '''sentencepiece.bpe.model'''}\r\rsnake_case\t\t\t\t: Tuple \t\t\t\t= {\r '''vocab_file''': {\r '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''',\r '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''',\r '''xlm-roberta-large-finetuned-conll02-dutch''': (\r '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model'''\r ),\r '''xlm-roberta-large-finetuned-conll02-spanish''': (\r '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model'''\r ),\r '''xlm-roberta-large-finetuned-conll03-english''': (\r '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model'''\r ),\r '''xlm-roberta-large-finetuned-conll03-german''': (\r '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model'''\r ),\r }\r}\r\rsnake_case\t\t\t\t: int \t\t\t\t= {\r '''xlm-roberta-base''': 5_12,\r '''xlm-roberta-large''': 5_12,\r '''xlm-roberta-large-finetuned-conll02-dutch''': 5_12,\r '''xlm-roberta-large-finetuned-conll02-spanish''': 5_12,\r '''xlm-roberta-large-finetuned-conll03-english''': 5_12,\r '''xlm-roberta-large-finetuned-conll03-german''': 5_12,\r}\r\r\r\r\r\r\r\rclass \t\t_snake_case ( _snake_case\t\t\t\t\t\t\t):\r SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES\r SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP\r SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\r SCREAMING_SNAKE_CASE__ = ['input_ids', 'attention_mask']\r\r\r\r\r def __init__(\t\tself\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase=\"\"\t\t\t\t\t, _lowerCamelCase=\"\"\t\t\t\t\t, _lowerCamelCase=\"\"\t\t\t\t\t, _lowerCamelCase=\"\"\t\t\t\t\t, _lowerCamelCase=\"\"\t\t\t\t\t, _lowerCamelCase=\"\"\t\t\t\t\t, _lowerCamelCase=\"\"\t\t\t\t\t, _lowerCamelCase = None\t\t\t\t\t, **_lowerCamelCase\t\t\t\t\t, ):\r # Mask token behave like a normal word, i.e. include the space before it\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= AddedToken(_lowerCamelCase\t\t\t\t\t, lstrip=_lowerCamelCase\t\t\t\t\t, rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase\t\t\t\t\t, _lowerCamelCase ) else mask_token\r\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= {} if sp_model_kwargs is None else sp_model_kwargs\r\r super().__init__(\r bos_token=_lowerCamelCase\t\t\t\t\t, eos_token=_lowerCamelCase\t\t\t\t\t, unk_token=_lowerCamelCase\t\t\t\t\t, sep_token=_lowerCamelCase\t\t\t\t\t, cls_token=_lowerCamelCase\t\t\t\t\t, pad_token=_lowerCamelCase\t\t\t\t\t, mask_token=_lowerCamelCase\t\t\t\t\t, sp_model_kwargs=self.sp_model_kwargs\t\t\t\t\t, **_lowerCamelCase\t\t\t\t\t, )\r\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= spm.SentencePieceProcessor(**self.sp_model_kwargs )\r self.sp_model.Load(str(_lowerCamelCase ) )\r a\t\t\t\t\t\t:str \t\t\t\t\t\t\t= vocab_file\r\r # Original fairseq vocab and spm vocab must be \"aligned\":\r # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\r # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----\r # fairseq | '' | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-'\r # spm | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'\r\r # Mimic fairseq token-to-id alignment for the first 4 token\r a\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= {'''''': 0, '''''': 1, '''''': 2, '''''': 3}\r\r # The first \"real\" token \",\" has position 4 in the original fairseq vocab and position 3 in the spm vocab\r a\t\t\t\t\t\t:List[str] \t\t\t\t\t\t\t= 1\r\r a\t\t\t\t\t\t:Dict \t\t\t\t\t\t\t= len(self.sp_model ) + self.fairseq_offset\r a\t\t\t\t\t\t:List[Any] \t\t\t\t\t\t\t= {v: k for k, v in self.fairseq_tokens_to_ids.items()}\r\r\r\r\r def __getstate__(\t\tself ):\r a\t\t\t\t\t\t:List[str] \t\t\t\t\t\t\t= self.__dict__.copy()\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= None\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= self.sp_model.serialized_model_proto()\r return state\r\r\r\r\r def __setstate__(\t\tself\t\t\t\t\t, _lowerCamelCase ):\r a\t\t\t\t\t\t:Union[str, Any] \t\t\t\t\t\t\t= d\r\r # for backward compatibility\r if not hasattr(self\t\t\t\t\t, '''sp_model_kwargs''' ):\r a\t\t\t\t\t\t:Union[str, Any] \t\t\t\t\t\t\t= {}\r\r a\t\t\t\t\t\t:Optional[int] \t\t\t\t\t\t\t= spm.SentencePieceProcessor(**self.sp_model_kwargs )\r self.sp_model.LoadFromSerializedProto(self.sp_model_proto )\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase = None ):\r\r if token_ids_a is None:\r return [self.cls_token_id] + token_ids_a + [self.sep_token_id]\r a\t\t\t\t\t\t:List[Any] \t\t\t\t\t\t\t= [self.cls_token_id]\r a\t\t\t\t\t\t:Dict \t\t\t\t\t\t\t= [self.sep_token_id]\r return cls + token_ids_a + sep + sep + token_ids_a + sep\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase = None\t\t\t\t\t, _lowerCamelCase = False ):\r\r if already_has_special_tokens:\r return super().get_special_tokens_mask(\r token_ids_a=_lowerCamelCase\t\t\t\t\t, token_ids_a=_lowerCamelCase\t\t\t\t\t, already_has_special_tokens=_lowerCamelCase )\r\r if token_ids_a is None:\r return [1] + ([0] * len(_lowerCamelCase )) + [1]\r return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1]\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase = None ):\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= [self.sep_token_id]\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= [self.cls_token_id]\r\r if token_ids_a is None:\r return len(cls + token_ids_a + sep ) * [0]\r return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]\r\r\r\r\r @property\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself ):\r return len(self.sp_model ) + self.fairseq_offset + 1 # Add the token\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself ):\r a\t\t\t\t\t\t:Any \t\t\t\t\t\t\t= {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}\r vocab.update(self.added_tokens_encoder )\r return vocab\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase ):\r return self.sp_model.encode(_lowerCamelCase\t\t\t\t\t, out_type=_lowerCamelCase )\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase ):\r if token in self.fairseq_tokens_to_ids:\r return self.fairseq_tokens_to_ids[token]\r a\t\t\t\t\t\t:Optional[Any] \t\t\t\t\t\t\t= self.sp_model.PieceToId(_lowerCamelCase )\r\r # Need to return unknown token if the SP model returned 0\r return spm_id + self.fairseq_offset if spm_id else self.unk_token_id\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase ):\r if index in self.fairseq_ids_to_tokens:\r return self.fairseq_ids_to_tokens[index]\r return self.sp_model.IdToPiece(index - self.fairseq_offset )\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase ):\r a\t\t\t\t\t\t:Tuple \t\t\t\t\t\t\t= ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase\t\t\t\t\t, ''' ''' ).strip()\r return out_string\r\r\r\r\r def SCREAMING_SNAKE_CASE__\t\t\t\t(\t\tself\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t, _lowerCamelCase = None ):\r if not os.path.isdir(_lowerCamelCase ):\r logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )\r return\r a\t\t\t\t\t\t:int \t\t\t\t\t\t\t= os.path.join(\r _lowerCamelCase\t\t\t\t\t, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )\r\r if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ):\r copyfile(self.vocab_file\t\t\t\t\t, _lowerCamelCase )\r elif not os.path.isfile(self.vocab_file ):\r with open(_lowerCamelCase\t\t\t\t\t, '''wb''' ) as fi:\r a\t\t\t\t\t\t:List[Any] \t\t\t\t\t\t\t= self.sp_model.serialized_model_proto()\r fi.write(_lowerCamelCase )\r\r return (out_vocab_file,)\r\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":94,"string":"94"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":221,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\ndef \t\t\t_lowerCAmelCase\t\t\t\t( ):\r\n\t\t\t\t\t\tfor n in range(1\t\t, 1000000\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\tyield n * (n + 1) // 2\r\n\r\ndef \t\t\t_lowerCAmelCase\t\t\t\t( lowercase_\t\t\t\t\t\t):\r\n\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t1\r\n\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t2\r\n\t\t\t\t\t\twhile i * i <= n:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t0\r\n\t\t\t\t\t\t\t\t\t\t\t\twhile n % i == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tn //= i\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmultiplicity += 1\r\n\t\t\t\t\t\t\t\t\t\t\t\tdivisors_count *= multiplicity + 1\r\n\t\t\t\t\t\t\t\t\t\t\t\ti += 1\r\n\t\t\t\t\t\tif n > 1:\r\n\t\t\t\t\t\t\t\t\t\t\t\tdivisors_count *= 2\r\n\t\t\t\t\t\treturn divisors_count\r\n\r\ndef \t\t\t_lowerCAmelCase\t\t\t\t( ):\r\n\t\t\t\t\t\treturn next(i for i in triangle_number_generator() if count_divisors(lowercase_\t\t\t\t\t\t) > 500\t\t\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\tprint(solution())\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":366,"string":"366"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\nimport contextlib\r\nimport copy\r\nimport random\r\nfrom typing import Any, Dict, Iterable, Optional, Union\r\n\r\nimport numpy as np\r\nimport torch\r\n\r\nfrom .utils import deprecate, is_transformers_available\r\n\r\n\r\nif is_transformers_available():\r\n\t\t\t\timport transformers\r\n\r\ndef \t\t\t_lowerCAmelCase\t\t\t\t( lowercase_\t\t\t\t\t\t):\r\n\t\t\t\t\t\trandom.seed(lowercase_\t\t\t\t\t\t)\r\n\t\t\t\t\t\tnp.random.seed(lowercase_\t\t\t\t\t\t)\r\n\t\t\t\t\t\ttorch.manual_seed(lowercase_\t\t\t\t\t\t)\r\n\t\t\t\t\t\ttorch.cuda.manual_seed_all(lowercase_\t\t\t\t\t\t)\r\n\t\t\t\t\t\t# ^^ safe to call this function even if cuda is not available\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass \t\t\t\tA_ :\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef __init__( self\t\t\t:Any , lowercase_\t\t\t:Iterable[torch.nn.Parameter] , lowercase_\t\t\t:float = 0.9999 , lowercase_\t\t\t:float = 0.0 , lowercase_\t\t\t:int = 0 , lowercase_\t\t\t:bool = False , lowercase_\t\t\t:Union[float, int] = 1.0 , lowercase_\t\t\t:Union[float, int] = 2 / 3 , lowercase_\t\t\t:Optional[Any] = None , lowercase_\t\t\t:Dict[str, Any] = None , **lowercase_\t\t\t:Dict , ) -> Optional[int]:\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif isinstance(lowercase_ , torch.nn.Module ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. '\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Please pass the parameters of the module instead.'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeprecate(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'passing a `torch.nn.Module` to `ExponentialMovingAverage`' , '1.0.0' , lowercase_ , standard_warn=lowercase_ , )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tparameters.parameters()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tTrue\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif kwargs.get('max_value' , lowercase_ ) is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t'The `max_value` argument is deprecated. Please use `decay` instead.'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeprecate('max_value' , '1.0.0' , lowercase_ , standard_warn=lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tkwargs['max_value']\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif kwargs.get('min_value' , lowercase_ ) is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t'The `min_value` argument is deprecated. Please use `min_decay` instead.'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeprecate('min_value' , '1.0.0' , lowercase_ , standard_warn=lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tkwargs['min_value']\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tlist(lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t[p.clone().detach() for p in parameters]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif kwargs.get('device' , lowercase_ ) is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t'The `device` argument is deprecated. Please use `to` instead.'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeprecate('device' , '1.0.0' , lowercase_ , standard_warn=lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.to(device=kwargs['device'] )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tNone\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tdecay\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tmin_decay\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tupdate_after_step\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tuse_ema_warmup\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tinv_gamma\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tpower\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t0\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tNone # set in `step()`\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tmodel_cls\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tmodel_config\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@classmethod\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( cls\t\t\t:int , lowercase_\t\t\t:Union[str, Any] , lowercase_\t\t\t:Any ) -> \"EMAModel\":\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t, UpperCAmelCase\t\t\t\t\t=\t\t\tmodel_cls.load_config(lowercase_ , return_unused_kwargs=lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tmodel_cls.from_pretrained(lowercase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tcls(model.parameters() , model_cls=lowercase_ , model_config=model.config )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tema_model.load_state_dict(lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn ema_model\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:List[Any] , lowercase_\t\t\t:List[str] ) -> int:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.model_cls is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('`save_pretrained` can only be used if `model_cls` was defined at __init__.' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.model_config is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('`save_pretrained` can only be used if `model_config` was defined at __init__.' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tself.model_cls.from_config(self.model_config )\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tself.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\tstate_dict.pop('shadow_params' , lowercase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tmodel.register_to_config(**lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.copy_to(model.parameters() )\r\n\t\t\t\t\t\t\t\t\t\t\t\tmodel.save_pretrained(lowercase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:Optional[int] , lowercase_\t\t\t:int ) -> float:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tmax(0 , optimization_step - self.update_after_step - 1 )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif step <= 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn 0.0\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.use_ema_warmup:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t1 - (1 + step / self.inv_gamma) ** -self.power\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t(1 + step) / (10 + step)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tmin(lowercase_ , self.decay )\r\n\t\t\t\t\t\t\t\t\t\t\t\t# make sure decay is not smaller than min_decay\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tmax(lowercase_ , self.min_decay )\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn cur_decay_value\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@torch.no_grad()\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:List[Any] , lowercase_\t\t\t:Iterable[torch.nn.Parameter] ) -> Optional[int]:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif isinstance(lowercase_ , torch.nn.Module ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. '\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Please pass the parameters of the module instead.'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdeprecate(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'passing a `torch.nn.Module` to `ExponentialMovingAverage.step`' , '1.0.0' , lowercase_ , standard_warn=lowercase_ , )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tparameters.parameters()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tlist(lowercase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.optimization_step += 1\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Compute the decay factor for the exponential moving average.\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tself.get_decay(self.optimization_step )\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tdecay\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t1 - decay\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tcontextlib.nullcontext\r\n\t\t\t\t\t\t\t\t\t\t\t\tif is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timport deepspeed\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor s_param, param in zip(self.shadow_params , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tdeepspeed.zero.GatheredParameters(lowercase_ , modifier_rank=lowercase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith context_manager():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif param.requires_grad:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ts_param.sub_(one_minus_decay * (s_param - param) )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ts_param.copy_(lowercase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:Tuple , lowercase_\t\t\t:Iterable[torch.nn.Parameter] ) -> None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tlist(lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor s_param, param in zip(self.shadow_params , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparam.data.copy_(s_param.to(param.device ).data )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:Dict , lowercase_\t\t\t:Tuple=None , lowercase_\t\t\t:Union[str, Any]=None ) -> None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t[\r\n\t\t\t\t\t\t\t\t\t\t\t\t p.to(device=lowercase_ , dtype=lowercase_ ) if p.is_floating_point() else p.to(device=lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t for p in self.shadow_params\r\n\t\t\t\t\t\t\t\t\t\t\t\t]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:Union[str, Any] ) -> dict:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn {\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"decay\": self.decay,\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"min_decay\": self.min_decay,\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"optimization_step\": self.optimization_step,\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"update_after_step\": self.update_after_step,\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"use_ema_warmup\": self.use_ema_warmup,\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"inv_gamma\": self.inv_gamma,\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"power\": self.power,\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"shadow_params\": self.shadow_params,\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:Optional[int] , lowercase_\t\t\t:Iterable[torch.nn.Parameter] ) -> None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\t[param.detach().cpu().clone() for param in parameters]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:Optional[Any] , lowercase_\t\t\t:Iterable[torch.nn.Parameter] ) -> None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.temp_stored_params is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise RuntimeError('This ExponentialMovingAverage has no `store()`ed weights ' 'to `restore()`' )\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor c_param, param in zip(self.temp_stored_params , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparam.data.copy_(c_param.data )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Better memory-wise.\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tNone\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase__\t\t\t\t\t( self\t\t\t:Union[str, Any] , lowercase_\t\t\t:dict ) -> None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tcopy.deepcopy(lowercase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('decay' , self.decay )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.decay < 0.0 or self.decay > 1.0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('Decay must be between 0 and 1' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('min_decay' , self.min_decay )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(self.min_decay , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid min_decay' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('optimization_step' , self.optimization_step )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(self.optimization_step , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid optimization_step' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('update_after_step' , self.update_after_step )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(self.update_after_step , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid update_after_step' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('use_ema_warmup' , self.use_ema_warmup )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(self.use_ema_warmup , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid use_ema_warmup' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('inv_gamma' , self.inv_gamma )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(self.inv_gamma , (float, int) ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid inv_gamma' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('power' , self.power )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(self.power , (float, int) ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid power' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tstate_dict.get('shadow_params' , lowercase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\tif shadow_params is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase\t\t\t\t\t=\t\t\tshadow_params\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(self.shadow_params , lowercase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('shadow_params must be a list' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not all(isinstance(lowercase_ , torch.Tensor ) for p in self.shadow_params ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('shadow_params must all be Tensors' )\r\n\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":181,"string":"181"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":222,"cells":{"code":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\n\n\n\n\n\nimport json\nimport pathlib\nimport unittest\n\nimport numpy as np\n\nfrom transformers.testing_utils import require_torch, require_vision, slow\nfrom transformers.utils import is_torch_available, is_vision_available\n\nfrom ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs\n\n\nif is_torch_available():\n import torch\n\nif is_vision_available():\n from PIL import Image\n\n from transformers import YolosImageProcessor\n\nclass \t\t\t\t\t\t\ta__(\t\t\t\t\tunittest.TestCase\t):\n\n\n\n\n\n\n\n def __init__( self : int\t\t\t\t\t\t,\t\t\t__snake_case : str\t\t\t\t\t\t,\t\t\t__snake_case : Dict=7\t\t\t\t\t\t,\t\t\t__snake_case : int=3\t\t\t\t\t\t,\t\t\t__snake_case : int=30\t\t\t\t\t\t,\t\t\t__snake_case : Dict=4_00\t\t\t\t\t\t,\t\t\t__snake_case : Optional[Any]=True\t\t\t\t\t\t,\t\t\t__snake_case : List[str]=None\t\t\t\t\t\t,\t\t\t__snake_case : Union[str, Any]=True\t\t\t\t\t\t,\t\t\t__snake_case : List[Any]=[0.5, 0.5, 0.5]\t\t\t\t\t\t,\t\t\t__snake_case : Union[str, Any]=[0.5, 0.5, 0.5]\t\t\t\t\t\t,\t\t\t__snake_case : List[Any]=True\t\t\t\t\t\t,\t\t\t__snake_case : List[Any]=1 / 2_55\t\t\t\t\t\t,\t\t\t__snake_case : Any=True\t\t\t\t\t\t,\t\t\t):\n # by setting size[\"longest_edge\"] > max_resolution we're effectively not testing this :p\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33}\n a\t\t\t\t\t\t:\t\t\t\t\tstr = parent\n a\t\t\t\t\t\t:\t\t\t\t\tAny = batch_size\n a\t\t\t\t\t\t:\t\t\t\t\tAny = num_channels\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = min_resolution\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = max_resolution\n a\t\t\t\t\t\t:\t\t\t\t\tstr = do_resize\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = size\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = do_normalize\n a\t\t\t\t\t\t:\t\t\t\t\tList[Any] = image_mean\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = image_std\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = do_rescale\n a\t\t\t\t\t\t:\t\t\t\t\tAny = rescale_factor\n a\t\t\t\t\t\t:\t\t\t\t\tint = do_pad\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : Optional[Any]\t):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n \"do_normalize\": self.do_normalize,\n \"image_mean\": self.image_mean,\n \"image_std\": self.image_std,\n \"do_rescale\": self.do_rescale,\n \"rescale_factor\": self.rescale_factor,\n \"do_pad\": self.do_pad,\n }\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : List[str]\t\t\t\t\t\t,\t\t\t__snake_case : str\t\t\t\t\t\t,\t\t\t__snake_case : Tuple=False\t):\n if not batched:\n a\t\t\t\t\t\t:\t\t\t\t\tList[Any] = image_inputs[0]\n if isinstance(__snake_case\t\t\t\t\t\t,\t\t\tImage.Image\t):\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tDict = image.size\n else:\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = image.shape[1], image.shape[2]\n if w < h:\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = int(self.size['shortest_edge'] * h / w\t)\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = self.size['shortest_edge']\n elif w > h:\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = self.size['shortest_edge']\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = int(self.size['shortest_edge'] * w / h\t)\n else:\n a\t\t\t\t\t\t:\t\t\t\t\tAny = self.size['shortest_edge']\n a\t\t\t\t\t\t:\t\t\t\t\tstr = self.size['shortest_edge']\n\n else:\n a\t\t\t\t\t\t:\t\t\t\t\tstr = []\n for image in image_inputs:\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tint = self.get_expected_values([image]\t)\n expected_values.append((expected_height, expected_width)\t)\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = max(__snake_case\t\t\t\t\t\t,\t\t\tkey=lambda __snake_case\t: item[0]\t)[0]\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = max(__snake_case\t\t\t\t\t\t,\t\t\tkey=lambda __snake_case\t: item[1]\t)[1]\n\n return expected_height, expected_width\n\n@require_torch\n@require_vision\nclass \t\t\t\t\t\t\ta__(\t\t\t\t\tlowerCamelCase__\t\t, unittest.TestCase\t):\n lowercase__ = YolosImageProcessor if is_vision_available() else None\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : Optional[Any]\t):\n a\t\t\t\t\t\t:\t\t\t\t\tDict = YolosImageProcessingTester(self\t)\n\n\n\n\n\n\n\n @property\n def \t\t\tlowercase_ ( self : Dict\t):\n return self.image_processor_tester.prepare_image_processor_dict()\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : List[str]\t):\n a\t\t\t\t\t\t:\t\t\t\t\tstr = self.image_processing_class(**self.image_processor_dict\t)\n self.assertTrue(hasattr(__snake_case\t\t\t\t\t\t,\t\t\t'image_mean'\t)\t)\n self.assertTrue(hasattr(__snake_case\t\t\t\t\t\t,\t\t\t'image_std'\t)\t)\n self.assertTrue(hasattr(__snake_case\t\t\t\t\t\t,\t\t\t'do_normalize'\t)\t)\n self.assertTrue(hasattr(__snake_case\t\t\t\t\t\t,\t\t\t'do_resize'\t)\t)\n self.assertTrue(hasattr(__snake_case\t\t\t\t\t\t,\t\t\t'size'\t)\t)\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : Dict\t):\n a\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict\t)\n self.assertEqual(image_processor.size\t\t\t\t\t\t,\t\t\t{'shortest_edge': 18, 'longest_edge': 13_33}\t)\n self.assertEqual(image_processor.do_pad\t\t\t\t\t\t,\t\t\t__snake_case\t)\n\n a\t\t\t\t\t\t:\t\t\t\t\tstr = self.image_processing_class.from_dict(\n self.image_processor_dict\t\t\t\t\t\t,\t\t\tsize=42\t\t\t\t\t\t,\t\t\tmax_size=84\t\t\t\t\t\t,\t\t\tpad_and_return_pixel_mask=__snake_case\t)\n self.assertEqual(image_processor.size\t\t\t\t\t\t,\t\t\t{'shortest_edge': 42, 'longest_edge': 84}\t)\n self.assertEqual(image_processor.do_pad\t\t\t\t\t\t,\t\t\t__snake_case\t)\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : List[str]\t):\n pass\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : List[Any]\t):\n # Initialize image_processing\n a\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = self.image_processing_class(**self.image_processor_dict\t)\n # create random PIL images\n a\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = prepare_image_inputs(self.image_processor_tester\t\t\t\t\t\t,\t\t\tequal_resolution=__snake_case\t)\n for image in image_inputs:\n self.assertIsInstance(__snake_case\t\t\t\t\t\t,\t\t\tImage.Image\t)\n\n # Test not batched input\n a\t\t\t\t\t\t:\t\t\t\t\tAny = image_processing(image_inputs[0]\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t).pixel_values\n\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = self.image_processor_tester.get_expected_values(__snake_case\t)\n\n self.assertEqual(\n encoded_images.shape\t\t\t\t\t\t,\t\t\t(1, self.image_processor_tester.num_channels, expected_height, expected_width)\t\t\t\t\t\t,\t\t\t)\n\n # Test batched\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = self.image_processor_tester.get_expected_values(__snake_case\t\t\t\t\t\t,\t\t\tbatched=__snake_case\t)\n\n a\t\t\t\t\t\t:\t\t\t\t\tDict = image_processing(__snake_case\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t).pixel_values\n self.assertEqual(\n encoded_images.shape\t\t\t\t\t\t,\t\t\t(\n self.image_processor_tester.batch_size,\n self.image_processor_tester.num_channels,\n expected_height,\n expected_width,\n )\t\t\t\t\t\t,\t\t\t)\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : Any\t):\n # Initialize image_processing\n a\t\t\t\t\t\t:\t\t\t\t\tAny = self.image_processing_class(**self.image_processor_dict\t)\n # create random numpy tensors\n a\t\t\t\t\t\t:\t\t\t\t\tstr = prepare_image_inputs(self.image_processor_tester\t\t\t\t\t\t,\t\t\tequal_resolution=__snake_case\t\t\t\t\t\t,\t\t\tnumpify=__snake_case\t)\n for image in image_inputs:\n self.assertIsInstance(__snake_case\t\t\t\t\t\t,\t\t\tnp.ndarray\t)\n\n # Test not batched input\n a\t\t\t\t\t\t:\t\t\t\t\tstr = image_processing(image_inputs[0]\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t).pixel_values\n\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tAny = self.image_processor_tester.get_expected_values(__snake_case\t)\n\n self.assertEqual(\n encoded_images.shape\t\t\t\t\t\t,\t\t\t(1, self.image_processor_tester.num_channels, expected_height, expected_width)\t\t\t\t\t\t,\t\t\t)\n\n # Test batched\n a\t\t\t\t\t\t:\t\t\t\t\tstr = image_processing(__snake_case\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t).pixel_values\n\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tTuple = self.image_processor_tester.get_expected_values(__snake_case\t\t\t\t\t\t,\t\t\tbatched=__snake_case\t)\n\n self.assertEqual(\n encoded_images.shape\t\t\t\t\t\t,\t\t\t(\n self.image_processor_tester.batch_size,\n self.image_processor_tester.num_channels,\n expected_height,\n expected_width,\n )\t\t\t\t\t\t,\t\t\t)\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : Optional[int]\t):\n # Initialize image_processing\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = self.image_processing_class(**self.image_processor_dict\t)\n # create random PyTorch tensors\n a\t\t\t\t\t\t:\t\t\t\t\tList[Any] = prepare_image_inputs(self.image_processor_tester\t\t\t\t\t\t,\t\t\tequal_resolution=__snake_case\t\t\t\t\t\t,\t\t\ttorchify=__snake_case\t)\n for image in image_inputs:\n self.assertIsInstance(__snake_case\t\t\t\t\t\t,\t\t\ttorch.Tensor\t)\n\n # Test not batched input\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = image_processing(image_inputs[0]\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t).pixel_values\n\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tList[str] = self.image_processor_tester.get_expected_values(__snake_case\t)\n\n self.assertEqual(\n encoded_images.shape\t\t\t\t\t\t,\t\t\t(1, self.image_processor_tester.num_channels, expected_height, expected_width)\t\t\t\t\t\t,\t\t\t)\n\n # Test batched\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = image_processing(__snake_case\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t).pixel_values\n\n a ,\ta\t\t\t\t\t\t:\t\t\t\t\tAny = self.image_processor_tester.get_expected_values(__snake_case\t\t\t\t\t\t,\t\t\tbatched=__snake_case\t)\n\n self.assertEqual(\n encoded_images.shape\t\t\t\t\t\t,\t\t\t(\n self.image_processor_tester.batch_size,\n self.image_processor_tester.num_channels,\n expected_height,\n expected_width,\n )\t\t\t\t\t\t,\t\t\t)\n\n\n\n\n\n\n\n def \t\t\tlowercase_ ( self : Optional[int]\t):\n # Initialize image_processings\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = self.image_processing_class(**self.image_processor_dict\t)\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = self.image_processing_class(do_resize=__snake_case\t\t\t\t\t\t,\t\t\tdo_normalize=__snake_case\t\t\t\t\t\t,\t\t\tdo_rescale=__snake_case\t)\n # create random PyTorch tensors\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = prepare_image_inputs(self.image_processor_tester\t\t\t\t\t\t,\t\t\tequal_resolution=__snake_case\t\t\t\t\t\t,\t\t\ttorchify=__snake_case\t)\n for image in image_inputs:\n self.assertIsInstance(__snake_case\t\t\t\t\t\t,\t\t\ttorch.Tensor\t)\n\n # Test whether the method \"pad\" and calling the image processor return the same tensors\n a\t\t\t\t\t\t:\t\t\t\t\tstr = image_processing_a.pad(__snake_case\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t)\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = image_processing_a(__snake_case\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t)\n\n self.assertTrue(\n torch.allclose(encoded_images_with_method['pixel_values']\t\t\t\t\t\t,\t\t\tencoded_images['pixel_values']\t\t\t\t\t\t,\t\t\tatol=1e-4\t)\t)\n\n\n\n\n\n\n\n @slow\n def \t\t\tlowercase_ ( self : Union[str, Any]\t):\n # prepare image and target\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'\t)\n with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'\t\t\t\t\t\t,\t\t\t'r'\t) as f:\n a\t\t\t\t\t\t:\t\t\t\t\tint = json.loads(f.read()\t)\n\n a\t\t\t\t\t\t:\t\t\t\t\tTuple = {'image_id': 3_97_69, 'annotations': target}\n\n # encode them\n a\t\t\t\t\t\t:\t\t\t\t\tstr = YolosImageProcessor.from_pretrained('hustvl/yolos-small'\t)\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = image_processing(images=__snake_case\t\t\t\t\t\t,\t\t\tannotations=__snake_case\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t)\n\n # verify pixel values\n a\t\t\t\t\t\t:\t\t\t\t\tDict = torch.Size([1, 3, 8_00, 10_66]\t)\n self.assertEqual(encoding['pixel_values'].shape\t\t\t\t\t\t,\t\t\t__snake_case\t)\n\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = torch.tensor([0.2796, 0.3138, 0.3481]\t)\n self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]\t\t\t\t\t\t,\t\t\t__snake_case\t\t\t\t\t\t,\t\t\tatol=1e-4\t)\t)\n\n # verify area\n a\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['area']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify boxes\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = torch.Size([6, 4]\t)\n self.assertEqual(encoding['labels'][0]['boxes'].shape\t\t\t\t\t\t,\t\t\t__snake_case\t)\n a\t\t\t\t\t\t:\t\t\t\t\tAny = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]\t\t\t\t\t\t,\t\t\t__snake_case\t\t\t\t\t\t,\t\t\tatol=1e-3\t)\t)\n # verify image_id\n a\t\t\t\t\t\t:\t\t\t\t\tAny = torch.tensor([3_97_69]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify is_crowd\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = torch.tensor([0, 0, 0, 0, 0, 0]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify class_labels\n a\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify orig_size\n a\t\t\t\t\t\t:\t\t\t\t\tAny = torch.tensor([4_80, 6_40]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify size\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = torch.tensor([8_00, 10_66]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['size']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n\n\n\n\n\n\n\n @slow\n def \t\t\tlowercase_ ( self : List[str]\t):\n # prepare image, target and masks_path\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'\t)\n with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'\t\t\t\t\t\t,\t\t\t'r'\t) as f:\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = json.loads(f.read()\t)\n\n a\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target}\n\n a\t\t\t\t\t\t:\t\t\t\t\tList[str] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'\t)\n\n # encode them\n a\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any] = YolosImageProcessor(format='coco_panoptic'\t)\n a\t\t\t\t\t\t:\t\t\t\t\tint = image_processing(images=__snake_case\t\t\t\t\t\t,\t\t\tannotations=__snake_case\t\t\t\t\t\t,\t\t\tmasks_path=__snake_case\t\t\t\t\t\t,\t\t\treturn_tensors='pt'\t)\n\n # verify pixel values\n a\t\t\t\t\t\t:\t\t\t\t\tint = torch.Size([1, 3, 8_00, 10_66]\t)\n self.assertEqual(encoding['pixel_values'].shape\t\t\t\t\t\t,\t\t\t__snake_case\t)\n\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = torch.tensor([0.2796, 0.3138, 0.3481]\t)\n self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]\t\t\t\t\t\t,\t\t\t__snake_case\t\t\t\t\t\t,\t\t\tatol=1e-4\t)\t)\n\n # verify area\n a\t\t\t\t\t\t:\t\t\t\t\tList[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['area']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify boxes\n a\t\t\t\t\t\t:\t\t\t\t\tList[Any] = torch.Size([6, 4]\t)\n self.assertEqual(encoding['labels'][0]['boxes'].shape\t\t\t\t\t\t,\t\t\t__snake_case\t)\n a\t\t\t\t\t\t:\t\t\t\t\tDict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]\t\t\t\t\t\t,\t\t\t__snake_case\t\t\t\t\t\t,\t\t\tatol=1e-3\t)\t)\n # verify image_id\n a\t\t\t\t\t\t:\t\t\t\t\tstr = torch.tensor([3_97_69]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify is_crowd\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = torch.tensor([0, 0, 0, 0, 0, 0]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify class_labels\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = torch.tensor([17, 17, 63, 75, 75, 93]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify masks\n a\t\t\t\t\t\t:\t\t\t\t\tDict = 82_28_73\n self.assertEqual(encoding['labels'][0]['masks'].sum().item()\t\t\t\t\t\t,\t\t\t__snake_case\t)\n # verify orig_size\n a\t\t\t\t\t\t:\t\t\t\t\tint = torch.tensor([4_80, 6_40]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)\n # verify size\n a\t\t\t\t\t\t:\t\t\t\t\tOptional[int] = torch.tensor([8_00, 10_66]\t)\n self.assertTrue(torch.allclose(encoding['labels'][0]['size']\t\t\t\t\t\t,\t\t\t__snake_case\t)\t)"},"code_codestyle":{"kind":"number","value":297,"string":"297"},"style_context":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\n\n\n\n\n\nfrom __future__ import annotations\n\nfrom math import pi, sqrt\ndef lowerCamelCase__ (\t\t\t\t\t\t_A ,\t\t\t_A\t\t\t\t):\n\n if inductance <= 0:\n raise ValueError('Inductance cannot be 0 or negative'\t\t\t\t)\n\n elif capacitance <= 0:\n raise ValueError('Capacitance cannot be 0 or negative'\t\t\t\t)\n\n else:\n return (\n \"Resonant frequency\",\n float(1 / (2 * pi * (sqrt(inductance * capacitance\t\t\t\t)))\t\t\t\t),\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()"},"style_context_codestyle":{"kind":"number","value":297,"string":"297"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":223,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t\t\t\t_A (\t\t\t\t\t\tlowerCAmelCase_\t\t\t\t\t: int ):\r\n \"\"\"simple docstring\"\"\"\r\n\r\n return str(lowerCAmelCase_ ) == str(lowerCAmelCase_ )[::-1]\r\n\r\n\r\n\r\ndef \t\t\t\t\t\t\t_A (\t\t\t\t\t\tlowerCAmelCase_\t\t\t\t\t: int ):\r\n \"\"\"simple docstring\"\"\"\r\n\r\n return int(lowerCAmelCase_ ) + int(str(lowerCAmelCase_ )[::-1] )\r\n\r\n\r\n\r\ndef \t\t\t\t\t\t\t_A (\t\t\t\t\t\tlowerCAmelCase_\t\t\t\t\t: int = 1_0000 ):\r\n \"\"\"simple docstring\"\"\"\r\n\r\n lowerCAmelCase__ =\t\t\t[]\r\n for num in range(1 , lowerCAmelCase_ ):\r\n lowerCAmelCase__ =\t\t\t0\r\n lowerCAmelCase__ =\t\t\tnum\r\n while iterations < 50:\r\n lowerCAmelCase__ =\t\t\tsum_reverse(lowerCAmelCase_ )\r\n iterations += 1\r\n if is_palindrome(lowerCAmelCase_ ):\r\n break\r\n else:\r\n lychrel_nums.append(lowerCAmelCase_ )\r\n return len(lowerCAmelCase_ )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(F\"\"\"{solution() = }\"\"\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":370,"string":"370"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\nfrom math import pi, sqrt\r\n\r\n\r\n\r\ndef \t\t\t\t\t\t\t_A (\t\t\t\t\t\tlowerCAmelCase_\t\t\t\t\t: float ):\r\n \"\"\"simple docstring\"\"\"\r\n\r\n if num <= 0:\r\n raise ValueError(\"math domain error\" )\r\n if num > 171.5:\r\n raise OverflowError(\"math range error\" )\r\n elif num - int(lowerCAmelCase_ ) not in (0, 0.5):\r\n raise NotImplementedError(\"num must be an integer or a half-integer\" )\r\n elif num == 0.5:\r\n return sqrt(lowerCAmelCase_ )\r\n else:\r\n return 1.0 if num == 1 else (num - 1) * gamma(num - 1 )\r\n\r\n\r\n\r\ndef \t\t\t\t\t\t\t_A (\t\t\t\t\t\t):\r\n \"\"\"simple docstring\"\"\"\r\n\r\n assert gamma(0.5 ) == sqrt(lowerCAmelCase_ )\r\n assert gamma(1 ) == 1.0\r\n assert gamma(2 ) == 1.0\r\n\r\n\r\nif __name__ == \"__main__\":\r\n from doctest import testmod\r\n\r\n testmod()\r\n UpperCamelCase\t\t\t\t\t\t\t\t=\t\t\t\t\t1.0\r\n while num:\r\n UpperCamelCase\t\t\t\t\t\t\t\t=\t\t\t\t\tfloat(input('Gamma of: '))\r\n print(F\"\"\"gamma({num}) = {gamma(num)}\"\"\")\r\n print('\\nEnter 0 to exit...')\r\n"},"style_context_codestyle":{"kind":"number","value":221,"string":"221"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":224,"cells":{"code":{"kind":"string","value":"\r\r\rimport json\rimport sys\rimport tempfile\rimport unittest\rfrom pathlib import Path\r\rimport transformers\rfrom transformers import (\r CONFIG_MAPPING,\r IMAGE_PROCESSOR_MAPPING,\r AutoConfig,\r AutoImageProcessor,\r CLIPConfig,\r CLIPImageProcessor,\r)\rfrom transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER\r\r\rsys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))\r\rfrom test_module.custom_configuration import CustomConfig # noqa E402\rfrom test_module.custom_image_processing import CustomImageProcessor # noqa E402\rclass _lowercase (\t\t\tunittest.TestCase ):\r\r\r\r\r\r\r\t\t\t\t'''simple docstring'''\r\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:int\t)\t\t->\t\t\tDict:\r\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Dict\t\t\t\t\t=\t\t0\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:Dict\t)\t\t->\t\t\tAny:\r\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Dict\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''\t)\r\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:List[Any]\t)\t\t->\t\t\tOptional[int]:\r\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdirname:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Tuple\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''preprocessor_config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[Any]\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t\t\t,\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump({'''model_type''': '''clip'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: int\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:Any\t)\t\t->\t\t\tstr:\r\t\t\t\t\t\t\t\t\t\t# Ensure we can load the image processor from the feature extractor config\r\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdirname:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: str\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''preprocessor_config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t\t\t,\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump({'''model_type''': '''clip'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:int\t)\t\t->\t\t\tUnion[str, Any]:\r\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdirname:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[str]\t\t\t\t\t=\t\tCLIPConfig()\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Create a dummy config file with image_proceesor_type\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Tuple\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''preprocessor_config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[Any]\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t\t\t,\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump({'''model_type''': '''clip'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# remove image_processor_type to make sure config.json alone is enough to load image processor locally\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Any\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t).to_dict()\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfig_dict.pop('''image_processor_type'''\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Dict\t\t\t\t\t=\t\tCLIPImageProcessor(**lowerCAmelCase__\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# save in new folder\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmodel_config.save_pretrained(lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfig.save_pretrained(lowerCAmelCase__\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Dict\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# make sure private variable is not incorrectly saved\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[str]\t\t\t\t\t=\t\tjson.loads(config.to_json_string()\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue('''_processor_class''' not in dict_as_saved\t)\r\r\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:str\t)\t\t->\t\t\tOptional[Any]:\r\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdirname:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Tuple\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''preprocessor_config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t\t\t,\t\t\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Optional[int]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:int\t)\t\t->\t\t\tUnion[str, Any]:\r\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(\r\t\t\t\t\t\t\t\t\t\t lowerCAmelCase__\t\t\t,\t\t\t'''clip-base is not a local folder and is not a valid model identifier'''\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Dict\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained('''clip-base'''\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:Dict\t)\t\t->\t\t\tDict:\r\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(\r\t\t\t\t\t\t\t\t\t\t lowerCAmelCase__\t\t\t,\t\t\tr'''aaaaaa is not a valid git identifier \\(branch name, tag name or commit id\\)'''\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Tuple\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t\t\t,\t\t\trevision='''aaaaaa'''\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:Tuple\t)\t\t->\t\t\tList[str]:\r\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(\r\t\t\t\t\t\t\t\t\t\t lowerCAmelCase__\t\t\t,\t\t\t'''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''\t\t\t,\t\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:Optional[Any]\t)\t\t->\t\t\tstr:\r\t\t\t\t\t\t\t\t\t\t# If remote code is not set, we will time out when asking whether to load the model.\r\t\t\t\t\t\t\t\t\t\twith self.assertRaises(lowerCAmelCase__\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Optional[int]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''\t)\r\t\t\t\t\t\t\t\t\t\t# If remote code is disabled, we can't load this config.\r\t\t\t\t\t\t\t\t\t\twith self.assertRaises(lowerCAmelCase__\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_image_processor'''\t\t\t,\t\t\ttrust_remote_code=lowerCAmelCase__\t)\r\r\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: int\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(\r\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_image_processor'''\t\t\t,\t\t\ttrust_remote_code=lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\tself.assertEqual(image_processor.__class__.__name__\t\t\t,\t\t\t'''NewImageProcessor'''\t)\r\r\t\t\t\t\t\t\t\t\t\t# Test image processor can be reloaded.\r\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timage_processor.save_pretrained(lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[str]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t\t\t,\t\t\ttrust_remote_code=lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\tself.assertEqual(reloaded_image_processor.__class__.__name__\t\t\t,\t\t\t'''NewImageProcessor'''\t)\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:Dict\t)\t\t->\t\t\tTuple:\r\t\t\t\t\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoConfig.register('''custom'''\t\t\t,\t\t\tlowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoImageProcessor.register(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Trying to register something existing in the Transformers library will raise an error\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaises(lowerCAmelCase__\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoImageProcessor.register(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdirname:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Dict\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''preprocessor_config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[Any]\t\t\t\t\t=\t\tPath(lowerCAmelCase__\t) / '''config.json'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t\t\t,\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump({'''model_type''': '''clip'''}\t\t\t,\t\t\topen(lowerCAmelCase__\t\t\t,\t\t\t'''w'''\t)\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[str]\t\t\t\t\t=\t\tCustomImageProcessor.from_pretrained(lowerCAmelCase__\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Now that the config is registered, it can be used as any other config with the auto-API\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timage_processor.save_pretrained(lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: str\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\r\t\t\t\t\t\t\t\t\t\tfinally:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"custom\" in CONFIG_MAPPING._extra_content:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel CONFIG_MAPPING._extra_content[\"custom\"]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]\r\r\r\r\t\t\t\tdef \t\t__magic_name__( self\t\t\t:List[Any]\t)\t\t->\t\t\tint:\r\t\t\t\t\t\t\t\t\t\tclass _lowercase (\t\t\tA__ ):\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t=\t\tTrue\r\r\t\t\t\t\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoConfig.register('''custom'''\t\t\t,\t\t\tlowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoImageProcessor.register(lowerCAmelCase__\t\t\t,\t\t\tlowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If remote code is not set, the default is to use local\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: str\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(image_processor.__class__.__name__\t\t\t,\t\t\t'''NewImageProcessor'''\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(image_processor.is_local\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If remote code is disabled, we load the local one.\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: List[str]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_image_processor'''\t\t\t,\t\t\ttrust_remote_code=lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(image_processor.__class__.__name__\t\t\t,\t\t\t'''NewImageProcessor'''\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(image_processor.is_local\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If remote is enabled, we load from the Hub\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t\t\t: Optional[int]\t\t\t\t\t=\t\tAutoImageProcessor.from_pretrained(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_image_processor'''\t\t\t,\t\t\ttrust_remote_code=lowerCAmelCase__\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(image_processor.__class__.__name__\t\t\t,\t\t\t'''NewImageProcessor'''\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(not hasattr(lowerCAmelCase__\t\t\t,\t\t\t'''is_local'''\t)\t)\r\r\t\t\t\t\t\t\t\t\t\tfinally:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"custom\" in CONFIG_MAPPING._extra_content:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel CONFIG_MAPPING._extra_content[\"custom\"]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]\r"},"code_codestyle":{"kind":"number","value":9,"string":"9"},"style_context":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\n\n\n\nimport argparse\nimport json\n\nimport gdown\nimport numpy as np\nimport torch\nfrom huggingface_hub import hf_hub_download\n\nfrom transformers import (\n VideoMAEConfig,\n VideoMAEForPreTraining,\n VideoMAEForVideoClassification,\n VideoMAEImageProcessor,\n)\n\n\n\ndef \ta\t\t\t( lowerCamelCase__ ):\n\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\tA_\t:\t\t\t\t\t\tOptional[int]\t= VideoMAEConfig()\n\n\t\t\tset_architecture_configs(lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__ )\n\n\t\t\tif \"finetuned\" not in model_name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= False\n\n\t\t\tif \"finetuned\" in model_name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= \"\"\"huggingface/label-files\"\"\"\n\t\t\t\t\t\tif \"kinetics\" in model_name:\n\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= 4_00\n\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= \"\"\"kinetics400-id2label.json\"\"\"\n\t\t\t\t\t\telif \"ssv2\" in model_name:\n\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tTuple\t= 1_74\n\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= \"\"\"something-something-v2-id2label.json\"\"\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\traise ValueError(\"\"\"Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned.\"\"\" )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= json.load(open(hf_hub_download(lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__\t\t\t\t\t\t, repo_type=\"\"\"dataset\"\"\" )\t\t\t\t\t\t, \"\"\"r\"\"\" ) )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= {int(lowerCamelCase__ ): v for k, v in idalabel.items()}\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= idalabel\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= {v: k for k, v in idalabel.items()}\n\n\t\t\treturn config\n\n\n\ndef \ta\t\t\t( lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__ ):\n\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\tif \"small\" in model_name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= 3_84\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= 15_36\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= 12\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[int]\t= 16\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= 12\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= 3\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= 1_92\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= 7_68\n\t\t\telif \"large\" in model_name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= 10_24\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= 40_96\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= 24\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= 16\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= 12\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= 8\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= 5_12\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= 20_48\n\t\t\telif \"huge\" in model_name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= 12_80\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= 51_20\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= 32\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= 16\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= 12\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= 8\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= 6_40\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= 25_60\n\t\t\telif \"base\" not in model_name:\n\t\t\t\t\t\traise ValueError(\"\"\"Model name should include either \\\"small\\\", \\\"base\\\", \\\"large\\\", or \\\"huge\\\"\"\"\" )\n\n\n\ndef \ta\t\t\t( lowerCamelCase__ ):\n\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\tif \"encoder.\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= name.replace(\"\"\"encoder.\"\"\"\t\t\t\t\t\t, \"\"\"\"\"\" )\n\t\t\tif \"cls_token\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= name.replace(\"\"\"cls_token\"\"\"\t\t\t\t\t\t, \"\"\"videomae.embeddings.cls_token\"\"\" )\n\t\t\tif \"decoder_pos_embed\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tTuple\t= name.replace(\"\"\"decoder_pos_embed\"\"\"\t\t\t\t\t\t, \"\"\"decoder.decoder_pos_embed\"\"\" )\n\t\t\tif \"pos_embed\" in name and \"decoder\" not in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= name.replace(\"\"\"pos_embed\"\"\"\t\t\t\t\t\t, \"\"\"videomae.embeddings.position_embeddings\"\"\" )\n\t\t\tif \"patch_embed.proj\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= name.replace(\"\"\"patch_embed.proj\"\"\"\t\t\t\t\t\t, \"\"\"videomae.embeddings.patch_embeddings.projection\"\"\" )\n\t\t\tif \"patch_embed.norm\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= name.replace(\"\"\"patch_embed.norm\"\"\"\t\t\t\t\t\t, \"\"\"videomae.embeddings.norm\"\"\" )\n\t\t\tif \"decoder.blocks\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= name.replace(\"\"\"decoder.blocks\"\"\"\t\t\t\t\t\t, \"\"\"decoder.decoder_layers\"\"\" )\n\t\t\tif \"blocks\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= name.replace(\"\"\"blocks\"\"\"\t\t\t\t\t\t, \"\"\"videomae.encoder.layer\"\"\" )\n\t\t\tif \"attn.proj\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= name.replace(\"\"\"attn.proj\"\"\"\t\t\t\t\t\t, \"\"\"attention.output.dense\"\"\" )\n\t\t\tif \"attn\" in name and \"bias\" not in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= name.replace(\"\"\"attn\"\"\"\t\t\t\t\t\t, \"\"\"attention.self\"\"\" )\n\t\t\tif \"attn\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= name.replace(\"\"\"attn\"\"\"\t\t\t\t\t\t, \"\"\"attention.attention\"\"\" )\n\t\t\tif \"norm1\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= name.replace(\"\"\"norm1\"\"\"\t\t\t\t\t\t, \"\"\"layernorm_before\"\"\" )\n\t\t\tif \"norm2\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= name.replace(\"\"\"norm2\"\"\"\t\t\t\t\t\t, \"\"\"layernorm_after\"\"\" )\n\t\t\tif \"mlp.fc1\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= name.replace(\"\"\"mlp.fc1\"\"\"\t\t\t\t\t\t, \"\"\"intermediate.dense\"\"\" )\n\t\t\tif \"mlp.fc2\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= name.replace(\"\"\"mlp.fc2\"\"\"\t\t\t\t\t\t, \"\"\"output.dense\"\"\" )\n\t\t\tif \"decoder_embed\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= name.replace(\"\"\"decoder_embed\"\"\"\t\t\t\t\t\t, \"\"\"decoder.decoder_embed\"\"\" )\n\t\t\tif \"decoder_norm\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tTuple\t= name.replace(\"\"\"decoder_norm\"\"\"\t\t\t\t\t\t, \"\"\"decoder.decoder_norm\"\"\" )\n\t\t\tif \"decoder_pred\" in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tTuple\t= name.replace(\"\"\"decoder_pred\"\"\"\t\t\t\t\t\t, \"\"\"decoder.decoder_pred\"\"\" )\n\t\t\tif \"norm.weight\" in name and \"decoder\" not in name and \"fc\" not in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= name.replace(\"\"\"norm.weight\"\"\"\t\t\t\t\t\t, \"\"\"videomae.layernorm.weight\"\"\" )\n\t\t\tif \"norm.bias\" in name and \"decoder\" not in name and \"fc\" not in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= name.replace(\"\"\"norm.bias\"\"\"\t\t\t\t\t\t, \"\"\"videomae.layernorm.bias\"\"\" )\n\t\t\tif \"head\" in name and \"decoder\" not in name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= name.replace(\"\"\"head\"\"\"\t\t\t\t\t\t, \"\"\"classifier\"\"\" )\n\n\t\t\treturn name\n\n\n\ndef \ta\t\t\t( lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__ ):\n\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\tfor key in orig_state_dict.copy().keys():\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= orig_state_dict.pop(lowerCamelCase__ )\n\n\t\t\t\t\t\tif key.startswith(\"\"\"encoder.\"\"\" ):\n\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tTuple\t= key.replace(\"\"\"encoder.\"\"\"\t\t\t\t\t\t, \"\"\"\"\"\" )\n\n\t\t\t\t\t\tif \"qkv\" in key:\n\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[int]\t= key.split(\"\"\".\"\"\" )\n\t\t\t\t\t\t\t\t\tif key.startswith(\"\"\"decoder.blocks\"\"\" ):\n\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= config.decoder_hidden_size\n\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= int(key_split[2] )\n\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= \"\"\"decoder.decoder_layers.\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\tif \"weight\" in key:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= val[:dim, :]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= val[dim : dim * 2, :]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= val[-dim:, :]\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= config.hidden_size\n\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= int(key_split[1] )\n\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= \"\"\"videomae.encoder.layer.\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\tif \"weight\" in key:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= val[:dim, :]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= val[dim : dim * 2, :]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= val[-dim:, :]\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= val\n\n\t\t\treturn orig_state_dict\n\n\n\ndef \ta\t\t\t( ):\n\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= hf_hub_download(\n\t\t\t repo_id=\"\"\"hf-internal-testing/spaghetti-video\"\"\"\t\t\t\t\t\t, filename=\"\"\"eating_spaghetti.npy\"\"\"\t\t\t\t\t\t, repo_type=\"\"\"dataset\"\"\" )\n\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= np.load(lowerCamelCase__ )\n\t\t\treturn list(lowerCamelCase__ )\n\n\n\ndef \ta\t\t\t( lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__ ):\n\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\tA_\t:\t\t\t\t\t\tAny\t= get_videomae_config(lowerCamelCase__ )\n\n\t\t\tif \"finetuned\" in model_name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= VideoMAEForVideoClassification(lowerCamelCase__ )\n\t\t\telse:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= VideoMAEForPreTraining(lowerCamelCase__ )\n\n\t\t\t# download original checkpoint, hosted on Google Drive\n\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= \"\"\"pytorch_model.bin\"\"\"\n\t\t\tgdown.cached_download(lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__\t\t\t\t\t\t, quiet=lowerCamelCase__ )\n\t\t\tA_\t:\t\t\t\t\t\tAny\t= torch.load(lowerCamelCase__\t\t\t\t\t\t, map_location=\"\"\"cpu\"\"\" )\n\t\t\tif \"model\" in files:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= files[\"\"\"model\"\"\"]\n\t\t\telse:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= files[\"\"\"module\"\"\"]\n\t\t\tA_\t:\t\t\t\t\t\tAny\t= convert_state_dict(lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__ )\n\n\t\t\tmodel.load_state_dict(lowerCamelCase__ )\n\t\t\tmodel.eval()\n\n\t\t\t# verify model on basic input\n\t\t\tA_\t:\t\t\t\t\t\tint\t= VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]\t\t\t\t\t\t, image_std=[0.5, 0.5, 0.5] )\n\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= prepare_video()\n\t\t\tA_\t:\t\t\t\t\t\tstr\t= image_processor(lowerCamelCase__\t\t\t\t\t\t, return_tensors=\"\"\"pt\"\"\" )\n\n\t\t\tif \"finetuned\" not in model_name:\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= hf_hub_download(repo_id=\"\"\"hf-internal-testing/bool-masked-pos\"\"\"\t\t\t\t\t\t, filename=\"\"\"bool_masked_pos.pt\"\"\" )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= torch.load(lowerCamelCase__ )\n\n\t\t\tA_\t:\t\t\t\t\t\tDict\t= model(**lowerCamelCase__ )\n\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= outputs.logits\n\n\t\t\tA_\t:\t\t\t\t\t\tAny\t= [\n\t\t\t \"\"\"videomae-small-finetuned-kinetics\"\"\",\n\t\t\t \"\"\"videomae-small-finetuned-ssv2\"\"\",\n\t\t\t # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)\n\t\t\t \"\"\"videomae-base-short\"\"\",\n\t\t\t \"\"\"videomae-base-short-finetuned-kinetics\"\"\",\n\t\t\t \"\"\"videomae-base\"\"\",\n\t\t\t \"\"\"videomae-base-finetuned-kinetics\"\"\",\n\t\t\t \"\"\"videomae-large\"\"\",\n\t\t\t \"\"\"videomae-large-finetuned-kinetics\"\"\",\n\t\t\t \"\"\"videomae-huge-finetuned-kinetics\"\"\",\n\t\t\t # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)\n\t\t\t \"\"\"videomae-base-short-ssv2\"\"\",\n\t\t\t \"\"\"videomae-base-short-finetuned-ssv2\"\"\",\n\t\t\t \"\"\"videomae-base-ssv2\"\"\",\n\t\t\t \"\"\"videomae-base-finetuned-ssv2\"\"\",\n\t\t\t]\n\n\t\t\t# NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]\n\t\t\tif model_name == \"videomae-small-finetuned-kinetics\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= torch.Size([1, 4_00] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= torch.tensor([-0.9_291, -0.4_061, -0.9_307] )\n\t\t\telif model_name == \"videomae-small-finetuned-ssv2\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= torch.Size([1, 1_74] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= torch.tensor([0.2_671, -0.4_689, -0.8_235] )\n\t\t\telif model_name == \"videomae-base\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tTuple\t= torch.Size([1, 14_08, 15_36] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= torch.tensor([[0.7_739, 0.7_968, 0.7_089], [0.6_701, 0.7_487, 0.6_209], [0.4_287, 0.5_158, 0.4_773]] )\n\t\t\telif model_name == \"videomae-base-short\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= torch.Size([1, 14_08, 15_36] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[str]\t= torch.tensor([[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]] )\n\t\t\t\t\t\t# we verified the loss both for normalized and unnormalized targets for this one\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= torch.tensor([0.5_142] ) if config.norm_pix_loss else torch.tensor([0.6_469] )\n\t\t\telif model_name == \"videomae-large\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= torch.Size([1, 14_08, 15_36] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= torch.tensor([[0.7_149, 0.7_997, 0.6_966], [0.6_768, 0.7_869, 0.6_948], [0.5_139, 0.6_221, 0.5_605]] )\n\t\t\telif model_name == \"videomae-large-finetuned-kinetics\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tint\t= torch.Size([1, 4_00] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= torch.tensor([0.0_771, 0.0_011, -0.3_625] )\n\t\t\telif model_name == \"videomae-huge-finetuned-kinetics\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= torch.Size([1, 4_00] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[int]\t= torch.tensor([0.2_433, 0.1_632, -0.4_894] )\n\t\t\telif model_name == \"videomae-base-short-finetuned-kinetics\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= torch.Size([1, 4_00] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= torch.tensor([0.6_588, 0.0_990, -0.2_493] )\n\t\t\telif model_name == \"videomae-base-finetuned-kinetics\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tUnion[str, Any]\t= torch.Size([1, 4_00] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tTuple\t= torch.tensor([0.3_669, -0.0_688, -0.2_421] )\n\t\t\telif model_name == \"videomae-base-short-ssv2\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[Any]\t= torch.Size([1, 14_08, 15_36] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tList[Any]\t= torch.tensor([[0.4_712, 0.5_296, 0.5_786], [0.2_278, 0.2_729, 0.4_026], [0.0_352, 0.0_730, 0.2_506]] )\n\t\t\telif model_name == \"videomae-base-short-finetuned-ssv2\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= torch.Size([1, 1_74] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= torch.tensor([-0.0_537, -0.1_539, -0.3_266] )\n\t\t\telif model_name == \"videomae-base-ssv2\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= torch.Size([1, 14_08, 15_36] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tDict\t= torch.tensor([[0.8_131, 0.8_727, 0.8_546], [0.7_366, 0.9_377, 0.8_870], [0.5_935, 0.8_874, 0.8_564]] )\n\t\t\telif model_name == \"videomae-base-finetuned-ssv2\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tAny\t= torch.Size([1, 1_74] )\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tstr\t= torch.tensor([0.1_961, -0.8_337, -0.6_389] )\n\t\t\telse:\n\t\t\t\t\t\traise ValueError(f'Model name not supported. Should be one of {model_names}' )\n\n\t\t\t# verify logits\n\t\t\tassert logits.shape == expected_shape\n\t\t\tif \"finetuned\" in model_name:\n\t\t\t\t\t\tassert torch.allclose(logits[0, :3]\t\t\t\t\t\t, lowerCamelCase__\t\t\t\t\t\t, atol=1E-4 )\n\t\t\telse:\n\t\t\t\t\t\tprint(\"\"\"Logits:\"\"\"\t\t\t\t\t\t, logits[0, :3, :3] )\n\t\t\t\t\t\tassert torch.allclose(logits[0, :3, :3]\t\t\t\t\t\t, lowerCamelCase__\t\t\t\t\t\t, atol=1E-4 )\n\t\t\tprint(\"\"\"Logits ok!\"\"\" )\n\n\t\t\t# verify loss, if applicable\n\t\t\tif model_name == \"videomae-base-short\":\n\t\t\t\t\t\tA_\t:\t\t\t\t\t\tOptional[int]\t= outputs.loss\n\t\t\t\t\t\tassert torch.allclose(lowerCamelCase__\t\t\t\t\t\t, lowerCamelCase__\t\t\t\t\t\t, atol=1E-4 )\n\t\t\t\t\t\tprint(\"\"\"Loss ok!\"\"\" )\n\n\t\t\tif pytorch_dump_folder_path is not None:\n\t\t\t\t\t\tprint(f'Saving model and image processor to {pytorch_dump_folder_path}' )\n\t\t\t\t\t\timage_processor.save_pretrained(lowerCamelCase__ )\n\t\t\t\t\t\tmodel.save_pretrained(lowerCamelCase__ )\n\n\t\t\tif push_to_hub:\n\t\t\t\t\t\tprint(\"\"\"Pushing to the hub...\"\"\" )\n\t\t\t\t\t\tmodel.push_to_hub(lowerCamelCase__\t\t\t\t\t\t, organization=\"\"\"nielsr\"\"\" )\n\n\nif __name__ == \"__main__\":\n\t\t\t\t\t\tlowerCamelCase\t\t\t\t\t\t\t:Tuple\t\t\t\t =\t\t\t\t\targparse.ArgumentParser()\n\t\t\t\t\t\t# Required parameters\n\t\t\t\t\t\tparser.add_argument(\n\t\t\t\t\t\t '''--checkpoint_url''',\n\t\t\t\t\t\t default='''https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&export=download&confirm=t&uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4''',\n\t\t\t\t\t\t type=str,\n\t\t\t\t\t\t help=(\n\t\t\t\t\t\t '''URL of the original PyTorch checkpoint (on Google Drive) you\\'d like to convert. Should be a direct'''\n\t\t\t\t\t\t ''' download link.'''\n\t\t\t\t\t\t ),\n\t\t\t\t\t\t)\n\t\t\t\t\t\tparser.add_argument(\n\t\t\t\t\t\t '''--pytorch_dump_folder_path''',\n\t\t\t\t\t\t default='''/Users/nielsrogge/Documents/VideoMAE/Test''',\n\t\t\t\t\t\t type=str,\n\t\t\t\t\t\t help='''Path to the output PyTorch model directory.''',\n\t\t\t\t\t\t)\n\t\t\t\t\t\tparser.add_argument('''--model_name''', default='''videomae-base''', type=str, help='''Name of the model.''')\n\t\t\t\t\t\tparser.add_argument(\n\t\t\t\t\t\t '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\tlowerCamelCase\t\t\t\t\t\t\t:Union[str, Any]\t\t\t\t =\t\t\t\t\tparser.parse_args()\n\t\t\t\t\t\tconvert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)"},"style_context_codestyle":{"kind":"number","value":206,"string":"206"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":225,"cells":{"code":{"kind":"string","value":"\n\n\n\nfrom __future__ import annotations\n\nimport typing\nfrom collections.abc import Iterable\n\nimport numpy as np\n\n__A =\t\t\t\t\t\ttyping.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007\n__A =\t\t\t\t\t\ttyping.Union[np.floataa, int, float] # noqa: UP007\n\n\n\ndef \t__a\t\t\t\t\t( lowerCAmelCase_ : Vector ,lowerCAmelCase_ : Vector )\t\t\t\t->\t\t\tVectorOut:\n\n\n\n\n\n\n\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\treturn np.sqrt(np.sum((np.asarray(lowerCAmelCase_ ) - np.asarray(lowerCAmelCase_ )) ** 2 ) )\n\n\n\ndef \t__a\t\t\t\t\t( lowerCAmelCase_ : Vector ,lowerCAmelCase_ : Vector )\t\t\t\t->\t\t\tVectorOut:\n\n\n\n\n\n\n\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\treturn sum((va - va) ** 2 for va, va in zip(lowerCAmelCase_ ,lowerCAmelCase_ ) ) ** (1 / 2)\n\n\nif __name__ == \"__main__\":\n\n\n\n\tdef \t__a\t\t\t\t\t( )\t\t\t\t->\t\t\tNone:\n\n\n\n\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\t\tfrom timeit import timeit\n\n\t\t\t\t\t\t\tprint(\"\"\"Without Numpy\"\"\" )\n\t\t\t\t\t\t\tprint(\n\t\t\t\t\t\t\t timeit(\n\t\t\t\t\t\t\t \"\"\"euclidean_distance_no_np([1, 2, 3], [4, 5, 6])\"\"\" ,number=1_00_00 ,globals=globals() ,) )\n\t\t\t\t\t\t\tprint(\"\"\"With Numpy\"\"\" )\n\t\t\t\t\t\t\tprint(\n\t\t\t\t\t\t\t timeit(\n\t\t\t\t\t\t\t \"\"\"euclidean_distance([1, 2, 3], [4, 5, 6])\"\"\" ,number=1_00_00 ,globals=globals() ,) )\n\n\n\n\tbenchmark()\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":277,"string":"277"},"style_context":{"kind":"string","value":"\n\n\n\n__A =\t\t\t\t\t\t6_5521\n\n\n\ndef \t__a\t\t\t\t\t( lowerCAmelCase_ : str )\t\t\t\t->\t\t\tint:\n\n\n\n\n\n\n\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\t\t\t\t\t\tUpperCAmelCase_= 1\n\t\t\t\t\t\tUpperCAmelCase_= 0\n\t\t\t\t\t\tfor plain_chr in plain_text:\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase_= (a + ord(lowerCAmelCase_ )) % MOD_ADLER\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase_= (b + a) % MOD_ADLER\n\t\t\t\t\t\treturn (b << 16) | a\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":277,"string":"277"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":226,"cells":{"code":{"kind":"string","value":"\nfrom pickle import UnpicklingError\n\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nfrom flax.serialization import from_bytes\nfrom flax.traverse_util import flatten_dict\n\nfrom ..utils import logging\n\n\na__\t\t\t\t\t\t\t:\tDict \t\t\t\t\t\t=\t\t\tlogging.get_logger(__name__)\n\n\n\n\n\n\n\ndef \t\t\t\t\t\t\tUpperCAmelCase_( a__ ,\t\ta__\t\t\t\t\t):\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n try:\n with open(_lowerCamelCase ,\t\t'''rb'''\t\t\t\t\t) as flax_state_f:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t= from_bytes(_lowerCamelCase ,\t\tflax_state_f.read()\t\t\t\t\t)\n except UnpicklingError as e:\n try:\n with open(_lowerCamelCase\t\t\t\t\t) as f:\n if f.read().startswith('''version'''\t\t\t\t\t):\n raise OSError(\n '''You seem to have cloned a repository without having git-lfs installed. Please'''\n ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the'''\n ''' folder you cloned.'''\t\t\t\t\t)\n else:\n raise ValueError from e\n except (UnicodeDecodeError, ValueError):\n raise EnvironmentError(F\"\"\"Unable to convert {model_file} to Flax deserializable object. \"\"\"\t\t\t\t\t)\n\n return load_flax_weights_in_pytorch_model(_lowerCamelCase ,\t\t_lowerCamelCase\t\t\t\t\t)\n\n\n\n\n\n\n\ndef \t\t\t\t\t\t\tUpperCAmelCase_( a__ ,\t\ta__\t\t\t\t\t):\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n try:\n import torch # noqa: F401\n except ImportError:\n logger.error(\n '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see'''\n ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation'''\n ''' instructions.'''\t\t\t\t\t)\n raise\n\n # check if we have bf16 weights\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t= flatten_dict(jax.tree_util.tree_map(lambda a__\t\t\t\t\t: x.dtype == jnp.bfloataa ,\t\t_lowerCamelCase\t\t\t\t\t)\t\t\t\t\t).values()\n if any(_lowerCamelCase\t\t\t\t\t):\n # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16\n\n # and bf16 is not fully supported in PT yet.\n logger.warning(\n '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` '''\n '''before loading those in PyTorch model.'''\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= jax.tree_util.tree_map(\n lambda a__\t\t\t\t\t: params.astype(np.floataa\t\t\t\t\t) if params.dtype == jnp.bfloataa else params ,\t\t_lowerCamelCase\t\t\t\t\t)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t= \"\"\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= flatten_dict(_lowerCamelCase ,\t\tsep='''.'''\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= pt_model.state_dict()\n\n # keep track of unexpected & missing keys\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= []\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= set(pt_model_dict.keys()\t\t\t\t\t)\n\n for flax_key_tuple, flax_tensor in flax_state_dict.items():\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t= flax_key_tuple.split('''.'''\t\t\t\t\t)\n\n if flax_key_tuple_array[-1] == \"kernel\" and flax_tensor.ndim == 4:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t= flax_key_tuple_array[:-1] + [\"weight\"]\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= jnp.transpose(_lowerCamelCase ,\t\t(3, 2, 0, 1)\t\t\t\t\t)\n elif flax_key_tuple_array[-1] == \"kernel\":\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t= flax_key_tuple_array[:-1] + [\"weight\"]\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t= flax_tensor.T\n elif flax_key_tuple_array[-1] == \"scale\":\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t= flax_key_tuple_array[:-1] + [\"weight\"]\n\n if \"time_embedding\" not in flax_key_tuple_array:\n for i, flax_key_tuple_string in enumerate(_lowerCamelCase\t\t\t\t\t):\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= (\n flax_key_tuple_string.replace('''_0''' ,\t\t'''.0'''\t\t\t\t\t)\n .replace('''_1''' ,\t\t'''.1'''\t\t\t\t\t)\n .replace('''_2''' ,\t\t'''.2'''\t\t\t\t\t)\n .replace('''_3''' ,\t\t'''.3'''\t\t\t\t\t)\n .replace('''_4''' ,\t\t'''.4'''\t\t\t\t\t)\n .replace('''_5''' ,\t\t'''.5'''\t\t\t\t\t)\n .replace('''_6''' ,\t\t'''.6'''\t\t\t\t\t)\n .replace('''_7''' ,\t\t'''.7'''\t\t\t\t\t)\n .replace('''_8''' ,\t\t'''.8'''\t\t\t\t\t)\n .replace('''_9''' ,\t\t'''.9'''\t\t\t\t\t)\n )\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t= \".\".join(_lowerCamelCase\t\t\t\t\t)\n\n if flax_key in pt_model_dict:\n if flax_tensor.shape != pt_model_dict[flax_key].shape:\n raise ValueError(\n F\"\"\"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected \"\"\"\n F\"\"\"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.\"\"\"\t\t\t\t\t)\n else:\n # add weight to pytorch dict\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t= np.asarray(_lowerCamelCase\t\t\t\t\t) if not isinstance(_lowerCamelCase ,\t\tnp.ndarray\t\t\t\t\t) else flax_tensor\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t= torch.from_numpy(_lowerCamelCase\t\t\t\t\t)\n # remove from missing keys\n missing_keys.remove(_lowerCamelCase\t\t\t\t\t)\n else:\n # weight is not expected by PyTorch model\n unexpected_keys.append(_lowerCamelCase\t\t\t\t\t)\n\n pt_model.load_state_dict(_lowerCamelCase\t\t\t\t\t)\n\n # re-transform missing_keys to list\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= list(_lowerCamelCase\t\t\t\t\t)\n\n if len(_lowerCamelCase\t\t\t\t\t) > 0:\n logger.warning(\n '''Some weights of the Flax model were not used when initializing the PyTorch model'''\n F\"\"\" {pt_model.__class__.__name__}: {unexpected_keys}\\n- This IS expected if you are initializing\"\"\"\n F\"\"\" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture\"\"\"\n ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\\n- This'''\n F\"\"\" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect\"\"\"\n ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a'''\n ''' FlaxBertForSequenceClassification model).'''\t\t\t\t\t)\n if len(_lowerCamelCase\t\t\t\t\t) > 0:\n logger.warning(\n F\"\"\"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly\"\"\"\n F\"\"\" initialized: {missing_keys}\\nYou should probably TRAIN this model on a down-stream task to be able to\"\"\"\n ''' use it for predictions and inference.'''\t\t\t\t\t)\n\n return pt_model\n"},"code_codestyle":{"kind":"number","value":313,"string":"313"},"style_context":{"kind":"string","value":"\"\"\"simple docstring\"\"\"\n\n\n\n\n\nimport json\nimport os\nimport tempfile\nimport unittest\nimport unittest.mock as mock\nfrom pathlib import Path\n\nfrom requests.exceptions import HTTPError\n\nfrom transformers.utils import (\n CONFIG_NAME,\n FLAX_WEIGHTS_NAME,\n TF2_WEIGHTS_NAME,\n TRANSFORMERS_CACHE,\n WEIGHTS_NAME,\n cached_file,\n get_file_from_repo,\n has_file,\n)\n\n\n__A = '''hf-internal-testing/tiny-random-bert'''\n__A = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''')\n__A = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6'''\nclass _snake_case ( unittest.TestCase\t\t\t\t\t\t):\n\n\n\n\n\n\n\t\t\t\t\t\tdef \t\t\t\t\tlowerCamelCase__ (\t\t\t\tself\t\t\t\t\t:\tAny\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tDict\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t# Should have downloaded the file in here\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(os.path.isdir(UpperCAmelCase\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t# Cache should contain at least those three subfolders:\n\t\t\t\t\t\t\t\t\t\t\t\t\tfor subfolder in [\"blobs\", \"refs\", \"snapshots\"]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(os.path.isdir(os.path.join(UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\twith open(os.path.join(UpperCAmelCase\t\t\t\t\t\t\t, \"refs\"\t\t\t\t\t\t\t, \"main\"\t\t\t)\t\t\t) as f:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tDict\t\t\t\t\t\t = f.read()\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCAmelCase\t\t\t\t\t\t\t, os.path.join(UpperCAmelCase\t\t\t\t\t\t\t, \"snapshots\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(os.path.isfile(UpperCAmelCase\t\t\t)\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t# File is cached at the same place the second time.\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tTuple\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t# Using a specific revision to test the full commit hash.\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tList[str]\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t\t\t\t\t, revision=\"9b8c223\"\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCAmelCase\t\t\t\t\t\t\t, os.path.join(UpperCAmelCase\t\t\t\t\t\t\t, \"snapshots\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\t\t\t)\n\n\n\n\n\n\n\t\t\t\t\t\tdef \t\t\t\t\tlowerCamelCase__ (\t\t\t\tself\t\t\t\t\t:\tList[str]\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(UpperCAmelCase\t\t\t\t\t\t\t, \"is not a valid model identifier\"\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t = cached_file(\"tiny-random-bert\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(UpperCAmelCase\t\t\t\t\t\t\t, \"is not a valid git identifier\"\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tDict\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t\t\t\t\t, revision=\"aaaa\"\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(UpperCAmelCase\t\t\t\t\t\t\t, \"does not appear to have a file named\"\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tList[Any]\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, \"conf\"\t\t\t)\n\n\n\n\n\n\n\t\t\t\t\t\tdef \t\t\t\t\tlowerCamelCase__ (\t\t\t\tself\t\t\t\t\t:\tstr\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(UpperCAmelCase\t\t\t\t\t\t\t, \"does not appear to have a file named\"\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tAny\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, \"conf\"\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\twith open(os.path.join(UpperCAmelCase\t\t\t\t\t\t\t, \"refs\"\t\t\t\t\t\t\t, \"main\"\t\t\t)\t\t\t) as f:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tList[str]\t\t\t\t\t\t = f.read()\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase\t\t\t\t\t\t\t, \".no_exist\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t\t\t\t\t, \"conf\"\t\t\t)\t\t\t)\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tList[str]\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, \"conf\"\t\t\t\t\t\t\t, _raise_exceptions_for_missing_entries=UpperCAmelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsNone(UpperCAmelCase\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, \"conf\"\t\t\t\t\t\t\t, local_files_only=UpperCAmelCase\t\t\t\t\t\t\t, _raise_exceptions_for_missing_entries=UpperCAmelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsNone(UpperCAmelCase\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tstr\t\t\t\t\t\t = mock.Mock()\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t = 500\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tTuple\t\t\t\t\t\t = {}\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tDict\t\t\t\t\t\t = HTTPError\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tAny\t\t\t\t\t\t = {}\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t# Under the mock environment we get a 500 error when trying to reach the tokenizer.\n\t\t\t\t\t\t\t\t\t\t\t\t\twith mock.patch(\"requests.Session.request\"\t\t\t\t\t\t\t, return_value=UpperCAmelCase\t\t\t) as mock_head:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tAny\t\t\t\t\t\t = cached_file(UpperCAmelCase\t\t\t\t\t\t\t, \"conf\"\t\t\t\t\t\t\t, _raise_exceptions_for_connection_errors=UpperCAmelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsNone(UpperCAmelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# This check we did call the fake head request\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmock_head.assert_called()\n\n\n\n\n\n\n\t\t\t\t\t\tdef \t\t\t\t\tlowerCamelCase__ (\t\t\t\tself\t\t\t\t\t:\tstr\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(has_file(\"hf-internal-testing/tiny-bert-pt-only\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertFalse(has_file(\"hf-internal-testing/tiny-bert-pt-only\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertFalse(has_file(\"hf-internal-testing/tiny-bert-pt-only\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\t\t\t)\n\n\n\n\n\n\n\t\t\t\t\t\tdef \t\t\t\t\tlowerCamelCase__ (\t\t\t\tself\t\t\t\t\t:\tAny\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t# `get_file_from_repo` returns None if the file does not exist\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsNone(get_file_from_repo(\"bert-base-cased\"\t\t\t\t\t\t\t, \"ahah.txt\"\t\t\t)\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t# The function raises if the repository does not exist.\n\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(UpperCAmelCase\t\t\t\t\t\t\t, \"is not a valid model identifier\"\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tget_file_from_repo(\"bert-base-case\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t# The function raises if the revision does not exist.\n\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(UpperCAmelCase\t\t\t\t\t\t\t, \"is not a valid git identifier\"\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tget_file_from_repo(\"bert-base-cased\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t\t\t\t\t, revision=\"ahaha\"\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tstr\t\t\t\t\t\t = get_file_from_repo(\"bert-base-cased\"\t\t\t\t\t\t\t, UpperCAmelCase\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t# The name is the cached name which is not very easy to test, so instead we load the content.\n\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tTuple\t\t\t\t\t\t = json.loads(open(UpperCAmelCase\t\t\t\t\t\t\t, \"r\"\t\t\t).read()\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(config[\"hidden_size\"]\t\t\t\t\t\t\t, 768\t\t\t)\n\n\n\n\n\n\n\n\t\t\t\t\t\tdef \t\t\t\t\tlowerCamelCase__ (\t\t\t\tself\t\t\t\t\t:\tAny\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__lowerCamelCase :\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t = Path(UpperCAmelCase\t\t\t) / \"a.txt\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfilename.touch()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(get_file_from_repo(UpperCAmelCase\t\t\t\t\t\t\t, \"a.txt\"\t\t\t)\t\t\t\t\t\t\t, str(UpperCAmelCase\t\t\t)\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsNone(get_file_from_repo(UpperCAmelCase\t\t\t\t\t\t\t, \"b.txt\"\t\t\t)\t\t\t)"},"style_context_codestyle":{"kind":"number","value":135,"string":"135"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":227,"cells":{"code":{"kind":"string","value":"\r\r'''simple docstring'''\rdef \t_lowerCAmelCase (\t\t\t\t\t\t_UpperCamelCase\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] = 10_00 )\t\t\t\t-> int:\r \"\"\"simple docstring\"\"\"\r\r\r\r\r _SCREAMING_SNAKE_CASE ,\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t =1, 1\r _SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t =2\r while True:\r _SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t =0\r _SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t =fa + fa\r _SCREAMING_SNAKE_CASE ,\t\t\t\t\t\t_SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t =fa, f\r index += 1\r for _ in str(a__ ):\r i += 1\r if i == n:\r break\r return index\r\r\rif __name__ == \"__main__\":\r print(solution(int(str(input()).strip())))\r"},"code_codestyle":{"kind":"number","value":361,"string":"361"},"style_context":{"kind":"string","value":"\r\r'''simple docstring'''\rdef \t_lowerCAmelCase (\t\t\t\t\t\t_UpperCamelCase\t\t\t\t\t\t:\t\t\t\t\tfloat\t\t\t\t\t\t\t,\t\t\t_UpperCamelCase\t\t\t\t\t\t:\t\t\t\t\tfloat )\t\t\t\t-> float:\r \"\"\"simple docstring\"\"\"\r\r\r\r\r if mass < 0:\r raise ValueError('The mass of a body cannot be negative' )\r return 0.5 * mass * abs(_UpperCamelCase ) * abs(_UpperCamelCase )\r\r\rif __name__ == \"__main__\":\r import doctest\r\r doctest.testmod(verbose=True)\r"},"style_context_codestyle":{"kind":"number","value":114,"string":"114"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":228,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\nfrom typing import Dict\r\n\r\nimport numpy as np\r\nimport torch\r\n\r\nfrom . import residue_constants as rc\r\nfrom .tensor_utils import tensor_tree_map, tree_map\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : Dict[str, torch.Tensor]\t\t\t) -> List[Any]:\r\n\t\t__a =\t\t\t[]\r\n\t\t__a =\t\t\t[]\r\n\t\t__a =\t\t\t[]\r\n\r\n\t\tfor rt in rc.restypes:\r\n\t\t\t\t__a =\t\t\trc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]\r\n\t\t\t\trestype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names]\t\t\t)\r\n\t\t\t\t__a =\t\t\t{name: i for i, name in enumerate(snake_case__\t\t\t)}\r\n\t\t\t\trestype_atomaa_to_atomaa_list.append(\r\n\t\t\t\t [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types]\t\t\t)\r\n\r\n\t\t\t\trestype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names]\t\t\t)\r\n\r\n\t\t# Add dummy mapping for restype 'UNK'\r\n\t\trestype_atomaa_to_atomaa_list.append([0] * 14\t\t\t)\r\n\t\trestype_atomaa_to_atomaa_list.append([0] * 37\t\t\t)\r\n\t\trestype_atomaa_mask_list.append([0.0] * 14\t\t\t)\r\n\r\n\t\t__a =\t\t\ttorch.tensor(\r\n\t\t snake_case__ ,\t\t\t\t\tdtype=torch.intaa ,\t\t\t\t\tdevice=protein['''aatype'''].device ,\t\t\t\t\t)\r\n\t\t__a =\t\t\ttorch.tensor(\r\n\t\t snake_case__ ,\t\t\t\t\tdtype=torch.intaa ,\t\t\t\t\tdevice=protein['''aatype'''].device ,\t\t\t\t\t)\r\n\t\t__a =\t\t\ttorch.tensor(\r\n\t\t snake_case__ ,\t\t\t\t\tdtype=torch.floataa ,\t\t\t\t\tdevice=protein['''aatype'''].device ,\t\t\t\t\t)\r\n\t\t__a =\t\t\tprotein['''aatype'''].to(torch.long\t\t\t)\r\n\r\n\t\t# create the mapping for (residx, atom14) --> atom37, i.e. an array\r\n\t\t# with shape (num_res, 14) containing the atom37 indices for this protein\r\n\t\t__a =\t\t\trestype_atomaa_to_atomaa[protein_aatype]\r\n\t\t__a =\t\t\trestype_atomaa_mask[protein_aatype]\r\n\r\n\t\t__a =\t\t\tresidx_atomaa_mask\r\n\t\t__a =\t\t\tresidx_atomaa_to_atomaa.long()\r\n\r\n\t\t# create the gather indices for mapping back\r\n\t\t__a =\t\t\trestype_atomaa_to_atomaa[protein_aatype]\r\n\t\t__a =\t\t\tresidx_atomaa_to_atomaa.long()\r\n\r\n\t\t# create the corresponding mask\r\n\t\t__a =\t\t\ttorch.zeros([21, 37] ,\t\t\t\t\tdtype=torch.floataa ,\t\t\t\t\tdevice=protein['''aatype'''].device\t\t\t)\r\n\t\tfor restype, restype_letter in enumerate(rc.restypes\t\t\t):\r\n\t\t\t\t__a =\t\t\trc.restype_atoa[restype_letter]\r\n\t\t\t\t__a =\t\t\trc.residue_atoms[restype_name]\r\n\t\t\t\tfor atom_name in atom_names:\r\n\t\t\t\t\t\t__a =\t\t\trc.atom_order[atom_name]\r\n\t\t\t\t\t\t__a =\t\t\t1\r\n\r\n\t\t__a =\t\t\trestype_atomaa_mask[protein_aatype]\r\n\t\t__a =\t\t\tresidx_atomaa_mask\r\n\r\n\t\treturn protein\r\n\r\n\r\n\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : Dict[str, torch.Tensor]\t\t\t) -> Any:\r\n\t\t__a =\t\t\ttree_map(lambda lowerCAmelCase__\t\t\t: torch.tensor(snake_case__ ,\t\t\t\t\tdevice=batch['''aatype'''].device\t\t\t) ,\t\t\t\t\tsnake_case__ ,\t\t\t\t\tnp.ndarray\t\t\t)\r\n\t\t__a =\t\t\ttensor_tree_map(lambda lowerCAmelCase__\t\t\t: np.array(snake_case__\t\t\t) ,\t\t\t\t\tmake_atomaa_masks(snake_case__\t\t\t)\t\t\t)\r\n\t\treturn out\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":45,"string":"45"},"style_context":{"kind":"string","value":"\r\nimport os\r\n\r\n\r\n\r\n\r\ndef \t\t\t\ta\t\t\t\t\t\t(\t\t\t\t\t\t\t):\r\n\r\n\r\n\t\t\t\t'''simple docstring'''\r\n\t\t\t\tlowercase_ =\t\t\t\t\tos.path.join(os.path.dirname(snake_case__\t\t\t\t\t)\t\t\t\t\t\t, '''num.txt'''\t\t\t\t\t)\r\n\t\t\t\twith open(snake_case__\t\t\t\t\t) as file_hand:\r\n\t\t\t\t\t\t\t\treturn str(sum(int(snake_case__\t\t\t\t\t) for line in file_hand\t\t\t\t\t)\t\t\t\t\t)[:10]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\t\t\tprint(solution())\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":30,"string":"30"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":229,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nimport pytest\r\n\r\nfrom datasets.parallel import ParallelBackendConfig, parallel_backend\r\nfrom datasets.utils.py_utils import map_nested\r\n\r\nfrom .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows\r\ndef \t\tsnake_case_ (UpperCamelCase\t: int\t\t\t\t): # picklable for multiprocessing\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\t\t\t\t\t\t\treturn i + 1\r\n@require_dill_gt_0_3_2\r\n@require_joblibspark\r\n@require_not_windows\r\ndef \t\tsnake_case_ ():\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\t\t\t\t\t\t\twith parallel_backend('''spark'''\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert ParallelBackendConfig.backend_name == \"spark\"\r\n\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= [1, 2, 3]\r\n\t\t\t\t\t\t\twith pytest.raises(UpperCamelCase\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith parallel_backend('''unsupported backend'''\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmap_nested(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t,\t\t\t\t\t\tnum_proc=2\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\twith pytest.raises(UpperCamelCase\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith parallel_backend('''unsupported backend'''\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmap_nested(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t,\t\t\t\t\t\tnum_proc=-1\t\t\t\t)\r\n\r\n@require_dill_gt_0_3_2\r\n@require_joblibspark\r\n@require_not_windows\r\n@pytest.mark.parametrize('''num_proc'''\t\t\t,\t\t\t\t\t\t[2, -1]\t\t\t\t)\r\ndef \t\tsnake_case_ (UpperCamelCase\t: str\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= [1, 2]\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': 1, '''b''': 2}\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': [1, 2], '''b''': [3, 4]}\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': {'''1''': 1}, '''b''': 2}\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': 1, '''b''': 2, '''c''': 3, '''d''': 4}\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= [2, 3]\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': 2, '''b''': 3}\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': [2, 3], '''b''': [4, 5]}\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': {'''1''': 2}, '''b''': 3}\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= {'''a''': 2, '''b''': 3, '''c''': 4, '''d''': 5}\r\n\r\n\t\t\t\t\t\t\twith parallel_backend('''spark'''\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert map_nested(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t,\t\t\t\t\t\tnum_proc=UpperCamelCase\t\t\t\t) == expected_map_nested_sa\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert map_nested(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t,\t\t\t\t\t\tnum_proc=UpperCamelCase\t\t\t\t) == expected_map_nested_sa\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert map_nested(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t,\t\t\t\t\t\tnum_proc=UpperCamelCase\t\t\t\t) == expected_map_nested_sa\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert map_nested(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t,\t\t\t\t\t\tnum_proc=UpperCamelCase\t\t\t\t) == expected_map_nested_sa\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert map_nested(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t,\t\t\t\t\t\tnum_proc=UpperCamelCase\t\t\t\t) == expected_map_nested_sa\r\n\r\n"},"code_codestyle":{"kind":"number","value":179,"string":"179"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nimport json\r\nimport sys\r\nimport tempfile\r\nimport unittest\r\nfrom pathlib import Path\r\n\r\nimport transformers\r\nfrom transformers import (\r\n CONFIG_MAPPING,\r\n FEATURE_EXTRACTOR_MAPPING,\r\n AutoConfig,\r\n AutoFeatureExtractor,\r\n WavaVecaConfig,\r\n WavaVecaFeatureExtractor,\r\n)\r\nfrom transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir\r\n\r\n\r\nsys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))\r\n\r\nfrom test_module.custom_configuration import CustomConfig # noqa E402\r\nfrom test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402\r\n\r\n\r\n_snake_case\t\t\t\t:\t\t\t\tint \t\t\t\t\t\t\t=\t\tget_tests_dir('fixtures')\r\n_snake_case\t\t\t\t:\t\t\t\tTuple \t\t\t\t\t\t\t=\t\tget_tests_dir('fixtures/dummy_feature_extractor_config.json')\r\n_snake_case\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t\t\t\t=\t\tget_tests_dir('fixtures/dummy-config.json')\r\n\r\nclass A (\t\tunittest.TestCase ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: int ) ->\t\t\t\t\t\t\tList[Any]:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= 0\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: List[str] ) ->\t\t\t\t\t\t\tint:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained('''facebook/wav2vec2-base-960h''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: str ) ->\t\t\t\t\t\t\tTuple:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: List[str] ) ->\t\t\t\t\t\t\tAny:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdirname:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= WavaVecaConfig()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ ).to_dict()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfig_dict.pop('''feature_extractor_type''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= WavaVecaFeatureExtractor(**lowerCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# save in new folder\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmodel_config.save_pretrained(lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfig.save_pretrained(lowerCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# make sure private variable is not incorrectly saved\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= json.loads(config.to_json_string() )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue('''_processor_class''' not in dict_as_saved )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: Optional[Any] ) ->\t\t\t\t\t\t\tOptional[Any]:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: Optional[int] ) ->\t\t\t\t\t\t\tstr:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t lowerCAmelCase_\t\t\t\t\t\t\t, '''bert-base is not a local folder and is not a valid model identifier''' ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained('''bert-base''' )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: Tuple ) ->\t\t\t\t\t\t\tUnion[str, Any]:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t lowerCAmelCase_\t\t\t\t\t\t\t, R'''aaaaaa is not a valid git identifier \\(branch name, tag name or commit id\\)''' ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(lowerCAmelCase_\t\t\t\t\t\t\t, revision='''aaaaaa''' )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: Any ) ->\t\t\t\t\t\t\tDict:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaisesRegex(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t lowerCAmelCase_\t\t\t\t\t\t\t, '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'''\t\t\t\t\t\t\t, ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained('''hf-internal-testing/config-no-model''' )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: List[Any] ) ->\t\t\t\t\t\t\tAny:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaises(lowerCAmelCase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_feature_extractor''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If remote code is disabled, we can't load this config.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaises(lowerCAmelCase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_feature_extractor'''\t\t\t\t\t\t\t, trust_remote_code=lowerCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_feature_extractor'''\t\t\t\t\t\t\t, trust_remote_code=lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(feature_extractor.__class__.__name__\t\t\t\t\t\t\t, '''NewFeatureExtractor''' )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Test feature extractor can be reloaded.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfeature_extractor.save_pretrained(lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(lowerCAmelCase_\t\t\t\t\t\t\t, trust_remote_code=lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(reloaded_feature_extractor.__class__.__name__\t\t\t\t\t\t\t, '''NewFeatureExtractor''' )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: int ) ->\t\t\t\t\t\t\tOptional[Any]:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoConfig.register('''custom'''\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoFeatureExtractor.register(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Trying to register something existing in the Transformers library will raise an error\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaises(lowerCAmelCase_ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoFeatureExtractor.register(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Now that the config is registered, it can be used as any other config with the auto-API\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= CustomFeatureExtractor.from_pretrained(lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfeature_extractor.save_pretrained(lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfinally:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"custom\" in CONFIG_MAPPING._extra_content:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel CONFIG_MAPPING._extra_content[\"custom\"]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowerCAmelCase ( self\t: Optional[int] ) ->\t\t\t\t\t\t\tAny:\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass A (\t\t_a ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_ = True\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoConfig.register('''custom'''\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAutoFeatureExtractor.register(lowerCAmelCase_\t\t\t\t\t\t\t, lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If remote code is not set, the default is to use local\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_feature_extractor''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(feature_extractor.__class__.__name__\t\t\t\t\t\t\t, '''NewFeatureExtractor''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(feature_extractor.is_local )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If remote code is disabled, we load the local one.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_feature_extractor'''\t\t\t\t\t\t\t, trust_remote_code=lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(feature_extractor.__class__.__name__\t\t\t\t\t\t\t, '''NewFeatureExtractor''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(feature_extractor.is_local )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# If remote is enabled, we load from the Hub\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= AutoFeatureExtractor.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''hf-internal-testing/test_dynamic_feature_extractor'''\t\t\t\t\t\t\t, trust_remote_code=lowerCAmelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(feature_extractor.__class__.__name__\t\t\t\t\t\t\t, '''NewFeatureExtractor''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(not hasattr(lowerCAmelCase_\t\t\t\t\t\t\t, '''is_local''' ) )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfinally:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"custom\" in CONFIG_MAPPING._extra_content:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel CONFIG_MAPPING._extra_content[\"custom\"]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdel FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":179,"string":"179"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":230,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\nimport unittest\r\n\r\nfrom datasets import load_dataset\r\n\r\nfrom transformers import BloomTokenizerFast\r\nfrom transformers.testing_utils import require_tokenizers\r\n\r\nfrom ...test_tokenization_common import TokenizerTesterMixin\r\n\r\n\r\n\r\n@require_tokenizers\r\nclass \t\t\t\t\t\t\tA ( UpperCAmelCase__ , unittest.TestCase\t\t\t\t\t\t\t):\r\n\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__\t\t\t= None\r\n\t\t\t\t\tA__\t\t\t= BloomTokenizerFast\r\n\t\t\t\t\tA__\t\t\t= BloomTokenizerFast\r\n\t\t\t\t\tA__\t\t\t= True\r\n\t\t\t\t\tA__\t\t\t= False\r\n\t\t\t\t\tA__\t\t\t= '''tokenizer_file'''\r\n\t\t\t\t\tA__\t\t\t= {'''bos_token''': '''''', '''eos_token''': '''''', '''unk_token''': '''''', '''pad_token''': ''''''}\r\n\r\n\t\t\t\t\tdef lowerCamelCase__ (self :\t\t\t\t\t\tstr\t\t)\t\t\t\t\t\t-> int:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\tsuper().setUp()\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tBloomTokenizerFast.from_pretrained(\"\"\"bigscience/tokenizer\"\"\"\t\t)\r\n\t\t\t\t\t\t\ttokenizer.save_pretrained(self.tmpdirname\t\t)\r\n\r\n\t\t\t\t\tdef lowerCamelCase__ (self :\t\t\t\t\t\tList[str] ,\t\t\t\t\t**_UpperCAmelCase :\t\t\t\t\t\tstr\t\t)\t\t\t\t\t\t-> Optional[int]:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\tkwargs.update(self.special_tokens_map\t\t)\r\n\t\t\t\t\t\t\treturn BloomTokenizerFast.from_pretrained(self.tmpdirname ,\t\t\t\t\t**_UpperCAmelCase\t\t)\r\n\r\n\t\t\t\t\tdef lowerCamelCase__ (self :\t\t\t\t\t\tint\t\t)\t\t\t\t\t\t-> Any:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tself.get_rust_tokenizer()\r\n\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\t[\"\"\"The quick brown fox\"\"\", \"\"\"jumps over the lazy dog\"\"\"]\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\t[[2175, 2_3714, 7_3173, 14_4252, 2], [77, 13_2619, 3478, 368, 10_9586, 3_5433, 2]]\r\n\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\ttokenizer.batch_encode_plus(_UpperCAmelCase\t\t)[\"\"\"input_ids\"\"\"]\r\n\t\t\t\t\t\t\tself.assertListEqual(_UpperCAmelCase ,\t\t\t\t\t_UpperCAmelCase\t\t)\r\n\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\ttokenizer.batch_decode(_UpperCAmelCase\t\t)\r\n\t\t\t\t\t\t\tself.assertListEqual(_UpperCAmelCase ,\t\t\t\t\t_UpperCAmelCase\t\t)\r\n\r\n\t\t\t\t\tdef lowerCamelCase__ (self :\t\t\t\t\t\tUnion[str, Any] ,\t\t\t\t\t_UpperCAmelCase :\t\t\t\t\t\tUnion[str, Any]=6\t\t)\t\t\t\t\t\t-> Any:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\tfor tokenizer, pretrained_name, kwargs in self.tokenizers_list:\r\n\t\t\t\t\t\t\t\t\twith self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tself.rust_tokenizer_class.from_pretrained(_UpperCAmelCase ,\t\t\t\t\t**_UpperCAmelCase\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t# tokenizer_r.pad_token = None # Hotfixing padding = None\r\n\t\t\t\t\t\t\t\t\t\t\t# Simple input\r\n\t\t\t\t\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\t\"\"\"This is a simple input\"\"\"\r\n\t\t\t\t\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\t[\"\"\"This is a simple input 1\"\"\", \"\"\"This is a simple input 2\"\"\"]\r\n\t\t\t\t\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\t(\"\"\"This is a simple input\"\"\", \"\"\"This is a pair\"\"\")\r\n\t\t\t\t\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\t[\r\n\t\t\t\t\t\t\t\t\t\t\t (\"\"\"This is a simple input 1\"\"\", \"\"\"This is a simple input 2\"\"\"),\r\n\t\t\t\t\t\t\t\t\t\t\t (\"\"\"This is a simple pair 1\"\"\", \"\"\"This is a simple pair 2\"\"\"),\r\n\t\t\t\t\t\t\t\t\t\t\t]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t# Simple input tests\r\n\t\t\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\ttokenizer_r.encode(_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\ttokenizer_r.encode_plus(_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\ttokenizer_r.batch_encode_plus(_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\ttokenizer_r.encode(_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\ttokenizer_r.batch_encode_plus(_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.fail(\"\"\"Bloom Tokenizer should be able to deal with padding\"\"\"\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tNone # Hotfixing padding = None\r\n\t\t\t\t\t\t\t\t\t\t\tself.assertRaises(_UpperCAmelCase ,\t\t\t\t\ttokenizer_r.encode ,\t\t\t\t\t_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase ,\t\t\t\t\tpadding=\"\"\"max_length\"\"\"\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t# Simple input\r\n\t\t\t\t\t\t\t\t\t\t\tself.assertRaises(_UpperCAmelCase ,\t\t\t\t\ttokenizer_r.encode_plus ,\t\t\t\t\t_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase ,\t\t\t\t\tpadding=\"\"\"max_length\"\"\"\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t# Simple input\r\n\t\t\t\t\t\t\t\t\t\t\tself.assertRaises(\r\n\t\t\t\t\t\t\t\t\t\t\t _UpperCAmelCase ,\t\t\t\t\ttokenizer_r.batch_encode_plus ,\t\t\t\t\t_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase ,\t\t\t\t\tpadding=\"\"\"max_length\"\"\" ,\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t# Pair input\r\n\t\t\t\t\t\t\t\t\t\t\tself.assertRaises(_UpperCAmelCase ,\t\t\t\t\ttokenizer_r.encode ,\t\t\t\t\t_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase ,\t\t\t\t\tpadding=\"\"\"max_length\"\"\"\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t# Pair input\r\n\t\t\t\t\t\t\t\t\t\t\tself.assertRaises(_UpperCAmelCase ,\t\t\t\t\ttokenizer_r.encode_plus ,\t\t\t\t\t_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase ,\t\t\t\t\tpadding=\"\"\"max_length\"\"\"\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t# Pair input\r\n\t\t\t\t\t\t\t\t\t\t\tself.assertRaises(\r\n\t\t\t\t\t\t\t\t\t\t\t _UpperCAmelCase ,\t\t\t\t\ttokenizer_r.batch_encode_plus ,\t\t\t\t\t_UpperCAmelCase ,\t\t\t\t\tmax_length=_UpperCAmelCase ,\t\t\t\t\tpadding=\"\"\"max_length\"\"\" ,\t\t\t\t\t)\r\n\r\n\t\t\t\t\tdef lowerCamelCase__ (self :\t\t\t\t\t\tint\t\t)\t\t\t\t\t\t-> Any:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tself.get_rust_tokenizer()\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tload_dataset(\"\"\"xnli\"\"\" ,\t\t\t\t\t\"\"\"all_languages\"\"\" ,\t\t\t\t\tsplit=\"\"\"test\"\"\" ,\t\t\t\t\tstreaming=_UpperCAmelCase\t\t)\r\n\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tnext(iter(_UpperCAmelCase\t\t)\t\t)[\"\"\"premise\"\"\"] # pick up one data\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tlist(sample_data.values()\t\t)\r\n\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\tlist(map(tokenizer.encode ,\t\t\t\t\t_UpperCAmelCase\t\t)\t\t)\r\n\t\t\t\t\t\t\tlowercase__ \t\t\t=\t\t[tokenizer.decode(_UpperCAmelCase ,\t\t\t\t\tclean_up_tokenization_spaces=_UpperCAmelCase\t\t) for x in output_tokens]\r\n\t\t\t\t\t\t\tself.assertListEqual(_UpperCAmelCase ,\t\t\t\t\t_UpperCAmelCase\t\t)\r\n\r\n\r\n\t\t\t\t\tdef lowerCamelCase__ (self :\t\t\t\t\t\tstr\t\t)\t\t\t\t\t\t-> List[str]:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\tself.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map\t\t) ,\t\t\t\t\t1\t\t)\r\n\t\t\t\t\t\t\tself.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values()\t\t)[0]\t\t) ,\t\t\t\t\t1\t\t)\r\n\r\n"},"code_codestyle":{"kind":"number","value":305,"string":"305"},"style_context":{"kind":"string","value":"\r\n\r\n\r\nfrom typing import TYPE_CHECKING\r\n\r\nfrom ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available\r\nfrom ...utils import OptionalDependencyNotAvailable\r\n\r\n\r\nA :\t\tint = {'configuration_dpt': ['DPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DPTConfig']}\r\n\r\ntry:\r\n\tif not is_vision_available():\r\n\t\traise OptionalDependencyNotAvailable()\r\nexcept OptionalDependencyNotAvailable:\r\n\tpass\r\nelse:\r\n\tA :\t\tUnion[str, Any] = ['DPTFeatureExtractor']\r\n\tA :\t\tint = ['DPTImageProcessor']\r\n\r\ntry:\r\n\tif not is_torch_available():\r\n\t\traise OptionalDependencyNotAvailable()\r\nexcept OptionalDependencyNotAvailable:\r\n\tpass\r\nelse:\r\n\tA :\t\tTuple = [\r\n\t 'DPT_PRETRAINED_MODEL_ARCHIVE_LIST',\r\n\t 'DPTForDepthEstimation',\r\n\t 'DPTForSemanticSegmentation',\r\n\t 'DPTModel',\r\n\t 'DPTPreTrainedModel',\r\n\t]\r\n\r\n\r\nif TYPE_CHECKING:\r\n\tfrom .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig\r\n\r\n\ttry:\r\n\t\tif not is_vision_available():\r\n\t\t\traise OptionalDependencyNotAvailable()\r\n\texcept OptionalDependencyNotAvailable:\r\n\t\tpass\r\n\telse:\r\n\t\tfrom .feature_extraction_dpt import DPTFeatureExtractor\r\n\t\tfrom .image_processing_dpt import DPTImageProcessor\r\n\r\n\ttry:\r\n\t\tif not is_torch_available():\r\n\t\t\traise OptionalDependencyNotAvailable()\r\n\texcept OptionalDependencyNotAvailable:\r\n\t\tpass\r\n\telse:\r\n\t\tfrom .modeling_dpt import (\r\n\t\t DPT_PRETRAINED_MODEL_ARCHIVE_LIST,\r\n\t\t DPTForDepthEstimation,\r\n\t\t DPTForSemanticSegmentation,\r\n\t\t DPTModel,\r\n\t\t DPTPreTrainedModel,\r\n\t\t)\r\n\r\n\r\nelse:\r\n\timport sys\r\n\r\n\tA :\t\tstr = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":305,"string":"305"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":231,"cells":{"code":{"kind":"string","value":"\r\nimport inspect\r\nimport os\r\nimport unittest\r\nfrom pathlib import Path\r\n\r\nimport torch\r\n\r\nimport accelerate\r\nfrom accelerate.test_utils import execute_subprocess_async\r\nfrom accelerate.test_utils.testing import run_command\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass \t\t\t\t\tA__\t\t\t\t\t\t\t(\t\t\t\t\tunittest.TestCase ):\r\n\t\t\t\tlowercase = inspect.getfile(accelerate.test_utils )\r\n\t\t\t\tlowercase = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['scripts', 'test_cli.py'] )\r\n\r\n\t\t\t\tlowercase = ['accelerate', 'launch']\r\n\t\t\t\tlowercase = Path.home() / '.cache/huggingface/accelerate'\r\n\t\t\t\tlowercase = 'default_config.yaml'\r\n\t\t\t\tlowercase = config_folder / config_file\r\n\t\t\t\tlowercase = config_folder / '_default_config.yaml'\r\n\r\n\t\t\t\tlowercase = Path('tests/test_configs' )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t@classmethod\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tcls :\t\t\t\tDict ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tif cls.config_path.is_file():\r\n\t\t\t\t\t\t\t\t\t\tcls.config_path.rename(cls.changed_path )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t@classmethod\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tcls :\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tif cls.changed_path.is_file():\r\n\t\t\t\t\t\t\t\t\t\tcls.changed_path.rename(cls.config_path )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tTuple ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\tself.base_cmd\r\n\t\t\t\t\t\t\tif torch.cuda.is_available() and (torch.cuda.device_count() > 1):\r\n\t\t\t\t\t\t\t\t\t\tcmd += [\"--multi_gpu\"]\r\n\t\t\t\t\t\t\texecute_subprocess_async(cmd + [self.test_file_path] ,\t\t\t\t\tenv=os.environ.copy() )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[int] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tfor config in sorted(self.test_config_path.glob('**/*.yaml' ) ):\r\n\t\t\t\t\t\t\t\t\t\twith self.subTest(config_file=a ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\texecute_subprocess_async(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t self.base_cmd + ['--config_file', str(a ), self.test_file_path] ,\t\t\t\t\tenv=os.environ.copy() )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\texecute_subprocess_async(['accelerate', 'test'] ,\t\t\t\t\tenv=os.environ.copy() )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass \t\t\t\t\tA__\t\t\t\t\t\t\t(\t\t\t\t\tunittest.TestCase ):\r\n\t\t\t\tlowercase = 'test-tpu'\r\n\t\t\t\tlowercase = 'us-central1-a'\r\n\t\t\t\tlowercase = 'ls'\r\n\t\t\t\tlowercase = ['accelerate', 'tpu-config']\r\n\t\t\t\tlowercase = 'cd /usr/share'\r\n\t\t\t\tlowercase = 'tests/test_samples/test_command_file.sh'\r\n\t\t\t\tlowercase = 'Running gcloud compute tpus tpu-vm ssh'\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd\r\n\t\t\t\t\t\t\t + ['--command', self.command, '--tpu_zone', self.tpu_zone, '--tpu_name', self.tpu_name, '--debug'] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[int] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd\r\n\t\t\t\t\t\t\t + [\r\n\t\t\t\t\t\t\t '--config_file',\r\n\t\t\t\t\t\t\t 'tests/test_configs/0_12_0.yaml',\r\n\t\t\t\t\t\t\t '--command',\r\n\t\t\t\t\t\t\t self.command,\r\n\t\t\t\t\t\t\t '--tpu_zone',\r\n\t\t\t\t\t\t\t self.tpu_zone,\r\n\t\t\t\t\t\t\t '--tpu_name',\r\n\t\t\t\t\t\t\t self.tpu_name,\r\n\t\t\t\t\t\t\t '--debug',\r\n\t\t\t\t\t\t\t ] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tList[str] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--debug'] ,\t\t\t\t\treturn_stdout=a )\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tint ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--command', self.command, '--debug'] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tTuple ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tstr \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd\r\n\t\t\t\t\t\t\t + [\r\n\t\t\t\t\t\t\t '--config_file',\r\n\t\t\t\t\t\t\t 'tests/test_configs/latest.yaml',\r\n\t\t\t\t\t\t\t '--command',\r\n\t\t\t\t\t\t\t self.command,\r\n\t\t\t\t\t\t\t '--command',\r\n\t\t\t\t\t\t\t 'echo \"Hello World\"',\r\n\t\t\t\t\t\t\t '--debug',\r\n\t\t\t\t\t\t\t ] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd\r\n\t\t\t\t\t\t\t + ['--config_file', 'tests/test_configs/latest.yaml', '--command_file', self.command_file, '--debug'] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[int] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tTuple \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd\r\n\t\t\t\t\t\t\t + [\r\n\t\t\t\t\t\t\t '--config_file',\r\n\t\t\t\t\t\t\t 'tests/test_configs/0_12_0.yaml',\r\n\t\t\t\t\t\t\t '--command_file',\r\n\t\t\t\t\t\t\t self.command_file,\r\n\t\t\t\t\t\t\t '--tpu_zone',\r\n\t\t\t\t\t\t\t self.tpu_zone,\r\n\t\t\t\t\t\t\t '--tpu_name',\r\n\t\t\t\t\t\t\t self.tpu_name,\r\n\t\t\t\t\t\t\t '--debug',\r\n\t\t\t\t\t\t\t ] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[Any] \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd + ['--config_file', 'tests/test_configs/latest.yaml', '--install_accelerate', '--debug'] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\trun_command(\r\n\t\t\t\t\t\t\t self.cmd\r\n\t\t\t\t\t\t\t + [\r\n\t\t\t\t\t\t\t '--config_file',\r\n\t\t\t\t\t\t\t 'tests/test_configs/latest.yaml',\r\n\t\t\t\t\t\t\t '--install_accelerate',\r\n\t\t\t\t\t\t\t '--accelerate_version',\r\n\t\t\t\t\t\t\t '12.0.0',\r\n\t\t\t\t\t\t\t '--debug',\r\n\t\t\t\t\t\t\t ] ,\t\t\t\t\treturn_stdout=a ,\t\t\t\t\t)\r\n\t\t\t\t\t\t\tself.assertIn(\r\n\t\t\t\t\t\t\t f'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all''' ,\t\t\t\t\ta ,\t\t\t\t\t)"},"code_codestyle":{"kind":"number","value":307,"string":"307"},"style_context":{"kind":"string","value":"\r\nimport torch\r\n\r\nfrom diffusers import DPMSolverSDEScheduler\r\nfrom diffusers.utils import torch_device\r\nfrom diffusers.utils.testing_utils import require_torchsde\r\n\r\nfrom .test_schedulers import SchedulerCommonTest\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n@require_torchsde\r\nclass \t\t\t\t\tA__\t\t\t\t\t\t\t(\t\t\t\t\t__magic_name__ ):\r\n\t\t\t\tlowercase = (DPMSolverSDEScheduler,)\r\n\t\t\t\tlowercase = 10\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[int] ,\t\t\t\t\t**a :\t\t\t\tUnion[str, Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t{\r\n\t\t\t\t\t\t\t 'num_train_timesteps': 1_100,\r\n\t\t\t\t\t\t\t 'beta_start': 0.0_0_0_1,\r\n\t\t\t\t\t\t\t 'beta_end': 0.0_2,\r\n\t\t\t\t\t\t\t 'beta_schedule': 'linear',\r\n\t\t\t\t\t\t\t 'noise_sampler_seed': 0,\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tconfig.update(**a )\r\n\t\t\t\t\t\t\treturn config\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tTuple ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tfor timesteps in [10, 50, 100, 1_000]:\r\n\t\t\t\t\t\t\t\t\t\tself.check_over_configs(num_train_timesteps=a )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tint ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tfor beta_start, beta_end in zip([0.0_0_0_0_1, 0.0_0_0_1, 0.0_0_1] ,\t\t\t\t\t[0.0_0_0_2, 0.0_0_2, 0.0_2] ):\r\n\t\t\t\t\t\t\t\t\t\tself.check_over_configs(beta_start=a ,\t\t\t\t\tbeta_end=a )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tOptional[int] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tfor schedule in [\"linear\", \"scaled_linear\"]:\r\n\t\t\t\t\t\t\t\t\t\tself.check_over_configs(beta_schedule=a )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tList[str] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tfor prediction_type in [\"epsilon\", \"v_prediction\"]:\r\n\t\t\t\t\t\t\t\t\t\tself.check_over_configs(prediction_type=a )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tUnion[str, Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tint \t\t\t\t=\t\tself.scheduler_classes[0]\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tTuple \t\t\t\t=\t\tself.get_scheduler_config()\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tList[Any] \t\t\t\t=\t\tscheduler_class(**a )\r\n\r\n\t\t\t\t\t\t\tscheduler.set_timesteps(self.num_inference_steps )\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\tself.dummy_model()\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tint \t\t\t\t=\t\tself.dummy_sample_deter * scheduler.init_noise_sigma\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tint \t\t\t\t=\t\tsample.to(a )\r\n\r\n\t\t\t\t\t\t\tfor i, t in enumerate(scheduler.timesteps ):\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tList[Any] \t\t\t\t=\t\tscheduler.scale_model_input(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tstr \t\t\t\t=\t\tmodel(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tint \t\t\t\t=\t\tscheduler.step(a ,\t\t\t\t\ta ,\t\t\t\t\ta )\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\toutput.prev_sample\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tList[Any] \t\t\t\t=\t\ttorch.sum(torch.abs(a ) )\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\ttorch.mean(torch.abs(a ) )\r\n\r\n\t\t\t\t\t\t\tif torch_device in [\"mps\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_6_7.4_7_8_2_1_0_4_4_9_2_1_8_7_5 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_1_7_8_7_0_5_9_6_4_5_6_5_2_7_7 ) < 1E-3\r\n\t\t\t\t\t\t\telif torch_device in [\"cuda\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_7_1.5_9_3_5_2_1_1_1_8_1_6_4_0_6 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_2_3_4_2_9_0_6_8_9_2_2_9_9_6_5_2 ) < 1E-3\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_6_2.5_2_3_8_3_4_2_2_8_5_1_5_6_2 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_1_1_6_1_9_5_7_0_8_5_1_3_2_6 ) < 1E-3\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tUnion[str, Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\tself.scheduler_classes[0]\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tList[str] \t\t\t\t=\t\tself.get_scheduler_config(prediction_type='v_prediction' )\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\tscheduler_class(**a )\r\n\r\n\t\t\t\t\t\t\tscheduler.set_timesteps(self.num_inference_steps )\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\tself.dummy_model()\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tUnion[str, Any] \t\t\t\t=\t\tself.dummy_sample_deter * scheduler.init_noise_sigma\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\tsample.to(a )\r\n\r\n\t\t\t\t\t\t\tfor i, t in enumerate(scheduler.timesteps ):\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tstr \t\t\t\t=\t\tscheduler.scale_model_input(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tstr \t\t\t\t=\t\tmodel(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\tscheduler.step(a ,\t\t\t\t\ta ,\t\t\t\t\ta )\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tTuple \t\t\t\t=\t\toutput.prev_sample\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tint \t\t\t\t=\t\ttorch.sum(torch.abs(a ) )\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tUnion[str, Any] \t\t\t\t=\t\ttorch.mean(torch.abs(a ) )\r\n\r\n\t\t\t\t\t\t\tif torch_device in [\"mps\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_2_4.7_7_1_4_9_2_0_0_4_3_9_4_5_3 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.1_6_2_2_6_2_8_9_0_1_4_8_1_6_2_8_4 ) < 1E-3\r\n\t\t\t\t\t\t\telif torch_device in [\"cuda\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_2_8.1_6_6_3_3_6_0_5_9_5_7_0_3 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.1_6_6_8_8_3_2_6_0_0_1_1_6_7_2_9_7 ) < 1E-3\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_1_9.8_4_8_7_5_4_8_8_2_8_1_2_5 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.1_5_6_0_5_3_0_6_6_2_5_3_6_6_2_1 ) < 1E-3\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\tself.scheduler_classes[0]\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\tself.get_scheduler_config()\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tint \t\t\t\t=\t\tscheduler_class(**a )\r\n\r\n\t\t\t\t\t\t\tscheduler.set_timesteps(self.num_inference_steps ,\t\t\t\t\tdevice=a )\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tTuple \t\t\t\t=\t\tself.dummy_model()\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\tself.dummy_sample_deter.to(a ) * scheduler.init_noise_sigma\r\n\r\n\t\t\t\t\t\t\tfor t in scheduler.timesteps:\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\tscheduler.scale_model_input(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\tmodel(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tTuple \t\t\t\t=\t\tscheduler.step(a ,\t\t\t\t\ta ,\t\t\t\t\ta )\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\toutput.prev_sample\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tUnion[str, Any] \t\t\t\t=\t\ttorch.sum(torch.abs(a ) )\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tDict \t\t\t\t=\t\ttorch.mean(torch.abs(a ) )\r\n\r\n\t\t\t\t\t\t\tif torch_device in [\"mps\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_6_7.4_6_9_5_7_3_9_7_4_6_0_9_3_8 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_1_8_0_5_9_3_4_6_0_7_9_8_2_6_3_5 ) < 1E-3\r\n\t\t\t\t\t\t\telif torch_device in [\"cuda\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_7_1.5_9_3_5_3_6_3_7_6_9_5_3_1_2 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_2_3_4_2_9_0_8_3_8_2_4_1_5_7_7_1 ) < 1E-3\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_6_2.5_2_3_8_3_4_2_2_8_5_1_5_6_2 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_1_1_6_1_9_5_7_0_8_5_1_3_2_6 ) < 1E-3\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef \t\t\t\t\t\t\t_lowerCamelCase\t\t(\t\t\t\t\t\tself :\t\t\t\tDict ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tTuple \t\t\t\t=\t\tself.scheduler_classes[0]\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\tself.get_scheduler_config()\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\tscheduler_class(**a ,\t\t\t\t\tuse_karras_sigmas=a )\r\n\r\n\t\t\t\t\t\t\tscheduler.set_timesteps(self.num_inference_steps ,\t\t\t\t\tdevice=a )\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tstr \t\t\t\t=\t\tself.dummy_model()\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\tself.dummy_sample_deter.to(a ) * scheduler.init_noise_sigma\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tstr \t\t\t\t=\t\tsample.to(a )\r\n\r\n\t\t\t\t\t\t\tfor t in scheduler.timesteps:\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\tscheduler.scale_model_input(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tint \t\t\t\t=\t\tmodel(a ,\t\t\t\t\ta )\r\n\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tUnion[str, Any] \t\t\t\t=\t\tscheduler.step(a ,\t\t\t\t\ta ,\t\t\t\t\ta )\r\n\t\t\t\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tUnion[str, Any] \t\t\t\t=\t\toutput.prev_sample\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tOptional[int] \t\t\t\t=\t\ttorch.sum(torch.abs(a ) )\r\n\t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t:\t\t\t\tAny \t\t\t\t=\t\ttorch.mean(torch.abs(a ) )\r\n\r\n\t\t\t\t\t\t\tif torch_device in [\"mps\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_7_6.6_6_9_7_4_1_3_5_7_4_2_1_8_8 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_3_0_0_3_8_7_2_7_3_0_9_8_1_8_1_1 ) < 1E-2\r\n\t\t\t\t\t\t\telif torch_device in [\"cuda\"]:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_7_7.6_3_6_5_3_5_6_4_4_5_3_1_2_5 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_3_0_0_3_8_7_2_7_3_0_9_8_1_8_1_1 ) < 1E-2\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_sum.item() - 1_7_0.3_1_3_5_2_2_3_3_8_8_6_7_2 ) < 1E-2\r\n\t\t\t\t\t\t\t\t\t\tassert abs(result_mean.item() - 0.2_3_0_0_3_8_7_2_7_3_0_9_8_1_8_1_1 ) < 1E-2"},"style_context_codestyle":{"kind":"number","value":307,"string":"307"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":232,"cells":{"code":{"kind":"string","value":"\n\n\n\n\nimport numpy\n\n# List of input, output pairs\nUpperCAmelCase_\t\t\t\t\t\t\t\t\t=\t(\n ((5, 2, 3), 15),\n ((6, 5, 9), 25),\n ((11, 12, 13), 41),\n ((1, 1, 1), 8),\n ((11, 12, 13), 41),\n)\nUpperCAmelCase_\t\t\t\t\t\t\t\t\t=\t(((515, 22, 13), 555), ((61, 35, 49), 150))\nUpperCAmelCase_\t\t\t\t\t\t\t\t\t=\t[2, 4, 1, 5]\nUpperCAmelCase_\t\t\t\t\t\t\t\t\t=\tlen(train_data)\nUpperCAmelCase_\t\t\t\t\t\t\t\t\t=\t0.009\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\tA__ :\t\t\t\t\tDict ,\t\t\tA__ :\t\t\t\t\tOptional[int]=\"train\"\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n return calculate_hypothesis_value(A__ ,\t\t\tA__\t) - output(\n A__ ,\t\t\tA__\t)\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\tA__ :\t\t\t\t\tList[Any]\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n __lowerCamelCase =\t\t\t\t\t\t0\n for i in range(len(A__\t) - 1\t):\n hyp_val += data_input_tuple[i] * parameter_vector[i + 1]\n hyp_val += parameter_vector[0]\n return hyp_val\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\tA__ :\t\t\t\t\tUnion[str, Any] ,\t\t\tA__ :\t\t\t\t\tDict\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n if data_set == \"train\":\n return train_data[example_no][1]\n elif data_set == \"test\":\n return test_data[example_no][1]\n return None\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\tA__ :\t\t\t\t\tDict ,\t\t\tA__ :\t\t\t\t\tint\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n if data_set == \"train\":\n return _hypothesis_value(train_data[example_no][0]\t)\n elif data_set == \"test\":\n return _hypothesis_value(test_data[example_no][0]\t)\n return None\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\tA__ :\t\t\t\t\tstr ,\t\t\tA__ :\t\t\t\t\tList[Any]=m\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n __lowerCamelCase =\t\t\t\t\t\t0\n for i in range(A__\t):\n if index == -1:\n summation_value += _error(A__\t)\n else:\n summation_value += _error(A__\t) * train_data[i][0][index]\n return summation_value\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\tA__ :\t\t\t\t\tstr\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n __lowerCamelCase =\t\t\t\t\t\tsummation_of_cost_derivative(A__ ,\t\t\tA__\t) / m\n return cost_derivative_value\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n global parameter_vector\n # Tune these values to set a tolerance value for predicted output\n __lowerCamelCase =\t\t\t\t\t\t0.000_002\n __lowerCamelCase =\t\t\t\t\t\t0\n __lowerCamelCase =\t\t\t\t\t\t0\n while True:\n j += 1\n __lowerCamelCase =\t\t\t\t\t\t[0, 0, 0, 0]\n for i in range(0 ,\t\t\tlen(A__\t)\t):\n __lowerCamelCase =\t\t\t\t\t\tget_cost_derivative(i - 1\t)\n __lowerCamelCase =\t\t\t\t\t\t(\n parameter_vector[i] - LEARNING_RATE * cost_derivative\n )\n if numpy.allclose(\n A__ ,\t\t\tA__ ,\t\t\tatol=A__ ,\t\t\trtol=A__ ,\t\t\t):\n break\n __lowerCamelCase =\t\t\t\t\t\ttemp_parameter_vector\n print((\"\"\"Number of iterations:\"\"\", j)\t)\n\n\n\n\ndef \t\t\t\t\tlowerCamelCase__ (\t\t\t\t\t\t):\n\n\n\n\n\n '''simple docstring'''\n\n\n\n for i in range(len(A__\t)\t):\n print((\"\"\"Actual output value:\"\"\", output(A__ ,\t\t\t\"\"\"test\"\"\"\t))\t)\n print((\"\"\"Hypothesis output:\"\"\", calculate_hypothesis_value(A__ ,\t\t\t\"\"\"test\"\"\"\t))\t)\n\n\nif __name__ == \"__main__\":\n run_gradient_descent()\n print('\\nTesting gradient descent for a linear hypothesis function.\\n')\n test_gradient_descent()\n\n"},"code_codestyle":{"kind":"number","value":12,"string":"12"},"style_context":{"kind":"string","value":"from __future__ import annotations\r\rfrom math import pi, sqrt\r\r\r\r\rdef _snake_case\t( lowerCAmelCase\t\t\t\t\t\t\t: float , lowerCAmelCase\t\t\t\t\t\t\t: float\t):\r\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\r\t\tif inductance <= 0:\r\t\t\t\traise ValueError(\"Inductance cannot be 0 or negative\"\t)\r\r\t\telif capacitance <= 0:\r\t\t\t\traise ValueError(\"Capacitance cannot be 0 or negative\"\t)\r\r\t\telse:\r\t\t\t\treturn (\r\t\t\t\t \"Resonant frequency\",\r\t\t\t\t float(1 / (2 * pi * (sqrt(inductance * capacitance\t)))\t),\r\t\t\t\t)\r\r\rif __name__ == \"__main__\":\r\t\timport doctest\r\r\t\tdoctest.testmod()\r"},"style_context_codestyle":{"kind":"number","value":18,"string":"18"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":233,"cells":{"code":{"kind":"string","value":"\n\n\n\n\nfrom __future__ import annotations\n\nimport numpy as np\n\n\n\n\n\n\n\ndef lowerCAmelCase_ (\t\t\t\t\tsnake_case_\t\t\t\t\t):\n _A , _A\t\t\t\t\t\t\t:\t\t\t\t\tAny =\t\t\t\t\t\tnp.shape(snake_case_\t\t\t\t\t)\n if rows != columns:\n _A\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] =\t\t\t\t\t\t(\n \"\"\"'table' has to be of square shaped array but got a \"\"\"\n f'''{rows}x{columns} array:\\n{table}'''\n )\n raise ValueError(snake_case_\t\t\t\t\t)\n\n _A\t\t\t\t\t\t\t:\t\t\t\t\tList[Any] =\t\t\t\t\t\tnp.zeros((rows, columns)\t\t\t\t\t)\n _A\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int] =\t\t\t\t\t\tnp.zeros((rows, columns)\t\t\t\t\t)\n for i in range(snake_case_\t\t\t\t\t):\n for j in range(snake_case_\t\t\t\t\t):\n _A\t\t\t\t\t\t\t:\t\t\t\t\tTuple =\t\t\t\t\t\tsum(lower[i][k] * upper[k][j] for k in range(snake_case_\t\t\t\t\t)\t\t\t\t\t)\n if upper[j][j] == 0:\n raise ArithmeticError(\"\"\"No LU decomposition exists\"\"\"\t\t\t\t\t)\n _A\t\t\t\t\t\t\t:\t\t\t\t\tTuple =\t\t\t\t\t\t(table[i][j] - total) / upper[j][j]\n _A\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int] =\t\t\t\t\t\t1\n for j in range(snake_case_,snake_case_\t\t\t\t\t):\n _A\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int] =\t\t\t\t\t\tsum(lower[i][k] * upper[k][j] for k in range(snake_case_\t\t\t\t\t)\t\t\t\t\t)\n _A\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] =\t\t\t\t\t\ttable[i][j] - total\n return lower, upper\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n"},"code_codestyle":{"kind":"number","value":343,"string":"343"},"style_context":{"kind":"string","value":"\n\n\n\n\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\n\nimport requests\nfrom bsa import BeautifulSoup\n\n_snake_case =\t\"https://www.indeed.co.in/jobs?q=mobile+app+development&l=\"\n\n\n\n\n\n\n\ndef lowerCAmelCase_ (\t\t\t\t\tsnake_case_ = \"mumbai\"\t\t\t\t\t):\n _A\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any] =\t\t\t\t\t\tBeautifulSoup(requests.get(url + location\t\t\t\t\t).content,\"\"\"html.parser\"\"\"\t\t\t\t\t)\n # This attribute finds out all the specifics listed in a job\n for job in soup.find_all(\"\"\"div\"\"\",attrs={\"\"\"data-tn-component\"\"\": \"\"\"organicJob\"\"\"}\t\t\t\t\t):\n _A\t\t\t\t\t\t\t:\t\t\t\t\tTuple =\t\t\t\t\t\tjob.find(\"\"\"a\"\"\",attrs={\"\"\"data-tn-element\"\"\": \"\"\"jobTitle\"\"\"}\t\t\t\t\t).text.strip()\n _A\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int] =\t\t\t\t\t\tjob.find(\"\"\"span\"\"\",{\"\"\"class\"\"\": \"\"\"company\"\"\"}\t\t\t\t\t).text.strip()\n yield job_title, company_name\n\n\nif __name__ == \"__main__\":\n for i, job in enumerate(fetch_jobs(\"Bangalore\"), 1):\n print(f\"\"\"Job {i:>2} is {job[0]} at {job[1]}\"\"\")\n\n"},"style_context_codestyle":{"kind":"number","value":343,"string":"343"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":234,"cells":{"code":{"kind":"string","value":"\n\n\nimport inspect\nimport re\n\nfrom transformers.utils import direct_transformers_import\n\n\n# All paths are set with the intent you should run this script from the root of the repo with the command\n# python utils/check_config_docstrings.py\nlowerCAmelCase__ :str \t\t\t=\t\t\t\t\t\t\t'''src/transformers'''\n\n\n# This is to make sure the transformers module imported is the one in the repo.\nlowerCAmelCase__ :Dict \t\t\t=\t\t\t\t\t\t\tdirect_transformers_import(PATH_TO_TRANSFORMERS)\n\nlowerCAmelCase__ :Dict \t\t\t=\t\t\t\t\t\t\ttransformers.models.auto.configuration_auto.CONFIG_MAPPING\n\n# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.\n# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`\nlowerCAmelCase__ :int \t\t\t=\t\t\t\t\t\t\tre.compile(R'''\\[(.+?)\\]\\((https://huggingface\\.co/.+?)\\)''')\n\n\nlowerCAmelCase__ :Optional[int] \t\t\t=\t\t\t\t\t\t\t{\n '''DecisionTransformerConfig''',\n '''EncoderDecoderConfig''',\n '''MusicgenConfig''',\n '''RagConfig''',\n '''SpeechEncoderDecoderConfig''',\n '''TimmBackboneConfig''',\n '''VisionEncoderDecoderConfig''',\n '''VisionTextDualEncoderConfig''',\n '''LlamaConfig''',\n}\n\ndef lowerCAmelCase__ (\t\t\ta__:\t\tOptional[int] ) ->\t\tOptional[int]:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\tNone\n\n\t\t\t\t\t\t\t# source code of `config_class`\n\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\tinspect.getsource(lowercase__ )\n\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\t_re_checkpoint.findall(lowercase__ )\n\n\t\t\t\t\t\t\t# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.\n\t\t\t\t\t\t\t# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`\n\t\t\t\t\t\t\tfor ckpt_name, ckpt_link in checkpoints:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# allow the link to end with `/`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif ckpt_link.endswith('/' ):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\tckpt_link[:-1]\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# verify the checkpoint name corresponds to the checkpoint link\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\tF'''https://huggingface.co/{ckpt_name}'''\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif ckpt_link == ckpt_link_from_name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\tckpt_name\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\treturn checkpoint\n\ndef lowerCAmelCase__ (\t\t\t) ->\t\tstr:\n\n\n\t\t\t\t\t\t\t'''simple docstring'''\n\n\n\n\n\n\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\t[]\n\n\t\t\t\t\t\t\tfor config_class in list(CONFIG_MAPPING.values() ):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Skip deprecated models\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"models.deprecated\" in config_class.__module__:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\tget_checkpoint_from_config_class(lowercase__ )\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\tconfig_class.__name__\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconfigs_without_checkpoint.append(lowercase__ )\n\n\t\t\t\t\t\t\tif len(lowercase__ ) > 0:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCAmelCase \t\t=\t\t\t\"\\n\".join(sorted(lowercase__ ) )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(F'''The following configurations don\\'t contain any valid checkpoint:\\n{message}''' )\n\n\nif __name__ == \"__main__\":\n\t\tcheck_config_docstrings_have_checkpoints()\n"},"code_codestyle":{"kind":"number","value":329,"string":"329"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\nimport copy\r\nfrom typing import Dict, List, Optional\r\n\r\nfrom ...configuration_utils import PretrainedConfig\r\nfrom ...utils import logging\r\nfrom ..auto import CONFIG_MAPPING\r\n\r\n\r\n__A \t\t\t\t\t\t=\t{\r\n \"facebook/mask2former-swin-small-coco-instance\": (\r\n \"https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json\"\r\n )\r\n # See all Mask2Former models at https://huggingface.co/models?filter=mask2former\r\n}\r\n\r\n__A \t\t\t\t\t\t=\tlogging.get_logger(__name__)\r\nclass \tlowerCamelCase__\t\t\t( lowerCamelCase_\t):\r\n\t\t\ta__ :\t\t\t\t\tOptional[Any]\t = \"\"\"mask2former\"\"\"\r\n\t\t\ta__ :\t\t\t\t\tUnion[str, Any]\t = [\"\"\"swin\"\"\"]\r\n\t\t\ta__ :\t\t\t\t\tDict\t = {\"\"\"hidden_size\"\"\": \"\"\"hidden_dim\"\"\"}\r\n\r\n\r\n\t\t\tdef __init__( self , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE = 256 , SCREAMING_SNAKE_CASE = 256 , SCREAMING_SNAKE_CASE = 256 , SCREAMING_SNAKE_CASE = 1_024 , SCREAMING_SNAKE_CASE = \"relu\" , SCREAMING_SNAKE_CASE = 6 , SCREAMING_SNAKE_CASE = 10 , SCREAMING_SNAKE_CASE = 8 , SCREAMING_SNAKE_CASE = 0.0 , SCREAMING_SNAKE_CASE = 2_048 , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = 4 , SCREAMING_SNAKE_CASE = 255 , SCREAMING_SNAKE_CASE = 100 , SCREAMING_SNAKE_CASE = 0.1 , SCREAMING_SNAKE_CASE = 2.0 , SCREAMING_SNAKE_CASE = 5.0 , SCREAMING_SNAKE_CASE = 5.0 , SCREAMING_SNAKE_CASE = 12_544 , SCREAMING_SNAKE_CASE = 3.0 , SCREAMING_SNAKE_CASE = 0.75 , SCREAMING_SNAKE_CASE = 0.02 , SCREAMING_SNAKE_CASE = 1.0 , SCREAMING_SNAKE_CASE = True , SCREAMING_SNAKE_CASE = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE = None , **SCREAMING_SNAKE_CASE , ):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tif backbone_config is None:\r\n\t\t\t\t\t\t\tlogger.info(\"`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.\"\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[str] \t= CONFIG_MAPPING[\"swin\"](\r\n\t\t\t\t\t\t\t image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE , out_features=[\"stage1\", \"stage2\", \"stage3\", \"stage4\"] , )\r\n\r\n\t\t\t\t\tif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\tsnake_case\t\t\t\t\t\t: Tuple \t= backbone_config.pop(\"model_type\"\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\tsnake_case\t\t\t\t\t\t: Dict \t= CONFIG_MAPPING[backbone_model_type]\r\n\t\t\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= config_class.from_dict(SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t# verify that the backbone is supported\r\n\t\t\t\t\tif backbone_config.model_type not in self.backbones_supported:\r\n\t\t\t\t\t\t\tlogger.warning_once(\r\n\t\t\t\t\t\t\t F'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. '''\r\n\t\t\t\t\t\t\t F'''Supported model types: {','.join(self.backbones_supported\t\t\t\t\t\t\t)}'''\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[str] \t= backbone_config\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= feature_size\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= mask_feature_size\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= hidden_dim\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[str] \t= encoder_feedforward_dim\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Dict \t= activation_function\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[Any] \t= encoder_layers\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Any \t= decoder_layers\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= num_attention_heads\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[str] \t= dropout\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[Any] \t= dim_feedforward\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Tuple \t= pre_norm\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: int \t= enforce_input_projection\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: str \t= common_stride\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[Any] \t= ignore_value\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= num_queries\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= no_object_weight\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Dict \t= class_weight\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Tuple \t= mask_weight\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Tuple \t= dice_weight\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Tuple \t= train_num_points\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: int \t= oversample_ratio\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Dict \t= importance_sample_ratio\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Tuple \t= init_std\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Dict \t= init_xavier_std\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[Any] \t= use_auxiliary_loss\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Dict \t= feature_strides\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: List[Any] \t= output_auxiliary_logits\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Union[str, Any] \t= decoder_layers\r\n\r\n\t\t\t\t\tsuper().__init__(**SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t@classmethod\r\n\t\t\tdef \t\t\t\t\t\t\tlowerCamelCase_ ( cls , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\treturn cls(\r\n\t\t\t\t\t backbone_config=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , )\r\n\r\n\r\n\r\n\t\t\tdef \t\t\t\t\t\t\tlowerCamelCase_ ( self\t\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: int \t= copy.deepcopy(self.__dict__\t\t\t\t\t\t\t)\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: str \t= self.backbone_config.to_dict()\r\n\t\t\t\t\tsnake_case\t\t\t\t\t\t: Optional[int] \t= self.__class__.model_type\r\n\t\t\t\t\treturn output\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":148,"string":"148"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":235,"cells":{"code":{"kind":"string","value":"\r\r\r\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\rimport collections\rimport importlib.util\rimport os\rimport re\rfrom pathlib import Path\r\r\r__snake_case\t\t\t\t= '''src/transformers'''\r\r\r# Matches is_xxx_available()\r__snake_case\t\t\t\t= re.compile(r'''is\\_([a-z_]*)_available()''')\r# Catches a one-line _import_struct = {xxx}\r__snake_case\t\t\t\t= re.compile(r'''^_import_structure\\s+=\\s+\\{([^\\}]+)\\}''')\r# Catches a line with a key-values pattern: \"bla\": [\"foo\", \"bar\"]\r__snake_case\t\t\t\t= re.compile(r'''\\s+\"\\S*\":\\s+\\[([^\\]]*)\\]''')\r# Catches a line if not is_foo_available\r__snake_case\t\t\t\t= re.compile(r'''^\\s*if\\s+not\\s+is\\_[a-z_]*\\_available\\(\\)''')\r# Catches a line _import_struct[\"bla\"].append(\"foo\")\r__snake_case\t\t\t\t= re.compile(r'''^\\s*_import_structure\\[\"\\S*\"\\]\\.append\\(\"(\\S*)\"\\)''')\r# Catches a line _import_struct[\"bla\"].extend([\"foo\", \"bar\"]) or _import_struct[\"bla\"] = [\"foo\", \"bar\"]\r__snake_case\t\t\t\t= re.compile(r'''^\\s*_import_structure\\[\\S*\\](?:\\.extend\\(|\\s*=\\s+)\\[([^\\]]*)\\]''')\r# Catches a line with an object between quotes and a comma: \"MyModel\",\r__snake_case\t\t\t\t= re.compile('''^\\s+\"([^\"]+)\",''')\r# Catches a line with objects between brackets only: [\"foo\", \"bar\"],\r__snake_case\t\t\t\t= re.compile('''^\\s+\\[([^\\]]+)\\]''')\r# Catches a line with from foo import bar, bla, boo\r__snake_case\t\t\t\t= re.compile(r'''\\s+from\\s+\\S*\\s+import\\s+([^\\(\\s].*)\\n''')\r# Catches a line with try:\r__snake_case\t\t\t\t= re.compile(r'''^\\s*try:''')\r# Catches a line with else:\r__snake_case\t\t\t\t= re.compile(r'''^\\s*else:''')\rdef A_\t\t\t\t(\t\t\t\t_lowerCAmelCase : Optional[int] ):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r if _re_test_backend.search(_lowerCAmelCase ) is None:\r return None\r _a \t\t=\t\t\t[b[0] for b in _re_backend.findall(_lowerCAmelCase )]\r backends.sort()\r return \"_and_\".join(_lowerCAmelCase )\rdef A_\t\t\t\t(\t\t\t\t_lowerCAmelCase : Tuple ):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r with open(_lowerCAmelCase, '''r''', encoding='''utf-8''', newline='''\\n''' ) as f:\r _a \t\t=\t\t\tf.readlines()\r\r _a \t\t=\t\t\t0\r while line_index < len(_lowerCAmelCase ) and not lines[line_index].startswith('''_import_structure = {''' ):\r line_index += 1\r\r # If this is a traditional init, just return.\r if line_index >= len(_lowerCAmelCase ):\r return None\r\r # First grab the objects without a specific backend in _import_structure\r _a \t\t=\t\t\t[]\r while not lines[line_index].startswith('''if TYPE_CHECKING''' ) and find_backend(lines[line_index] ) is None:\r _a \t\t=\t\t\tlines[line_index]\r # If we have everything on a single line, let's deal with it.\r if _re_one_line_import_struct.search(_lowerCAmelCase ):\r _a \t\t=\t\t\t_re_one_line_import_struct.search(_lowerCAmelCase ).groups()[0]\r _a \t\t=\t\t\tre.findall('''\\[([^\\]]+)\\]''', _lowerCAmelCase )\r for imp in imports:\r objects.extend([obj[1:-1] for obj in imp.split(''', ''' )] )\r line_index += 1\r continue\r _a \t\t=\t\t\t_re_import_struct_key_value.search(_lowerCAmelCase )\r if single_line_import_search is not None:\r _a \t\t=\t\t\t[obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', ''' ) if len(_lowerCAmelCase ) > 0]\r objects.extend(_lowerCAmelCase )\r elif line.startswith(''' ''' * 8 + '''\"''' ):\r objects.append(line[9:-3] )\r line_index += 1\r\r _a \t\t=\t\t\t{'''none''': objects}\r # Let's continue with backend-specific objects in _import_structure\r while not lines[line_index].startswith('''if TYPE_CHECKING''' ):\r # If the line is an if not is_backend_available, we grab all objects associated.\r _a \t\t=\t\t\tfind_backend(lines[line_index] )\r # Check if the backend declaration is inside a try block:\r if _re_try.search(lines[line_index - 1] ) is None:\r _a \t\t=\t\t\tNone\r\r if backend is not None:\r line_index += 1\r\r # Scroll until we hit the else block of try-except-else\r while _re_else.search(lines[line_index] ) is None:\r line_index += 1\r\r line_index += 1\r\r _a \t\t=\t\t\t[]\r # Until we unindent, add backend objects to the list\r while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 4 ):\r _a \t\t=\t\t\tlines[line_index]\r if _re_import_struct_add_one.search(_lowerCAmelCase ) is not None:\r objects.append(_re_import_struct_add_one.search(_lowerCAmelCase ).groups()[0] )\r elif _re_import_struct_add_many.search(_lowerCAmelCase ) is not None:\r _a \t\t=\t\t\t_re_import_struct_add_many.search(_lowerCAmelCase ).groups()[0].split(''', ''' )\r _a \t\t=\t\t\t[obj[1:-1] for obj in imports if len(_lowerCAmelCase ) > 0]\r objects.extend(_lowerCAmelCase )\r elif _re_between_brackets.search(_lowerCAmelCase ) is not None:\r _a \t\t=\t\t\t_re_between_brackets.search(_lowerCAmelCase ).groups()[0].split(''', ''' )\r _a \t\t=\t\t\t[obj[1:-1] for obj in imports if len(_lowerCAmelCase ) > 0]\r objects.extend(_lowerCAmelCase )\r elif _re_quote_object.search(_lowerCAmelCase ) is not None:\r objects.append(_re_quote_object.search(_lowerCAmelCase ).groups()[0] )\r elif line.startswith(''' ''' * 8 + '''\"''' ):\r objects.append(line[9:-3] )\r elif line.startswith(''' ''' * 12 + '''\"''' ):\r objects.append(line[13:-3] )\r line_index += 1\r\r _a \t\t=\t\t\tobjects\r else:\r line_index += 1\r\r # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend\r _a \t\t=\t\t\t[]\r while (\r line_index < len(_lowerCAmelCase )\r and find_backend(lines[line_index] ) is None\r and not lines[line_index].startswith('''else''' )\r ):\r _a \t\t=\t\t\tlines[line_index]\r _a \t\t=\t\t\t_re_import.search(_lowerCAmelCase )\r if single_line_import_search is not None:\r objects.extend(single_line_import_search.groups()[0].split(''', ''' ) )\r elif line.startswith(''' ''' * 8 ):\r objects.append(line[8:-2] )\r line_index += 1\r\r _a \t\t=\t\t\t{'''none''': objects}\r # Let's continue with backend-specific objects\r while line_index < len(_lowerCAmelCase ):\r # If the line is an if is_backend_available, we grab all objects associated.\r _a \t\t=\t\t\tfind_backend(lines[line_index] )\r # Check if the backend declaration is inside a try block:\r if _re_try.search(lines[line_index - 1] ) is None:\r _a \t\t=\t\t\tNone\r\r if backend is not None:\r line_index += 1\r\r # Scroll until we hit the else block of try-except-else\r while _re_else.search(lines[line_index] ) is None:\r line_index += 1\r\r line_index += 1\r\r _a \t\t=\t\t\t[]\r # Until we unindent, add backend objects to the list\r while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 8 ):\r _a \t\t=\t\t\tlines[line_index]\r _a \t\t=\t\t\t_re_import.search(_lowerCAmelCase )\r if single_line_import_search is not None:\r objects.extend(single_line_import_search.groups()[0].split(''', ''' ) )\r elif line.startswith(''' ''' * 12 ):\r objects.append(line[12:-2] )\r line_index += 1\r\r _a \t\t=\t\t\tobjects\r else:\r line_index += 1\r\r return import_dict_objects, type_hint_objects\rdef A_\t\t\t\t(\t\t\t\t_lowerCAmelCase : Optional[int], _lowerCAmelCase : Union[str, Any] ):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r def find_duplicates(_lowerCAmelCase : Dict ):\r return [k for k, v in collections.Counter(_lowerCAmelCase ).items() if v > 1]\r\r if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ):\r return [\"Both sides of the init do not have the same backends!\"]\r\r _a \t\t=\t\t\t[]\r for key in import_dict_objects.keys():\r _a \t\t=\t\t\tfind_duplicates(import_dict_objects[key] )\r if duplicate_imports:\r errors.append(f'Duplicate _import_structure definitions for: {duplicate_imports}' )\r _a \t\t=\t\t\tfind_duplicates(type_hint_objects[key] )\r if duplicate_type_hints:\r errors.append(f'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' )\r\r if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ):\r _a \t\t=\t\t\t'''base imports''' if key == '''none''' else f'{key} backend'\r errors.append(f'Differences for {name}:' )\r for a in type_hint_objects[key]:\r if a not in import_dict_objects[key]:\r errors.append(f' {a} in TYPE_HINT but not in _import_structure.' )\r for a in import_dict_objects[key]:\r if a not in type_hint_objects[key]:\r errors.append(f' {a} in _import_structure but not in TYPE_HINT.' )\r return errors\rdef A_\t\t\t\t(\t\t\t\t):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r _a \t\t=\t\t\t[]\r for root, _, files in os.walk(_lowerCAmelCase ):\r if \"__init__.py\" in files:\r _a \t\t=\t\t\tos.path.join(_lowerCAmelCase, '''__init__.py''' )\r _a \t\t=\t\t\tparse_init(_lowerCAmelCase )\r if objects is not None:\r _a \t\t=\t\t\tanalyze_results(*_lowerCAmelCase )\r if len(_lowerCAmelCase ) > 0:\r _a \t\t=\t\t\tf'Problem in {fname}, both halves do not define the same objects.\\n{errors[0]}'\r failures.append('''\\n'''.join(_lowerCAmelCase ) )\r if len(_lowerCAmelCase ) > 0:\r raise ValueError('''\\n\\n'''.join(_lowerCAmelCase ) )\rdef A_\t\t\t\t(\t\t\t\t):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r _a \t\t=\t\t\t[]\r for path, directories, files in os.walk(_lowerCAmelCase ):\r for folder in directories:\r # Ignore private modules\r if folder.startswith('''_''' ):\r directories.remove(_lowerCAmelCase )\r continue\r # Ignore leftovers from branches (empty folders apart from pycache)\r if len(list((Path(_lowerCAmelCase ) / folder).glob('''*.py''' ) ) ) == 0:\r continue\r _a \t\t=\t\t\tstr((Path(_lowerCAmelCase ) / folder).relative_to(_lowerCAmelCase ) )\r _a \t\t=\t\t\tshort_path.replace(os.path.sep, '''.''' )\r submodules.append(_lowerCAmelCase )\r for fname in files:\r if fname == \"__init__.py\":\r continue\r _a \t\t=\t\t\tstr((Path(_lowerCAmelCase ) / fname).relative_to(_lowerCAmelCase ) )\r _a \t\t=\t\t\tshort_path.replace('''.py''', '''''' ).replace(os.path.sep, '''.''' )\r if len(submodule.split('''.''' ) ) == 1:\r submodules.append(_lowerCAmelCase )\r return submodules\r\r\r__snake_case\t\t\t\t= [\r '''convert_pytorch_checkpoint_to_tf2''',\r '''modeling_flax_pytorch_utils''',\r]\rdef A_\t\t\t\t(\t\t\t\t):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r _a \t\t=\t\t\timportlib.util.spec_from_file_location(\r '''transformers''', os.path.join(_lowerCAmelCase, '''__init__.py''' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], )\r _a \t\t=\t\t\tspec.loader.load_module()\r\r _a \t\t=\t\t\t[\r module\r for module in get_transformers_submodules()\r if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()\r ]\r if len(_lowerCAmelCase ) > 0:\r _a \t\t=\t\t\t'''\\n'''.join(f'- {module}' for module in module_not_registered )\r raise ValueError(\r '''The following submodules are not properly registered in the main init of Transformers:\\n'''\r f'{list_of_modules}\\n'\r '''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.''' )\r\r\rif __name__ == \"__main__\":\r check_all_inits()\r check_submodules()"},"code_codestyle":{"kind":"number","value":153,"string":"153"},"style_context":{"kind":"string","value":"\r\r\r\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\rimport itertools\rimport json\rimport os\rimport unittest\r\rfrom transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast\rfrom transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES\rfrom transformers.testing_utils import require_tokenizers, slow\r\rfrom ...test_tokenization_common import TokenizerTesterMixin\r\r\r@require_tokenizers\rclass __lowerCamelCase\t\t\t\t\t( a__\t\t\t\t\t, unittest.TestCase\t\t\t):\r\r '''simple docstring'''\r A_ :\t\tOptional[int] =\t\t\t\t\t\tRobertaTokenizer\r A_ :\t\tAny =\t\t\t\t\t\tRobertaTokenizerFast\r A_ :\t\tDict =\t\t\t\t\t\tTrue\r A_ :\t\tTuple =\t\t\t\t\t\t{'cls_token': ''}\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tDict:\r super().setUp()\r\r # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt\r _a \t\t=\t\t\t[\r '''l''',\r '''o''',\r '''w''',\r '''e''',\r '''r''',\r '''s''',\r '''t''',\r '''i''',\r '''d''',\r '''n''',\r '''\\u0120''',\r '''\\u0120l''',\r '''\\u0120n''',\r '''\\u0120lo''',\r '''\\u0120low''',\r '''er''',\r '''\\u0120lowest''',\r '''\\u0120newer''',\r '''\\u0120wider''',\r '''''',\r ]\r _a \t\t=\t\t\tdict(zip(__UpperCAmelCase ,\t\t\trange(len(__UpperCAmelCase\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r _a \t\t=\t\t\t['''#version: 0.2''', '''\\u0120 l''', '''\\u0120l o''', '''\\u0120lo w''', '''e r''', '''''']\r _a \t\t=\t\t\t{'''unk_token''': ''''''}\r\r _a \t\t=\t\t\tos.path.join(self.tmpdirname ,\t\t\tVOCAB_FILES_NAMES['''vocab_file''']\t\t\t\t\t\t\t)\r _a \t\t=\t\t\tos.path.join(self.tmpdirname ,\t\t\tVOCAB_FILES_NAMES['''merges_file''']\t\t\t\t\t\t\t)\r with open(self.vocab_file ,\t\t\t'''w''' ,\t\t\tencoding='''utf-8'''\t\t\t\t\t\t\t) as fp:\r fp.write(json.dumps(__UpperCAmelCase\t\t\t\t\t\t\t) + '''\\n'''\t\t\t\t\t\t\t)\r with open(self.merges_file ,\t\t\t'''w''' ,\t\t\tencoding='''utf-8'''\t\t\t\t\t\t\t) as fp:\r fp.write('''\\n'''.join(__UpperCAmelCase\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self ,\t\t\t**__UpperCAmelCase\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tList[str]:\r kwargs.update(self.special_tokens_map\t\t\t\t\t\t\t)\r return self.tokenizer_class.from_pretrained(self.tmpdirname ,\t\t\t**__UpperCAmelCase\t\t\t\t\t\t\t)\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self ,\t\t\t**__UpperCAmelCase\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tUnion[str, Any]:\r kwargs.update(self.special_tokens_map\t\t\t\t\t\t\t)\r return RobertaTokenizerFast.from_pretrained(self.tmpdirname ,\t\t\t**__UpperCAmelCase\t\t\t\t\t\t\t)\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tOptional[int]:\r _a \t\t=\t\t\t'''lower newer'''\r _a \t\t=\t\t\t'''lower newer'''\r return input_text, output_text\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tTuple:\r _a \t\t=\t\t\tself.tokenizer_class(self.vocab_file ,\t\t\tself.merges_file ,\t\t\t**self.special_tokens_map\t\t\t\t\t\t\t)\r _a \t\t=\t\t\t'''lower newer'''\r _a \t\t=\t\t\t['''l''', '''o''', '''w''', '''er''', '''\\u0120''', '''n''', '''e''', '''w''', '''er''']\r _a \t\t=\t\t\ttokenizer.tokenize(__UpperCAmelCase\t\t\t\t\t\t\t) # , add_prefix_space=True)\r self.assertListEqual(__UpperCAmelCase ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\ttokens + [tokenizer.unk_token]\r _a \t\t=\t\t\t[0, 1, 2, 15, 10, 9, 3, 2, 15, 19]\r self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase\t\t\t\t\t\t\t) ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tUnion[str, Any]:\r _a \t\t=\t\t\tself.get_tokenizer()\r\r self.assertListEqual(tokenizer.encode('''Hello world!''' ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t) ,\t\t\t[0, 31414, 232, 328, 2]\t\t\t\t\t\t\t)\r self.assertListEqual(\r tokenizer.encode('''Hello world! cécé herlolip 418''' ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t) ,\t\t\t[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2] ,\t\t\t)\r\r\r @slow\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tTuple:\r _a \t\t=\t\t\tself.tokenizer_class.from_pretrained('''roberta-base'''\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\ttokenizer.encode('''sequence builders''' ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.encode('''multi-sequence build''' ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\ttokenizer.encode(\r '''sequence builders''' ,\t\t\tadd_special_tokens=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.encode(\r '''sequence builders''' ,\t\t\t'''multi-sequence build''' ,\t\t\tadd_special_tokens=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\ttokenizer.build_inputs_with_special_tokens(__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r assert encoded_sentence == encoded_text_from_decode\r assert encoded_pair == encoded_pair_from_decode\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tUnion[str, Any]:\r _a \t\t=\t\t\tself.get_tokenizer()\r\r _a \t\t=\t\t\t'''Encode this sequence.'''\r _a \t\t=\t\t\ttokenizer.byte_encoder[''' '''.encode('''utf-8'''\t\t\t\t\t\t\t)[0]]\r\r # Testing encoder arguments\r _a \t\t=\t\t\ttokenizer.encode(__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.convert_ids_to_tokens(encoded[0]\t\t\t\t\t\t\t)[0]\r self.assertNotEqual(__UpperCAmelCase ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\ttokenizer.encode(__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.convert_ids_to_tokens(encoded[0]\t\t\t\t\t\t\t)[0]\r self.assertEqual(__UpperCAmelCase ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r tokenizer.add_special_tokens({'''bos_token''': ''''''}\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.encode(__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.convert_ids_to_tokens(encoded[1]\t\t\t\t\t\t\t)[0]\r self.assertNotEqual(__UpperCAmelCase ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r # Testing spaces after special tokens\r _a \t\t=\t\t\t''''''\r tokenizer.add_special_tokens(\r {'''mask_token''': AddedToken(__UpperCAmelCase ,\t\t\tlstrip=__UpperCAmelCase ,\t\t\trstrip=__UpperCAmelCase\t\t\t\t\t\t\t)}\t\t\t\t\t\t\t) # mask token has a left space\r _a \t\t=\t\t\ttokenizer.convert_tokens_to_ids(__UpperCAmelCase\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\t'''Encode sequence'''\r _a \t\t=\t\t\t'''Encode sequence'''\r\r _a \t\t=\t\t\ttokenizer.encode(__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\tencoded.index(__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.convert_ids_to_tokens(encoded[mask_loc + 1]\t\t\t\t\t\t\t)[0]\r self.assertEqual(__UpperCAmelCase ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\ttokenizer.encode(__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\tencoded.index(__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer.convert_ids_to_tokens(encoded[mask_loc + 1]\t\t\t\t\t\t\t)[0]\r self.assertNotEqual(__UpperCAmelCase ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tAny:\r pass\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tOptional[int]:\r for tokenizer, pretrained_name, kwargs in self.tokenizers_list:\r with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'\t\t\t\t\t\t\t):\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(__UpperCAmelCase ,\t\t\t**__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\tself.tokenizer_class.from_pretrained(__UpperCAmelCase ,\t\t\t**__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\t'''A, AllenNLP sentence.'''\r _a \t\t=\t\t\ttokenizer_r.encode_plus(__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase ,\t\t\treturn_token_type_ids=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_p.encode_plus(__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase ,\t\t\treturn_token_type_ids=__UpperCAmelCase\t\t\t\t\t\t\t)\r\r # token_type_ids should put 0 everywhere\r self.assertEqual(sum(tokens_r['''token_type_ids''']\t\t\t\t\t\t\t) ,\t\t\tsum(tokens_p['''token_type_ids''']\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r # attention_mask should put 1 everywhere, so sum over length should be 1\r self.assertEqual(\r sum(tokens_r['''attention_mask''']\t\t\t\t\t\t\t) / len(tokens_r['''attention_mask''']\t\t\t\t\t\t\t) ,\t\t\tsum(tokens_p['''attention_mask''']\t\t\t\t\t\t\t) / len(tokens_p['''attention_mask''']\t\t\t\t\t\t\t) ,\t\t\t)\r\r _a \t\t=\t\t\ttokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids''']\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids''']\t\t\t\t\t\t\t)\r\r # Rust correctly handles the space before the mask while python doesnt\r self.assertSequenceEqual(tokens_p['''input_ids'''] ,\t\t\t[0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]\t\t\t\t\t\t\t)\r self.assertSequenceEqual(tokens_r['''input_ids'''] ,\t\t\t[0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]\t\t\t\t\t\t\t)\r\r self.assertSequenceEqual(\r __UpperCAmelCase ,\t\t\t['''''', '''A''', ''',''', '''''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''''']\t\t\t\t\t\t\t)\r self.assertSequenceEqual(\r __UpperCAmelCase ,\t\t\t['''''', '''A''', ''',''', '''''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''''']\t\t\t\t\t\t\t)\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tAny:\r for trim_offsets, add_prefix_space in itertools.product([True, False] ,\t\t\trepeat=2\t\t\t\t\t\t\t):\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r self.tmpdirname ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r\r _a \t\t=\t\t\tjson.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__()\t\t\t\t\t\t\t)\r _a \t\t=\t\t\tjson.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__()\t\t\t\t\t\t\t)\r\r self.assertEqual(pre_tokenizer_state['''add_prefix_space'''] ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r self.assertEqual(post_processor_state['''add_prefix_space'''] ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(post_processor_state['''trim_offsets'''] ,\t\t\t__UpperCAmelCase\t\t\t\t\t\t\t)\r\r\r\r\r\r def \t\t\t\t\t\t\t_UpperCAmelCase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\t\tUnion[str, Any]:\r # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and\r # `trim_offsets`\r for tokenizer, pretrained_name, kwargs in self.tokenizers_list:\r with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'\t\t\t\t\t\t\t):\r _a \t\t=\t\t\t'''hello''' # `hello` is a token in the vocabulary of `pretrained_name`\r _a \t\t=\t\t\tF'{text_of_1_token} {text_of_1_token}'\r\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r __UpperCAmelCase ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_r(__UpperCAmelCase ,\t\t\treturn_offsets_mapping=__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(encoding.offset_mapping[0] ,\t\t\t(0, len(__UpperCAmelCase\t\t\t\t\t\t\t))\t\t\t\t\t\t\t)\r self.assertEqual(\r encoding.offset_mapping[1] ,\t\t\t(len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1, len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t)) ,\t\t\t)\r\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r __UpperCAmelCase ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_r(__UpperCAmelCase ,\t\t\treturn_offsets_mapping=__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(encoding.offset_mapping[0] ,\t\t\t(0, len(__UpperCAmelCase\t\t\t\t\t\t\t))\t\t\t\t\t\t\t)\r self.assertEqual(\r encoding.offset_mapping[1] ,\t\t\t(len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1, len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t)) ,\t\t\t)\r\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r __UpperCAmelCase ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_r(__UpperCAmelCase ,\t\t\treturn_offsets_mapping=__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(encoding.offset_mapping[0] ,\t\t\t(0, len(__UpperCAmelCase\t\t\t\t\t\t\t))\t\t\t\t\t\t\t)\r self.assertEqual(\r encoding.offset_mapping[1] ,\t\t\t(len(__UpperCAmelCase\t\t\t\t\t\t\t), len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t)) ,\t\t\t)\r\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r __UpperCAmelCase ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_r(__UpperCAmelCase ,\t\t\treturn_offsets_mapping=__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(encoding.offset_mapping[0] ,\t\t\t(0, len(__UpperCAmelCase\t\t\t\t\t\t\t))\t\t\t\t\t\t\t)\r self.assertEqual(\r encoding.offset_mapping[1] ,\t\t\t(len(__UpperCAmelCase\t\t\t\t\t\t\t), len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t)) ,\t\t\t)\r\r _a \t\t=\t\t\tF' {text}'\r\r # tokenizer_r = self.rust_tokenizer_class.from_pretrained(\r # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True\r # )\r # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False)\r # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token)))\r # self.assertEqual(\r # encoding.offset_mapping[1],\r # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)),\r # )\r\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r __UpperCAmelCase ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_r(__UpperCAmelCase ,\t\t\treturn_offsets_mapping=__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(encoding.offset_mapping[0] ,\t\t\t(1, 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t))\t\t\t\t\t\t\t)\r self.assertEqual(\r encoding.offset_mapping[1] ,\t\t\t(1 + len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1, 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t)) ,\t\t\t)\r\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r __UpperCAmelCase ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_r(__UpperCAmelCase ,\t\t\treturn_offsets_mapping=__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(encoding.offset_mapping[0] ,\t\t\t(0, 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t))\t\t\t\t\t\t\t)\r self.assertEqual(\r encoding.offset_mapping[1] ,\t\t\t(1 + len(__UpperCAmelCase\t\t\t\t\t\t\t), 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t)) ,\t\t\t)\r\r _a \t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\r __UpperCAmelCase ,\t\t\tuse_fast=__UpperCAmelCase ,\t\t\tadd_prefix_space=__UpperCAmelCase ,\t\t\ttrim_offsets=__UpperCAmelCase\t\t\t\t\t\t\t)\r _a \t\t=\t\t\ttokenizer_r(__UpperCAmelCase ,\t\t\treturn_offsets_mapping=__UpperCAmelCase ,\t\t\tadd_special_tokens=__UpperCAmelCase\t\t\t\t\t\t\t)\r self.assertEqual(encoding.offset_mapping[0] ,\t\t\t(0, 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t))\t\t\t\t\t\t\t)\r self.assertEqual(\r encoding.offset_mapping[1] ,\t\t\t(1 + len(__UpperCAmelCase\t\t\t\t\t\t\t), 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t) + 1 + len(__UpperCAmelCase\t\t\t\t\t\t\t)) ,\t\t\t)"},"style_context_codestyle":{"kind":"number","value":153,"string":"153"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":236,"cells":{"code":{"kind":"string","value":"from math import pi, sqrt, tan\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if side_length < 0:\r\n raise ValueError(\"\"\"surface_area_cube() only accepts non-negative values\"\"\"\t)\r\n return 6 * side_length**2\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if length < 0 or breadth < 0 or height < 0:\r\n raise ValueError(\"\"\"surface_area_cuboid() only accepts non-negative values\"\"\"\t)\r\n return 2 * ((length * breadth) + (breadth * height) + (length * height))\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if radius < 0:\r\n raise ValueError(\"\"\"surface_area_sphere() only accepts non-negative values\"\"\"\t)\r\n return 4 * pi * radius**2\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if radius < 0:\r\n raise ValueError(\"\"\"surface_area_hemisphere() only accepts non-negative values\"\"\"\t)\r\n return 3 * pi * radius**2\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if radius < 0 or height < 0:\r\n raise ValueError(\"\"\"surface_area_cone() only accepts non-negative values\"\"\"\t)\r\n return pi * radius * (radius + (height**2 + radius**2) ** 0.5)\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if radius_a < 0 or radius_a < 0 or height < 0:\r\n raise ValueError(\r\n \"\"\"surface_area_conical_frustum() only accepts non-negative values\"\"\"\t)\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= (height**2 + (radius_a - radius_a) ** 2) ** 0.5\r\n return pi * ((slant_height * (radius_a + radius_a)) + radius_a**2 + radius_a**2)\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if radius < 0 or height < 0:\r\n raise ValueError(\"\"\"surface_area_cylinder() only accepts non-negative values\"\"\"\t)\r\n return 2 * pi * radius * (height + radius)\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if torus_radius < 0 or tube_radius < 0:\r\n raise ValueError(\"\"\"surface_area_torus() only accepts non-negative values\"\"\"\t)\r\n if torus_radius < tube_radius:\r\n raise ValueError(\r\n \"\"\"surface_area_torus() does not support spindle or self intersecting tori\"\"\"\t)\r\n return 4 * pow(__UpperCamelCase , 2\t) * torus_radius * tube_radius\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if length < 0 or width < 0:\r\n raise ValueError(\"\"\"area_rectangle() only accepts non-negative values\"\"\"\t)\r\n return length * width\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if side_length < 0:\r\n raise ValueError(\"\"\"area_square() only accepts non-negative values\"\"\"\t)\r\n return side_length**2\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if base < 0 or height < 0:\r\n raise ValueError(\"\"\"area_triangle() only accepts non-negative values\"\"\"\t)\r\n return (base * height) / 2\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if sidea < 0 or sidea < 0 or sidea < 0:\r\n raise ValueError(\"\"\"area_triangle_three_sides() only accepts non-negative values\"\"\"\t)\r\n elif sidea + sidea < sidea or sidea + sidea < sidea or sidea + sidea < sidea:\r\n raise ValueError(\"\"\"Given three sides do not form a triangle\"\"\"\t)\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= (sidea + sidea + sidea) / 2\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= sqrt(\r\n semi_perimeter\r\n * (semi_perimeter - sidea)\r\n * (semi_perimeter - sidea)\r\n * (semi_perimeter - sidea)\t)\r\n return area\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if base < 0 or height < 0:\r\n raise ValueError(\"\"\"area_parallelogram() only accepts non-negative values\"\"\"\t)\r\n return base * height\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if basea < 0 or basea < 0 or height < 0:\r\n raise ValueError(\"\"\"area_trapezium() only accepts non-negative values\"\"\"\t)\r\n return 1 / 2 * (basea + basea) * height\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if radius < 0:\r\n raise ValueError(\"\"\"area_circle() only accepts non-negative values\"\"\"\t)\r\n return pi * radius**2\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if radius_x < 0 or radius_y < 0:\r\n raise ValueError(\"\"\"area_ellipse() only accepts non-negative values\"\"\"\t)\r\n return pi * radius_x * radius_y\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : float , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if diagonal_a < 0 or diagonal_a < 0:\r\n raise ValueError(\"\"\"area_rhombus() only accepts non-negative values\"\"\"\t)\r\n return 1 / 2 * diagonal_a * diagonal_a\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : int , __UpperCamelCase : float\t)\t\t\t\t\t\t\t->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n if not isinstance(__UpperCamelCase , __UpperCamelCase\t) or sides < 3:\r\n raise ValueError(\r\n \"\"\"area_reg_polygon() only accepts integers greater than or \\\nequal to three as number of sides\"\"\"\t)\r\n elif length < 0:\r\n raise ValueError(\r\n \"\"\"area_reg_polygon() only accepts non-negative values as \\\nlength of a side\"\"\"\t)\r\n return (sides * length**2) / (4 * tan(pi / sides\t))\r\n return (sides * length**2) / (4 * tan(pi / sides\t))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import doctest\r\n\r\n doctest.testmod(verbose=True) # verbose so we can see methods missing tests\r\n\r\n print('''[DEMO] Areas of various geometric shapes: \\n''')\r\n print(F\"\"\"Rectangle: {area_rectangle(10, 20) = }\"\"\")\r\n print(F\"\"\"Square: {area_square(10) = }\"\"\")\r\n print(F\"\"\"Triangle: {area_triangle(10, 10) = }\"\"\")\r\n print(F\"\"\"Triangle: {area_triangle_three_sides(5, 12, 13) = }\"\"\")\r\n print(F\"\"\"Parallelogram: {area_parallelogram(10, 20) = }\"\"\")\r\n print(F\"\"\"Rhombus: {area_rhombus(10, 20) = }\"\"\")\r\n print(F\"\"\"Trapezium: {area_trapezium(10, 20, 30) = }\"\"\")\r\n print(F\"\"\"Circle: {area_circle(20) = }\"\"\")\r\n print(F\"\"\"Ellipse: {area_ellipse(10, 20) = }\"\"\")\r\n print('''\\nSurface Areas of various geometric shapes: \\n''')\r\n print(F\"\"\"Cube: {surface_area_cube(20) = }\"\"\")\r\n print(F\"\"\"Cuboid: {surface_area_cuboid(10, 20, 30) = }\"\"\")\r\n print(F\"\"\"Sphere: {surface_area_sphere(20) = }\"\"\")\r\n print(F\"\"\"Hemisphere: {surface_area_hemisphere(20) = }\"\"\")\r\n print(F\"\"\"Cone: {surface_area_cone(10, 20) = }\"\"\")\r\n print(F\"\"\"Conical Frustum: {surface_area_conical_frustum(10, 20, 30) = }\"\"\")\r\n print(F\"\"\"Cylinder: {surface_area_cylinder(10, 20) = }\"\"\")\r\n print(F\"\"\"Torus: {surface_area_torus(20, 10) = }\"\"\")\r\n print(F\"\"\"Equilateral Triangle: {area_reg_polygon(3, 10) = }\"\"\")\r\n print(F\"\"\"Square: {area_reg_polygon(4, 10) = }\"\"\")\r\n print(F\"\"\"Reqular Pentagon: {area_reg_polygon(5, 10) = }\"\"\")\r\n"},"code_codestyle":{"kind":"number","value":219,"string":"219"},"style_context":{"kind":"string","value":"import unittest\r\nfrom pathlib import Path\r\nfrom shutil import copyfile\r\n\r\nfrom transformers import SPIECE_UNDERLINE, is_sentencepiece_available\r\nfrom transformers.models.speech_to_text import SpeechaTextTokenizer\r\nfrom transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json\r\nfrom transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow\r\n\r\nfrom ...test_tokenization_common import TokenizerTesterMixin\r\n\r\n\r\n__lowerCamelCase\t\t\t: str\t\t\t\t\t\t\t =\t\tget_tests_dir('''fixtures/test_sentencepiece.model''')\r\n\r\nif is_sentencepiece_available():\r\n import sentencepiece as sp\r\n\r\n\r\n__lowerCamelCase\t\t\t: Any\t\t\t\t\t\t\t =\t\t5\r\n__lowerCamelCase\t\t\t: Dict\t\t\t\t\t\t\t =\t\t10\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n@require_sentencepiece\r\n@require_tokenizers\r\nclass __snake_case\t\t\t\t(\t\t\t\t\t\tlowerCamelCase_ ,\t\tunittest.TestCase\t\t):\r\n lowerCAmelCase_\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tSpeechaTextTokenizer\r\n lowerCAmelCase_\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tFalse\r\n lowerCAmelCase_\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tTrue\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tTuple ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n super().setUp()\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= sp.SentencePieceProcessor()\r\n spm_model.Load(_lowercase )\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= [\"\"\"\"\"\", \"\"\"\"\"\", \"\"\"\"\"\", \"\"\"\"\"\"]\r\n\r\n vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(_lowercase ) )]\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= dict(zip(_lowercase ,\trange(len(_lowercase ) ) ) )\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= Path(self.tmpdirname )\r\n save_json(_lowercase ,\tsave_dir / VOCAB_FILES_NAMES[\"\"\"vocab_file\"\"\"] )\r\n if not (save_dir / VOCAB_FILES_NAMES[\"spm_file\"]).exists():\r\n copyfile(_lowercase ,\tsave_dir / VOCAB_FILES_NAMES[\"\"\"spm_file\"\"\"] )\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= SpeechaTextTokenizer.from_pretrained(self.tmpdirname )\r\n tokenizer.save_pretrained(self.tmpdirname )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tUnion[str, Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= \"\"\"\"\"\"\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 1\r\n\r\n self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowercase ) ,\t_lowercase )\r\n self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowercase ) ,\t_lowercase )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= list(self.get_tokenizer().get_vocab().keys() )\r\n\r\n self.assertEqual(vocab_keys[0] ,\t\"\"\"\"\"\" )\r\n self.assertEqual(vocab_keys[1] ,\t\"\"\"\"\"\" )\r\n self.assertEqual(vocab_keys[-1] ,\t\"\"\"j\"\"\" )\r\n self.assertEqual(len(_lowercase ) ,\t10_01 )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n self.assertEqual(self.get_tokenizer().vocab_size ,\t10_01 )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= SpeechaTextTokenizer.from_pretrained(self.tmpdirname )\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= tokenizer.tokenize(\"\"\"This is a test\"\"\" )\r\n self.assertListEqual(_lowercase ,\t[\"\"\"▁This\"\"\", \"\"\"▁is\"\"\", \"\"\"▁a\"\"\", \"\"\"▁t\"\"\", \"\"\"est\"\"\"] )\r\n\r\n self.assertListEqual(\r\n tokenizer.convert_tokens_to_ids(_lowercase ) ,\t[2_89, 50, 14, 1_74, 3_86] ,\t)\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= tokenizer.tokenize(\"\"\"I was born in 92000, and this is falsé.\"\"\" )\r\n self.assertListEqual(\r\n _lowercase ,\t[SPIECE_UNDERLINE + \"\"\"I\"\"\", SPIECE_UNDERLINE + \"\"\"was\"\"\", SPIECE_UNDERLINE + \"\"\"b\"\"\", \"\"\"or\"\"\", \"\"\"n\"\"\", SPIECE_UNDERLINE + \"\"\"in\"\"\", SPIECE_UNDERLINE + \"\"\"\"\"\", \"\"\"9\"\"\", \"\"\"2\"\"\", \"\"\"0\"\"\", \"\"\"0\"\"\", \"\"\"0\"\"\", \"\"\",\"\"\", SPIECE_UNDERLINE + \"\"\"and\"\"\", SPIECE_UNDERLINE + \"\"\"this\"\"\", SPIECE_UNDERLINE + \"\"\"is\"\"\", SPIECE_UNDERLINE + \"\"\"f\"\"\", \"\"\"al\"\"\", \"\"\"s\"\"\", \"\"\"é\"\"\", \"\"\".\"\"\"] ,\t)\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= tokenizer.convert_tokens_to_ids(_lowercase )\r\n self.assertListEqual(_lowercase ,\t[12, 25, 88, 59, 28, 23, 11, 4, 6_06, 3_51, 3_51, 3_51, 7, 16, 70, 50, 76, 84, 10, 4, 8] )\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= tokenizer.convert_ids_to_tokens(_lowercase )\r\n self.assertListEqual(\r\n _lowercase ,\t[SPIECE_UNDERLINE + \"\"\"I\"\"\", SPIECE_UNDERLINE + \"\"\"was\"\"\", SPIECE_UNDERLINE + \"\"\"b\"\"\", \"\"\"or\"\"\", \"\"\"n\"\"\", SPIECE_UNDERLINE + \"\"\"in\"\"\", SPIECE_UNDERLINE + \"\"\"\"\"\", \"\"\"\"\"\", \"\"\"2\"\"\", \"\"\"0\"\"\", \"\"\"0\"\"\", \"\"\"0\"\"\", \"\"\",\"\"\", SPIECE_UNDERLINE + \"\"\"and\"\"\", SPIECE_UNDERLINE + \"\"\"this\"\"\", SPIECE_UNDERLINE + \"\"\"is\"\"\", SPIECE_UNDERLINE + \"\"\"f\"\"\", \"\"\"al\"\"\", \"\"\"s\"\"\", \"\"\"\"\"\", \"\"\".\"\"\"] ,\t)\r\n\r\n\r\n\r\n\r\n @slow\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= {\"\"\"input_ids\"\"\": [[37_91, 7_97, 31, 11, 64, 7_97, 31, 24_29, 4_33, 12, 11_76, 12, 20, 7_86, 9_15, 1_42, 24_13, 2_40, 37, 32_38, 7_97, 31, 11, 35, 93, 9_15, 1_42, 24_13, 2_40, 37, 55_40, 5_67, 12_76, 93, 37, 6_10, 40, 62, 4_55, 6_57, 10_42, 1_23, 7_80, 1_77, 37, 3_09, 2_41, 12_98, 5_14, 20, 2_92, 27_37, 1_14, 24_69, 2_41, 85, 64, 3_02, 5_48, 5_28, 4_23, 4, 5_09, 4_06, 4_23, 37, 6_01, 4, 7_77, 3_02, 5_48, 5_28, 4_23, 2_84, 4, 33_88, 5_11, 4_59, 4, 35_55, 40, 3_21, 3_02, 7_05, 4, 33_88, 5_11, 5_83, 3_26, 5, 5, 5, 62, 33_10, 5_60, 1_77, 26_80, 2_17, 15_08, 32, 31, 8_53, 4_18, 64, 5_83, 5_11, 16_05, 62, 35, 93, 5_60, 1_77, 26_80, 2_17, 15_08, 15_21, 64, 5_83, 5_11, 5_19, 62, 20, 15_15, 7_64, 20, 1_49, 2_61, 56_25, 79_72, 20, 55_40, 5_67, 12_76, 93, 39_25, 16_75, 11, 15, 8_02, 79_72, 5_76, 2_17, 15_08, 11, 35, 93, 12_53, 24_41, 15, 2_89, 6_52, 31, 4_16, 3_21, 38_42, 1_15, 40, 9_11, 8, 4_76, 6_19, 4, 3_80, 1_42, 4_23, 3_35, 2_40, 35, 93, 2_64, 8, 11, 3_35, 5_69, 4_20, 1_63, 5, 2], [2_60, 5_48, 5_28, 4_23, 20, 4_51, 20, 26_81, 11_53, 34_34, 20, 55_40, 37, 5_67, 1_26, 12_53, 24_41, 33_76, 4_49, 2_10, 4_31, 15_63, 1_77, 7_67, 55_40, 11, 12_03, 4_72, 11, 29_53, 6_85, 2_85, 3_64, 7_06, 11_53, 20, 67_99, 20, 28_69, 20, 44_64, 1_26, 40, 24_29, 20, 10_40, 8_66, 26_64, 4_18, 20, 3_18, 20, 17_26, 1_86, 20, 2_65, 5_22, 35, 93, 21_91, 46_34, 20, 10_40, 12, 67_99, 15, 2_28, 23_56, 1_42, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_75, 26_66, 6_84, 15_82, 11_76, 12, 6_27, 1_49, 6_19, 20, 49_02, 5_63, 11, 20, 1_49, 2_61, 34_20, 23_56, 1_74, 1_42, 47_14, 1_31, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], \"\"\"attention_mask\"\"\": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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\r\n # fmt: on\r\n\r\n self.tokenizer_integration_test_util(\r\n expected_encoding=_lowercase ,\tmodel_name=\"\"\"facebook/s2t-small-mustc-en-de-st\"\"\" ,\trevision=\"\"\"a14f04cf0776c02f62a8cb800cf7909e15ea23ad\"\"\" ,\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n@require_sentencepiece\r\nclass __snake_case\t\t\t\t(\t\t\t\t\t\tunittest.TestCase\t\t):\r\n lowerCAmelCase_\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\t\"valhalla/s2t_mustc_multilinguial_medium\"\r\n\r\n lowerCAmelCase_\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\t\"C'est trop cool\"\r\n lowerCAmelCase_\t\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\t\"Esto es genial\"\r\n\r\n\r\n\r\n\r\n @classmethod\r\n def \t__a\t\t\t\t\t\t( cls\t\t\t:\t\t\t\tAny ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name )\r\n return cls\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tDict ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n self.assertEqual(self.tokenizer.lang_code_to_id[\"\"\"pt\"\"\"] ,\t4 )\r\n self.assertEqual(self.tokenizer.lang_code_to_id[\"\"\"ru\"\"\"] ,\t6 )\r\n self.assertEqual(self.tokenizer.lang_code_to_id[\"\"\"it\"\"\"] ,\t9 )\r\n self.assertEqual(self.tokenizer.lang_code_to_id[\"\"\"de\"\"\"] ,\t11 )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tUnion[str, Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n self.assertEqual(self.tokenizer.vocab_size ,\t1_00_00 )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tint ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n self.assertIn(_lowercase ,\tself.tokenizer.all_special_ids )\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= [ES_CODE, 4, 16_01, 47, 76_47, 2]\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= self.tokenizer.decode(_lowercase ,\tskip_special_tokens=_lowercase )\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= self.tokenizer.decode(generated_ids[1:] ,\tskip_special_tokens=_lowercase )\r\n self.assertEqual(_lowercase ,\t_lowercase )\r\n self.assertNotIn(self.tokenizer.eos_token ,\t_lowercase )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tAny ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= \"\"\"fr\"\"\"\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= self.tokenizer(self.french_text ).input_ids\r\n self.assertEqual(encoded[0] ,\t_lowercase )\r\n self.assertEqual(encoded[-1] ,\tself.tokenizer.eos_token_id )\r\n\r\n\r\n\r\n\r\n def \t__a\t\t\t\t\t\t( self\t\t\t:\t\t\t\tOptional[Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= \"\"\"fr\"\"\"\r\n self.assertListEqual(self.tokenizer.prefix_tokens ,\t[FR_CODE] )\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= \"\"\"es\"\"\"\r\n self.assertListEqual(self.tokenizer.prefix_tokens ,\t[ES_CODE] )\r\n"},"style_context_codestyle":{"kind":"number","value":219,"string":"219"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":237,"cells":{"code":{"kind":"string","value":"\r\rimport unittest\rfrom queue import Empty\rfrom threading import Thread\r\rfrom transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available\rfrom transformers.testing_utils import CaptureStdout, require_torch, torch_device\r\rfrom ..test_modeling_common import ids_tensor\r\r\rif is_torch_available():\r\timport torch\r\r\tfrom transformers import AutoModelForCausalLM\r\r\r\r@require_torch\rclass _a\t\t\t\t\t\t(unittest.TestCase ):\r\r\r\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\tdef __A (\t\t\tself ):\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Tuple\t\t\t\t\t =\t\tAutoTokenizer.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Dict\t\t\t\t\t =\t\tAutoModelForCausalLM.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\t-1\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t =\t\tids_tensor((1, 5) ,\tvocab_size=model.config.vocab_size ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Dict\t\t\t\t\t =\t\tmodel.generate(A__ ,\tmax_new_tokens=10 ,\tdo_sample=A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Tuple\t\t\t\t\t =\t\ttokenizer.decode(greedy_ids[0] )\r\r\t\t\t\t\t\twith CaptureStdout() as cs:\r\t\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Dict\t\t\t\t\t =\t\tTextStreamer(A__ )\r\t\t\t\t\t\t\tmodel.generate(A__ ,\tmax_new_tokens=10 ,\tdo_sample=A__ ,\tstreamer=A__ )\r\t\t\t\t\t\t# The greedy text should be printed to stdout, except for the final \"\\n\" in the streamer\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t =\t\tcs.out[:-1]\r\r\t\t\t\t\t\tself.assertEqual(A__ ,\tA__ )\r\r\r\r\r\r\r\t\t\t\t\tdef __A (\t\t\tself ):\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Tuple\t\t\t\t\t =\t\tAutoTokenizer.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[str]\t\t\t\t\t =\t\tAutoModelForCausalLM.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t =\t\t-1\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\tids_tensor((1, 5) ,\tvocab_size=model.config.vocab_size ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Any\t\t\t\t\t =\t\tmodel.generate(A__ ,\tmax_new_tokens=10 ,\tdo_sample=A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Any\t\t\t\t\t =\t\ttokenizer.decode(greedy_ids[0] )\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\tTextIteratorStreamer(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t =\t\t{\"\"\"input_ids\"\"\": input_ids, \"\"\"max_new_tokens\"\"\": 10, \"\"\"do_sample\"\"\": False, \"\"\"streamer\"\"\": streamer}\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[str]\t\t\t\t\t =\t\tThread(target=model.generate ,\tkwargs=A__ )\r\t\t\t\t\t\tthread.start()\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\t\"\"\"\"\"\"\r\t\t\t\t\t\tfor new_text in streamer:\r\t\t\t\t\t\t\tstreamer_text += new_text\r\r\t\t\t\t\t\tself.assertEqual(A__ ,\tA__ )\r\r\r\r\r\r\r\t\t\t\t\tdef __A (\t\t\tself ):\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\tAutoTokenizer.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[str]\t\t\t\t\t =\t\tAutoModelForCausalLM.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\t-1\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t =\t\tids_tensor((1, 5) ,\tvocab_size=model.config.vocab_size ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t =\t\tmodel.generate(A__ ,\tmax_new_tokens=10 ,\tdo_sample=A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Dict\t\t\t\t\t =\t\tgreedy_ids[:, input_ids.shape[1] :]\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Tuple\t\t\t\t\t =\t\ttokenizer.decode(new_greedy_ids[0] )\r\r\t\t\t\t\t\twith CaptureStdout() as cs:\r\t\t\t\t\t\t\tA__\t\t\t\t\t\t\t: int\t\t\t\t\t =\t\tTextStreamer(A__ ,\tskip_prompt=A__ )\r\t\t\t\t\t\t\tmodel.generate(A__ ,\tmax_new_tokens=10 ,\tdo_sample=A__ ,\tstreamer=A__ )\r\t\t\t\t\t\t# The greedy text should be printed to stdout, except for the final \"\\n\" in the streamer\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\tcs.out[:-1]\r\r\t\t\t\t\t\tself.assertEqual(A__ ,\tA__ )\r\r\r\r\r\r\r\t\t\t\t\tdef __A (\t\t\tself ):\r\t\t\t\t\t\t# Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested\r\t\t\t\t\t\t# with actual models -- the dummy models' tokenizers are not aligned with their models, and\r\t\t\t\t\t\t# `skip_special_tokens=True` has no effect on them\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Tuple\t\t\t\t\t =\t\tAutoTokenizer.from_pretrained(\"\"\"distilgpt2\"\"\" )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[str]\t\t\t\t\t =\t\tAutoModelForCausalLM.from_pretrained(\"\"\"distilgpt2\"\"\" ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: int\t\t\t\t\t =\t\t-1\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t =\t\ttorch.ones((1, 5) ,\tdevice=A__ ).long() * model.config.bos_token_id\r\t\t\t\t\t\twith CaptureStdout() as cs:\r\t\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[str]\t\t\t\t\t =\t\tTextStreamer(A__ ,\tskip_special_tokens=A__ )\r\t\t\t\t\t\t\tmodel.generate(A__ ,\tmax_new_tokens=1 ,\tdo_sample=A__ ,\tstreamer=A__ )\r\r\t\t\t\t\t\t# The prompt contains a special token, so the streamer should not print it. As such, the output text, when\r\t\t\t\t\t\t# re-tokenized, must only contain one token\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: int\t\t\t\t\t =\t\tcs.out[:-1] # Remove the final \"\\n\"\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t =\t\ttokenizer(A__ ,\treturn_tensors=\"\"\"pt\"\"\" )\r\t\t\t\t\t\tself.assertEqual(streamer_text_tokenized.input_ids.shape ,\t(1, 1) )\r\r\r\r\r\r\r\t\t\t\t\tdef __A (\t\t\tself ):\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[str]\t\t\t\t\t =\t\tAutoTokenizer.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\tAutoModelForCausalLM.from_pretrained(\"\"\"hf-internal-testing/tiny-random-gpt2\"\"\" ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\t-1\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\tids_tensor((1, 5) ,\tvocab_size=model.config.vocab_size ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t =\t\tTextIteratorStreamer(A__ ,\ttimeout=0.0_0_1 )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Any\t\t\t\t\t =\t\t{\"\"\"input_ids\"\"\": input_ids, \"\"\"max_new_tokens\"\"\": 10, \"\"\"do_sample\"\"\": False, \"\"\"streamer\"\"\": streamer}\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Dict\t\t\t\t\t =\t\tThread(target=model.generate ,\tkwargs=A__ )\r\t\t\t\t\t\tthread.start()\r\r\t\t\t\t\t\t# The streamer will timeout after 0.001 seconds, so an exception will be raised\r\t\t\t\t\t\twith self.assertRaises(A__ ):\r\t\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t =\t\t\"\"\"\"\"\"\r\t\t\t\t\t\t\tfor new_text in streamer:\r\t\t\t\t\t\t\t\tstreamer_text += new_text\r\r\r\r"},"code_codestyle":{"kind":"number","value":361,"string":"361"},"style_context":{"kind":"string","value":"\r\rimport unittest\r\rfrom transformers import is_torch_available\rfrom transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device\r\r\rif is_torch_available():\r\tfrom transformers import AutoModelForSeqaSeqLM, AutoTokenizer\r\r\r\r@require_torch\r@require_sentencepiece\r@require_tokenizers\rclass _a\t\t\t\t\t\t(unittest.TestCase ):\r\r\r\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t@slow\r\t\t\t\t\tdef __A (\t\t\tself ):\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t =\t\tAutoModelForSeqaSeqLM.from_pretrained(\"\"\"google/mt5-small\"\"\" ,\treturn_dict=A__ ).to(A__ )\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: str\t\t\t\t\t =\t\tAutoTokenizer.from_pretrained(\"\"\"google/mt5-small\"\"\" )\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: int\t\t\t\t\t =\t\ttokenizer(\"\"\"Hello there\"\"\" ,\treturn_tensors=\"\"\"pt\"\"\" ).input_ids\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t =\t\ttokenizer(\"\"\"Hi I am\"\"\" ,\treturn_tensors=\"\"\"pt\"\"\" ).input_ids\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t =\t\tmodel(input_ids.to(A__ ) ,\tlabels=labels.to(A__ ) ).loss\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t =\t\t-(labels.shape[-1] * loss.item())\r\r\t\t\t\t\t\tA__\t\t\t\t\t\t\t: Any\t\t\t\t\t =\t\t-8_4.9_1_2_7\r\t\t\t\t\t\tself.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":141,"string":"141"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":238,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nfrom collections import OrderedDict\r\nfrom typing import Mapping\r\n\r\nfrom packaging import version\r\n\r\nfrom ...configuration_utils import PretrainedConfig\r\nfrom ...onnx import OnnxConfig\r\nfrom ...utils import logging\r\n\r\n\r\nA__: int\t\t\t\t\t = logging.get_logger(__name__)\r\n\r\nA__: Tuple\t\t\t\t\t = {\r\n '''facebook/data2vec-vision-base-ft''': (\r\n '''https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json'''\r\n ),\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass A__ (\t\t\t\t\t\tUpperCAmelCase__ ):\r\n __UpperCamelCase : str\t =\t\t\t\t\t\t\t\"data2vec-vision\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __init__( self\t\t\t:List[Any] ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Dict=7_6_8 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Dict=1_2 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:str=1_2 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Dict=3_0_7_2 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Tuple=\"gelu\" ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Optional[int]=0.0 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Union[str, Any]=0.0 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:List[Any]=0.02 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Optional[int]=1e-12 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:str=2_2_4 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Dict=1_6 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Any=3 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Any=False ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:str=False ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Tuple=False ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:int=False ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Union[str, Any]=0.1 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Optional[Any]=0.1 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Any=True ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Dict=[3, 5, 7, 1_1] ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Any=[1, 2, 3, 6] ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Dict=True ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:List[str]=0.4 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Tuple=2_5_6 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Union[str, Any]=1 ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:str=False ,\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t:Any=2_5_5 ,\t\t\t\t\t\t**SCREAMING_SNAKE_CASE\t\t\t:Optional[Any] ,\t\t\t\t\t\t) ->\t\t\t\t\tint:\r\n\r\n\r\n\r\n\r\n '''simple docstring'''\r\n super().__init__(**UpperCamelCase_\t)\r\n\r\n _a : List[str] \t\t\t\t\t=hidden_size\r\n _a : Union[str, Any] \t\t\t\t\t=num_hidden_layers\r\n _a : Any \t\t\t\t\t=num_attention_heads\r\n _a : Optional[int] \t\t\t\t\t=intermediate_size\r\n _a : Optional[Any] \t\t\t\t\t=hidden_act\r\n _a : int \t\t\t\t\t=hidden_dropout_prob\r\n _a : Tuple \t\t\t\t\t=attention_probs_dropout_prob\r\n _a : Union[str, Any] \t\t\t\t\t=initializer_range\r\n _a : Dict \t\t\t\t\t=layer_norm_eps\r\n\r\n _a : int \t\t\t\t\t=image_size\r\n _a : Any \t\t\t\t\t=patch_size\r\n _a : Optional[int] \t\t\t\t\t=num_channels\r\n _a : Union[str, Any] \t\t\t\t\t=use_mask_token\r\n _a : Optional[Any] \t\t\t\t\t=use_absolute_position_embeddings\r\n _a : List[str] \t\t\t\t\t=use_relative_position_bias\r\n _a : int \t\t\t\t\t=use_shared_relative_position_bias\r\n _a : str \t\t\t\t\t=layer_scale_init_value\r\n _a : List[str] \t\t\t\t\t=drop_path_rate\r\n _a : Tuple \t\t\t\t\t=use_mean_pooling\r\n # decode head attributes (semantic segmentation)\r\n _a : Any \t\t\t\t\t=out_indices\r\n _a : int \t\t\t\t\t=pool_scales\r\n # auxiliary head attributes (semantic segmentation)\r\n _a : int \t\t\t\t\t=use_auxiliary_head\r\n _a : Optional[Any] \t\t\t\t\t=auxiliary_loss_weight\r\n _a : List[Any] \t\t\t\t\t=auxiliary_channels\r\n _a : List[str] \t\t\t\t\t=auxiliary_num_convs\r\n _a : Union[str, Any] \t\t\t\t\t=auxiliary_concat_input\r\n _a : List[Any] \t\t\t\t\t=semantic_loss_ignore_index\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass A__ (\t\t\t\t\t\tUpperCAmelCase__ ):\r\n __UpperCamelCase : List[Any]\t =\t\t\t\t\t\t\tversion.parse(\"1.11\" )\r\n\r\n\r\n\r\n\r\n\r\n\r\n @property\r\n def __UpperCAmelCase ( self\t\t\t:int\t) ->\t\t\t\t\tMapping[str, Mapping[int, str]]:\r\n\r\n\r\n\r\n\r\n '''simple docstring'''\r\n return OrderedDict(\r\n [\r\n (\"\"\"pixel_values\"\"\", {0: \"\"\"batch\"\"\", 1: \"\"\"num_channels\"\"\", 2: \"\"\"height\"\"\", 3: \"\"\"width\"\"\"}),\r\n ]\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n @property\r\n def __UpperCAmelCase ( self\t\t\t:int\t) ->\t\t\t\t\tfloat:\r\n\r\n\r\n\r\n\r\n '''simple docstring'''\r\n return 1e-4\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":276,"string":"276"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\nfrom argparse import ArgumentParser, Namespace\r\nfrom typing import Any, List, Optional\r\n\r\nfrom ..pipelines import Pipeline, get_supported_tasks, pipeline\r\nfrom ..utils import logging\r\nfrom . import BaseTransformersCLICommand\r\n\r\n\r\ntry:\r\n\t\t\tfrom fastapi import Body, FastAPI, HTTPException\r\n\t\t\tfrom fastapi.routing import APIRoute\r\n\t\t\tfrom pydantic import BaseModel\r\n\t\t\tfrom starlette.responses import JSONResponse\r\n\t\t\tfrom uvicorn import run\r\n\r\n\t\t\ta_\t = True\r\nexcept (ImportError, AttributeError):\r\n\t\t\ta_\t = object\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef \t\t\t__UpperCAmelCase\t\t\t( *__UpperCamelCase ,\t\t\t\t\t\t\t**__UpperCamelCase ):\r\n\t\t\t\t\t\tpass\r\n\r\n\r\n\t\t\ta_\t = False\r\n\r\n\r\na_\t = logging.get_logger('transformers-cli/serving')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t__UpperCAmelCase\t\t\t( __UpperCamelCase ):\r\n\t\t\t__lowercase : Optional[Any] = pipeline(\r\n\t\t\t task=args.task ,\t\t\t\t\t\t\tmodel=args.model if args.model else None ,\t\t\t\t\t\t\tconfig=args.config ,\t\t\t\t\t\t\ttokenizer=args.tokenizer ,\t\t\t\t\t\t\tdevice=args.device ,\t\t\t\t\t\t\t)\r\n\t\t\treturn ServeCommand(__UpperCamelCase ,\t\t\t\t\t\t\targs.host ,\t\t\t\t\t\t\targs.port ,\t\t\t\t\t\t\targs.workers )\r\n\r\nclass UpperCAmelCase_ ( snake_case\t\t\t\t\t\t):\r\n\t\tUpperCamelCase\t\t\t\t\t\t =42\r\n\r\n\r\nclass UpperCAmelCase_ ( snake_case\t\t\t\t\t\t):\r\n\t\tUpperCamelCase\t\t\t\t\t\t =42\r\n\t\tUpperCamelCase\t\t\t\t\t\t =42\r\n\r\n\r\nclass UpperCAmelCase_ ( snake_case\t\t\t\t\t\t):\r\n\t\tUpperCamelCase\t\t\t\t\t\t =42\r\n\r\n\r\nclass UpperCAmelCase_ ( snake_case\t\t\t\t\t\t):\r\n\t\tUpperCamelCase\t\t\t\t\t\t =42\r\n\r\n\r\nclass UpperCAmelCase_ ( snake_case\t\t\t\t\t\t):\r\n\t\t@staticmethod\r\n\t\tdef _lowerCamelCase\t\t\t\t(\t\tUpperCamelCase_ )\t\t-> Tuple:\r\n\t\t\t\t\t__lowercase : Dict = parser.add_parser(\r\n\t\t\t\t\t '''serve'''\t\t\t\t\t\t\t,\t\thelp='''CLI tool to run inference requests through REST and GraphQL endpoints.''' )\r\n\t\t\t\t\tserve_parser.add_argument(\r\n\t\t\t\t\t '''--task'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\tchoices=get_supported_tasks()\t\t\t\t\t\t\t,\t\thelp='''The task to run the pipeline on'''\t\t\t\t\t\t\t,\t\t)\r\n\t\t\t\t\tserve_parser.add_argument('''--host'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\tdefault='''localhost'''\t\t\t\t\t\t\t,\t\thelp='''Interface the server will listen on.''' )\r\n\t\t\t\t\tserve_parser.add_argument('''--port'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\tdefault=88_88\t\t\t\t\t\t\t,\t\thelp='''Port the serving will listen to.''' )\r\n\t\t\t\t\tserve_parser.add_argument('''--workers'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\tdefault=1\t\t\t\t\t\t\t,\t\thelp='''Number of http workers''' )\r\n\t\t\t\t\tserve_parser.add_argument('''--model'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\thelp='''Model\\'s name or path to stored model.''' )\r\n\t\t\t\t\tserve_parser.add_argument('''--config'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\thelp='''Model\\'s config name or path to stored model.''' )\r\n\t\t\t\t\tserve_parser.add_argument('''--tokenizer'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\thelp='''Tokenizer name to use.''' )\r\n\t\t\t\t\tserve_parser.add_argument(\r\n\t\t\t\t\t '''--device'''\t\t\t\t\t\t\t,\t\ttype=UpperCamelCase_\t\t\t\t\t\t\t,\t\tdefault=-1\t\t\t\t\t\t\t,\t\thelp='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)'''\t\t\t\t\t\t\t,\t\t)\r\n\t\t\t\t\tserve_parser.set_defaults(func=UpperCamelCase_ )\r\n\t\tdef __init__(\t\tself\t\t\t\t\t\t\t,\t\tUpperCamelCase_\t\t\t\t\t\t\t,\t\tUpperCamelCase_\t\t\t\t\t\t\t,\t\tUpperCamelCase_\t\t\t\t\t\t\t,\t\tUpperCamelCase_ )\t\t-> Any:\r\n\t\t\t\t\t__lowercase : List[Any] = pipeline\r\n\r\n\t\t\t\t\t__lowercase : str = host\r\n\t\t\t\t\t__lowercase : List[str] = port\r\n\t\t\t\t\t__lowercase : str = workers\r\n\r\n\t\t\t\t\tif not _serve_dependencies_installed:\r\n\t\t\t\t\t\t\t\traise RuntimeError(\r\n\t\t\t\t\t\t\t\t '''Using serve command requires FastAPI and uvicorn. '''\r\n\t\t\t\t\t\t\t\t '''Please install transformers with [serving]: pip install \"transformers[serving]\".'''\r\n\t\t\t\t\t\t\t\t '''Or install FastAPI and uvicorn separately.''' )\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tlogger.info(F\"\"\"Serving model over {host}:{port}\"\"\" )\r\n\t\t\t\t\t\t\t\t__lowercase : int = FastAPI(\r\n\t\t\t\t\t\t\t\t routes=[\r\n\t\t\t\t\t\t\t\t APIRoute(\r\n\t\t\t\t\t\t\t\t '''/'''\t\t\t\t\t\t\t,\t\tself.model_info\t\t\t\t\t\t\t,\t\tresponse_model=UpperCamelCase_\t\t\t\t\t\t\t,\t\tresponse_class=UpperCamelCase_\t\t\t\t\t\t\t,\t\tmethods=['''GET''']\t\t\t\t\t\t\t,\t\t),\r\n\t\t\t\t\t\t\t\t APIRoute(\r\n\t\t\t\t\t\t\t\t '''/tokenize'''\t\t\t\t\t\t\t,\t\tself.tokenize\t\t\t\t\t\t\t,\t\tresponse_model=UpperCamelCase_\t\t\t\t\t\t\t,\t\tresponse_class=UpperCamelCase_\t\t\t\t\t\t\t,\t\tmethods=['''POST''']\t\t\t\t\t\t\t,\t\t),\r\n\t\t\t\t\t\t\t\t APIRoute(\r\n\t\t\t\t\t\t\t\t '''/detokenize'''\t\t\t\t\t\t\t,\t\tself.detokenize\t\t\t\t\t\t\t,\t\tresponse_model=UpperCamelCase_\t\t\t\t\t\t\t,\t\tresponse_class=UpperCamelCase_\t\t\t\t\t\t\t,\t\tmethods=['''POST''']\t\t\t\t\t\t\t,\t\t),\r\n\t\t\t\t\t\t\t\t APIRoute(\r\n\t\t\t\t\t\t\t\t '''/forward'''\t\t\t\t\t\t\t,\t\tself.forward\t\t\t\t\t\t\t,\t\tresponse_model=UpperCamelCase_\t\t\t\t\t\t\t,\t\tresponse_class=UpperCamelCase_\t\t\t\t\t\t\t,\t\tmethods=['''POST''']\t\t\t\t\t\t\t,\t\t),\r\n\t\t\t\t\t\t\t\t ]\t\t\t\t\t\t\t,\t\ttimeout=6_00\t\t\t\t\t\t\t,\t\t)\r\n\t\tdef _lowerCamelCase\t\t\t\t(\t\tself )\t\t-> Union[str, Any]:\r\n\t\t\t\t\trun(self._app\t\t\t\t\t\t\t,\t\thost=self.host\t\t\t\t\t\t\t,\t\tport=self.port\t\t\t\t\t\t\t,\t\tworkers=self.workers )\r\n\t\tdef _lowerCamelCase\t\t\t\t(\t\tself )\t\t-> Tuple:\r\n\t\t\t\t\treturn ServeModelInfoResult(infos=vars(self._pipeline.model.config ) )\r\n\t\tdef _lowerCamelCase\t\t\t\t(\t\tself\t\t\t\t\t\t\t,\t\tUpperCamelCase_ = Body(UpperCamelCase_\t\t\t\t\t\t\t,\t\tembed=UpperCamelCase_ )\t\t\t\t\t\t\t,\t\tUpperCamelCase_ = Body(UpperCamelCase_\t\t\t\t\t\t\t,\t\tembed=UpperCamelCase_ ) )\t\t-> Optional[int]:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t__lowercase : Any = self._pipeline.tokenizer.tokenize(UpperCamelCase_ )\r\n\r\n\t\t\t\t\t\t\t\tif return_ids:\r\n\t\t\t\t\t\t\t\t\t\t\t__lowercase : Dict = self._pipeline.tokenizer.convert_tokens_to_ids(UpperCamelCase_ )\r\n\t\t\t\t\t\t\t\t\t\t\treturn ServeTokenizeResult(tokens=UpperCamelCase_\t\t\t\t\t\t\t,\t\ttokens_ids=UpperCamelCase_ )\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\treturn ServeTokenizeResult(tokens=UpperCamelCase_ )\r\n\r\n\t\t\t\t\texcept Exception as e:\r\n\t\t\t\t\t\t\t\traise HTTPException(status_code=5_00\t\t\t\t\t\t\t,\t\tdetail={'''model''': '''''', '''error''': str(UpperCamelCase_ )} )\r\n\t\tdef _lowerCamelCase\t\t\t\t(\t\tself\t\t\t\t\t\t\t,\t\tUpperCamelCase_ = Body(UpperCamelCase_\t\t\t\t\t\t\t,\t\tembed=UpperCamelCase_ )\t\t\t\t\t\t\t,\t\tUpperCamelCase_ = Body(UpperCamelCase_\t\t\t\t\t\t\t,\t\tembed=UpperCamelCase_ )\t\t\t\t\t\t\t,\t\tUpperCamelCase_ = Body(UpperCamelCase_\t\t\t\t\t\t\t,\t\tembed=UpperCamelCase_ )\t\t\t\t\t\t\t,\t\t)\t\t-> Dict:\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t__lowercase : Tuple = self._pipeline.tokenizer.decode(UpperCamelCase_\t\t\t\t\t\t\t,\t\tUpperCamelCase_\t\t\t\t\t\t\t,\t\tUpperCamelCase_ )\r\n\t\t\t\t\t\t\t\treturn ServeDeTokenizeResult(model=''''''\t\t\t\t\t\t\t,\t\ttext=UpperCamelCase_ )\r\n\t\t\t\t\texcept Exception as e:\r\n\t\t\t\t\t\t\t\traise HTTPException(status_code=5_00\t\t\t\t\t\t\t,\t\tdetail={'''model''': '''''', '''error''': str(UpperCamelCase_ )} )\r\n\t\tasync def _lowerCamelCase\t\t\t\t(\t\tself\t\t\t\t\t\t\t,\t\tUpperCamelCase_=Body(UpperCamelCase_\t\t\t\t\t\t\t,\t\tembed=UpperCamelCase_ ) )\t\t-> Union[str, Any]:\r\n\r\n\t\t\t\t\t# Check we don't have empty string\r\n\t\t\t\t\tif len(UpperCamelCase_ ) == 0:\r\n\t\t\t\t\t\t\t\treturn ServeForwardResult(output=[]\t\t\t\t\t\t\t,\t\tattention=[] )\r\n\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t# Forward through the model\r\n\t\t\t\t\t\t\t\t__lowercase : Optional[Any] = self._pipeline(UpperCamelCase_ )\r\n\t\t\t\t\t\t\t\treturn ServeForwardResult(output=UpperCamelCase_ )\r\n\t\t\t\t\texcept Exception as e:\r\n\t\t\t\t\t\t\t\traise HTTPException(5_00\t\t\t\t\t\t\t,\t\t{'''error''': str(UpperCamelCase_ )} )\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":249,"string":"249"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":239,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\nfrom typing import TYPE_CHECKING\r\n\r\nfrom ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available\r\n\r\n\r\n__UpperCamelCase\t\t\t =\t\t\t\t\t{\r\n \"configuration_mvp\": [\"MVP_PRETRAINED_CONFIG_ARCHIVE_MAP\", \"MvpConfig\", \"MvpOnnxConfig\"],\r\n \"tokenization_mvp\": [\"MvpTokenizer\"],\r\n}\r\n\r\ntry:\r\n\tif not is_tokenizers_available():\r\n\t\traise OptionalDependencyNotAvailable()\r\nexcept OptionalDependencyNotAvailable:\r\n\tpass\r\nelse:\r\n\t__UpperCamelCase\t\t\t =\t\t\t\t\t[\"MvpTokenizerFast\"]\r\n\r\ntry:\r\n\tif not is_torch_available():\r\n\t\traise OptionalDependencyNotAvailable()\r\nexcept OptionalDependencyNotAvailable:\r\n\tpass\r\nelse:\r\n\t__UpperCamelCase\t\t\t =\t\t\t\t\t[\r\n\t \"MVP_PRETRAINED_MODEL_ARCHIVE_LIST\",\r\n\t \"MvpForCausalLM\",\r\n\t \"MvpForConditionalGeneration\",\r\n\t \"MvpForQuestionAnswering\",\r\n\t \"MvpForSequenceClassification\",\r\n\t \"MvpModel\",\r\n\t \"MvpPreTrainedModel\",\r\n\t]\r\n\r\nif TYPE_CHECKING:\r\n\tfrom .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig\r\n\tfrom .tokenization_mvp import MvpTokenizer\r\n\r\n\ttry:\r\n\t\tif not is_tokenizers_available():\r\n\t\t\traise OptionalDependencyNotAvailable()\r\n\texcept OptionalDependencyNotAvailable:\r\n\t\tpass\r\n\telse:\r\n\t\tfrom .tokenization_mvp_fast import MvpTokenizerFast\r\n\r\n\ttry:\r\n\t\tif not is_torch_available():\r\n\t\t\traise OptionalDependencyNotAvailable()\r\n\texcept OptionalDependencyNotAvailable:\r\n\t\tpass\r\n\telse:\r\n\t\tfrom .modeling_mvp import (\r\n\t\t MVP_PRETRAINED_MODEL_ARCHIVE_LIST,\r\n\t\t MvpForCausalLM,\r\n\t\t MvpForConditionalGeneration,\r\n\t\t MvpForQuestionAnswering,\r\n\t\t MvpForSequenceClassification,\r\n\t\t MvpModel,\r\n\t\t MvpPreTrainedModel,\r\n\t\t)\r\n\r\nelse:\r\n\timport sys\r\n\r\n\t__UpperCamelCase\t\t\t =\t\t\t\t\t_LazyModule(__name__, globals()[\"__file__\"], _import_structure, module_spec=__spec__)\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":13,"string":"13"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport gc\r\nimport random\r\nimport unittest\r\n\r\nimport numpy as np\r\nimport torch\r\nfrom PIL import Image\r\nfrom transformers import XLMRobertaTokenizerFast\r\n\r\nfrom diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel\r\nfrom diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP\r\nfrom diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device\r\nfrom diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu\r\n\r\nfrom ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference\r\n\r\n\r\nenable_full_determinism()\r\n\r\n\r\n\r\n\r\nclass \t\t\t\t_A\t\t\t\t(\t\t\t__lowercase\t\t,\t\t\tunittest.TestCase\t\t\t\t\t\t):\r\n\t\tlowercase__: int\t\t\t\t\t\t\t = KandinskyImgaImgPipeline\r\n\t\tlowercase__: Any\t\t\t\t\t\t\t = ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''']\r\n\t\tlowercase__: int\t\t\t\t\t\t\t = [\r\n\t\t '''prompt''',\r\n\t\t '''negative_prompt''',\r\n\t\t '''image_embeds''',\r\n\t\t '''negative_image_embeds''',\r\n\t\t '''image''',\r\n\t\t]\r\n\t\tlowercase__: List[Any]\t\t\t\t\t\t\t = [\r\n\t\t '''generator''',\r\n\t\t '''height''',\r\n\t\t '''width''',\r\n\t\t '''strength''',\r\n\t\t '''guidance_scale''',\r\n\t\t '''negative_prompt''',\r\n\t\t '''num_inference_steps''',\r\n\t\t '''return_dict''',\r\n\t\t '''guidance_scale''',\r\n\t\t '''num_images_per_prompt''',\r\n\t\t '''output_type''',\r\n\t\t '''return_dict''',\r\n\t\t]\r\n\t\tlowercase__: Any\t\t\t\t\t\t\t = False\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Optional[Any]\t)\t\t\t-> Optional[int]:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn 32\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: str\t)\t\t\t-> str:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn 32\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Tuple\t)\t\t\t-> Any:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn self.time_input_dim\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: List[str]\t)\t\t\t-> Optional[int]:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn self.time_input_dim * 4\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Dict\t)\t\t\t-> Optional[Any]:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn 1_00\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: List[str]\t)\t\t\t-> List[str]:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: str = XLMRobertaTokenizerFast.from_pretrained(\"\"\"YiYiXu/tiny-random-mclip-base\"\"\"\t)\r\n\t\t\t\t\treturn tokenizer\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Union[str, Any]\t)\t\t\t-> List[Any]:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\ttorch.manual_seed(0\t)\r\n\t\t\t\t\t__snake_case\t\t\t: int = MCLIPConfig(\r\n\t\t\t\t\t numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=10_05 , )\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Tuple = MultilingualCLIP(__magic_name__\t)\r\n\t\t\t\t\t__snake_case\t\t\t: Optional[Any] = text_encoder.eval()\r\n\r\n\t\t\t\t\treturn text_encoder\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Tuple\t)\t\t\t-> Optional[int]:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\ttorch.manual_seed(0\t)\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: int = {\r\n\t\t\t\t\t \"\"\"in_channels\"\"\": 4,\r\n\t\t\t\t\t # Out channels is double in channels because predicts mean and variance\r\n\t\t\t\t\t \"\"\"out_channels\"\"\": 8,\r\n\t\t\t\t\t \"\"\"addition_embed_type\"\"\": \"\"\"text_image\"\"\",\r\n\t\t\t\t\t \"\"\"down_block_types\"\"\": (\"\"\"ResnetDownsampleBlock2D\"\"\", \"\"\"SimpleCrossAttnDownBlock2D\"\"\"),\r\n\t\t\t\t\t \"\"\"up_block_types\"\"\": (\"\"\"SimpleCrossAttnUpBlock2D\"\"\", \"\"\"ResnetUpsampleBlock2D\"\"\"),\r\n\t\t\t\t\t \"\"\"mid_block_type\"\"\": \"\"\"UNetMidBlock2DSimpleCrossAttn\"\"\",\r\n\t\t\t\t\t \"\"\"block_out_channels\"\"\": (self.block_out_channels_a, self.block_out_channels_a * 2),\r\n\t\t\t\t\t \"\"\"layers_per_block\"\"\": 1,\r\n\t\t\t\t\t \"\"\"encoder_hid_dim\"\"\": self.text_embedder_hidden_size,\r\n\t\t\t\t\t \"\"\"encoder_hid_dim_type\"\"\": \"\"\"text_image_proj\"\"\",\r\n\t\t\t\t\t \"\"\"cross_attention_dim\"\"\": self.cross_attention_dim,\r\n\t\t\t\t\t \"\"\"attention_head_dim\"\"\": 4,\r\n\t\t\t\t\t \"\"\"resnet_time_scale_shift\"\"\": \"\"\"scale_shift\"\"\",\r\n\t\t\t\t\t \"\"\"class_embed_type\"\"\": None,\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Tuple = UNetaDConditionModel(**__magic_name__\t)\r\n\t\t\t\t\treturn model\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: str\t)\t\t\t-> Dict:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn {\r\n\t\t\t\t\t \"block_out_channels\": [32, 64],\r\n\t\t\t\t\t \"down_block_types\": [\"DownEncoderBlock2D\", \"AttnDownEncoderBlock2D\"],\r\n\t\t\t\t\t \"in_channels\": 3,\r\n\t\t\t\t\t \"latent_channels\": 4,\r\n\t\t\t\t\t \"layers_per_block\": 1,\r\n\t\t\t\t\t \"norm_num_groups\": 8,\r\n\t\t\t\t\t \"norm_type\": \"spatial\",\r\n\t\t\t\t\t \"num_vq_embeddings\": 12,\r\n\t\t\t\t\t \"out_channels\": 3,\r\n\t\t\t\t\t \"up_block_types\": [\r\n\t\t\t\t\t \"AttnUpDecoderBlock2D\",\r\n\t\t\t\t\t \"UpDecoderBlock2D\",\r\n\t\t\t\t\t ],\r\n\t\t\t\t\t \"vq_embed_dim\": 4,\r\n\t\t\t\t\t}\r\n\r\n\t\t@property\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Optional[Any]\t)\t\t\t-> int:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\ttorch.manual_seed(0\t)\r\n\t\t\t\t\t__snake_case\t\t\t: int = VQModel(**self.dummy_movq_kwargs\t)\r\n\t\t\t\t\treturn model\r\n\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Tuple\t)\t\t\t-> str:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Tuple = self.dummy_text_encoder\r\n\t\t\t\t\t__snake_case\t\t\t: Dict = self.dummy_tokenizer\r\n\t\t\t\t\t__snake_case\t\t\t: Dict = self.dummy_unet\r\n\t\t\t\t\t__snake_case\t\t\t: int = self.dummy_movq\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: List[Any] = {\r\n\t\t\t\t\t \"\"\"num_train_timesteps\"\"\": 10_00,\r\n\t\t\t\t\t \"\"\"beta_schedule\"\"\": \"\"\"linear\"\"\",\r\n\t\t\t\t\t \"\"\"beta_start\"\"\": 0.00085,\r\n\t\t\t\t\t \"\"\"beta_end\"\"\": 0.012,\r\n\t\t\t\t\t \"\"\"clip_sample\"\"\": False,\r\n\t\t\t\t\t \"\"\"set_alpha_to_one\"\"\": False,\r\n\t\t\t\t\t \"\"\"steps_offset\"\"\": 0,\r\n\t\t\t\t\t \"\"\"prediction_type\"\"\": \"\"\"epsilon\"\"\",\r\n\t\t\t\t\t \"\"\"thresholding\"\"\": False,\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Dict = DDIMScheduler(**__magic_name__\t)\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Any = {\r\n\t\t\t\t\t \"\"\"text_encoder\"\"\": text_encoder,\r\n\t\t\t\t\t \"\"\"tokenizer\"\"\": tokenizer,\r\n\t\t\t\t\t \"\"\"unet\"\"\": unet,\r\n\t\t\t\t\t \"\"\"scheduler\"\"\": scheduler,\r\n\t\t\t\t\t \"\"\"movq\"\"\": movq,\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\treturn components\r\n\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: str , __magic_name__\t\t\t: str , __magic_name__\t\t\t: Union[str, Any]=0\t)\t\t\t-> str:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Dict = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__magic_name__\t)\t).to(__magic_name__\t)\r\n\t\t\t\t\t__snake_case\t\t\t: int = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1\t)\t).to(__magic_name__\t)\r\n\t\t\t\t\t# create init_image\r\n\t\t\t\t\t__snake_case\t\t\t: Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(__magic_name__\t)\t).to(__magic_name__\t)\r\n\t\t\t\t\t__snake_case\t\t\t: Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1\t)[0]\r\n\t\t\t\t\t__snake_case\t\t\t: Optional[int] = Image.fromarray(np.uinta(__magic_name__\t)\t).convert(\"\"\"RGB\"\"\"\t).resize((2_56, 2_56)\t)\r\n\r\n\t\t\t\t\tif str(__magic_name__\t).startswith(\"\"\"mps\"\"\"\t):\r\n\t\t\t\t\t\t\t\t__snake_case\t\t\t: str = torch.manual_seed(__magic_name__\t)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t__snake_case\t\t\t: str = torch.Generator(device=__magic_name__\t).manual_seed(__magic_name__\t)\r\n\t\t\t\t\t__snake_case\t\t\t: Optional[Any] = {\r\n\t\t\t\t\t \"\"\"prompt\"\"\": \"\"\"horse\"\"\",\r\n\t\t\t\t\t \"\"\"image\"\"\": init_image,\r\n\t\t\t\t\t \"\"\"image_embeds\"\"\": image_embeds,\r\n\t\t\t\t\t \"\"\"negative_image_embeds\"\"\": negative_image_embeds,\r\n\t\t\t\t\t \"\"\"generator\"\"\": generator,\r\n\t\t\t\t\t \"\"\"height\"\"\": 64,\r\n\t\t\t\t\t \"\"\"width\"\"\": 64,\r\n\t\t\t\t\t \"\"\"num_inference_steps\"\"\": 10,\r\n\t\t\t\t\t \"\"\"guidance_scale\"\"\": 7.0,\r\n\t\t\t\t\t \"\"\"strength\"\"\": 0.2,\r\n\t\t\t\t\t \"\"\"output_type\"\"\": \"\"\"np\"\"\",\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn inputs\r\n\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: int\t)\t\t\t-> str:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Dict = \"\"\"cpu\"\"\"\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Union[str, Any] = self.get_dummy_components()\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: List[str] = self.pipeline_class(**__magic_name__\t)\r\n\t\t\t\t\t__snake_case\t\t\t: Optional[Any] = pipe.to(__magic_name__\t)\r\n\r\n\t\t\t\t\tpipe.set_progress_bar_config(disable=__magic_name__\t)\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: List[str] = pipe(**self.get_dummy_inputs(__magic_name__\t)\t)\r\n\t\t\t\t\t__snake_case\t\t\t: List[str] = output.images\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Any = pipe(\r\n\t\t\t\t\t **self.get_dummy_inputs(__magic_name__\t) , return_dict=__magic_name__ , )[0]\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Optional[int] = image[0, -3:, -3:, -1]\r\n\t\t\t\t\t__snake_case\t\t\t: str = image_from_tuple[0, -3:, -3:, -1]\r\n\r\n\t\t\t\t\tassert image.shape == (1, 64, 64, 3)\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: int = np.array(\r\n\t\t\t\t\t [0.61474943, 0.6073539, 0.43308544, 0.5928269, 0.47493595, 0.46755973, 0.4613838, 0.45368797, 0.50119233]\t)\r\n\t\t\t\t\tassert (\r\n\t\t\t\t\t np.abs(image_slice.flatten() - expected_slice\t).max() < 1E-2\r\n\t\t\t\t\t), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''\r\n\t\t\t\t\tassert (\r\n\t\t\t\t\t np.abs(image_from_tuple_slice.flatten() - expected_slice\t).max() < 1E-2\r\n\t\t\t\t\t), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''\r\n\r\n\r\n\r\n\r\n\r\n@slow\r\n@require_torch_gpu\r\nclass \t\t\t\t_A\t\t\t\t(\t\t\tunittest.TestCase\t\t\t\t\t\t):\r\n\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: List[str]\t)\t\t\t-> Optional[Any]:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tsuper().tearDown()\r\n\t\t\t\t\tgc.collect()\r\n\t\t\t\t\ttorch.cuda.empty_cache()\r\n\r\n\t\tdef \t\t\t\t\tlowercase__ ( self\t\t\t: Optional[int]\t)\t\t\t-> str:\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Union[str, Any] = load_numpy(\r\n\t\t\t\t\t \"\"\"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\"\"\r\n\t\t\t\t\t \"\"\"/kandinsky/kandinsky_img2img_frog.npy\"\"\"\t)\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: List[str] = load_image(\r\n\t\t\t\t\t \"\"\"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\"\" \"\"\"/kandinsky/cat.png\"\"\"\t)\r\n\t\t\t\t\t__snake_case\t\t\t: List[Any] = \"\"\"A red cartoon frog, 4k\"\"\"\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: str = KandinskyPriorPipeline.from_pretrained(\r\n\t\t\t\t\t \"\"\"kandinsky-community/kandinsky-2-1-prior\"\"\" , torch_dtype=torch.floataa\t)\r\n\t\t\t\t\tpipe_prior.to(__magic_name__\t)\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Union[str, Any] = KandinskyImgaImgPipeline.from_pretrained(\r\n\t\t\t\t\t \"\"\"kandinsky-community/kandinsky-2-1\"\"\" , torch_dtype=torch.floataa\t)\r\n\t\t\t\t\t__snake_case\t\t\t: Any = pipeline.to(__magic_name__\t)\r\n\r\n\t\t\t\t\tpipeline.set_progress_bar_config(disable=__magic_name__\t)\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: List[str] = torch.Generator(device=\"\"\"cpu\"\"\"\t).manual_seed(0\t)\r\n\t\t\t\t\t__snake_case , __snake_case\t\t\t: Optional[Any] = pipe_prior(\r\n\t\t\t\t\t __magic_name__ , generator=__magic_name__ , num_inference_steps=5 , negative_prompt=\"\"\"\"\"\" , ).to_tuple()\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: List[str] = pipeline(\r\n\t\t\t\t\t __magic_name__ , image=__magic_name__ , image_embeds=__magic_name__ , negative_image_embeds=__magic_name__ , generator=__magic_name__ , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type=\"\"\"np\"\"\" , )\r\n\r\n\t\t\t\t\t__snake_case\t\t\t: Dict = output.images[0]\r\n\r\n\t\t\t\t\tassert image.shape == (7_68, 7_68, 3)\r\n\r\n\t\t\t\t\tassert_mean_pixel_difference(__magic_name__ , __magic_name__\t)\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":13,"string":"13"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":240,"cells":{"code":{"kind":"string","value":"'''simple docstring'''\r\r\r\r\rimport inspect\rimport unittest\r\rfrom transformers import ViTConfig\rfrom transformers.testing_utils import (\r require_accelerate,\r require_torch,\r require_torch_gpu,\r require_vision,\r slow,\r torch_device,\r)\rfrom transformers.utils import cached_property, is_torch_available, is_vision_available\r\rfrom ...test_configuration_common import ConfigTester\rfrom ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor\rfrom ...test_pipeline_mixin import PipelineTesterMixin\r\r\rif is_torch_available():\r\t\t\t\t\t\timport torch\r\t\t\t\t\t\tfrom torch import nn\r\r\t\t\t\t\t\tfrom transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel\r\t\t\t\t\t\tfrom transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST\r\r\rif is_vision_available():\r\t\t\t\t\t\tfrom PIL import Image\r\r\t\t\t\t\t\tfrom transformers import ViTImageProcessor\r\r\r\r\r\rclass __magic_name__\t\t\t\t\t\t:\r\r\r\r\r\r\r\r\t\t\tdef __init__(\tself\t\t\t\t: List[Any]\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Optional[Any]\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Optional[Any]=13\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Optional[int]=30\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Union[str, Any]=2\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Dict=3\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[Any]=True\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Optional[Any]=True\t\t\t\t,\t\t\tlowercase_\t\t\t\t: int=32\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Union[str, Any]=5\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Dict=4\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[str]=37\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[str]=\"gelu\"\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[str]=0.1\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Any=0.1\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[str]=10\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Any=0.02\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[str]=None\t\t\t\t,\t\t\tlowercase_\t\t\t\t: str=2\t\t\t\t,\t\t\t):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= parent\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tAny\t\t\t\t\t\t\t\t\t\t= batch_size\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= image_size\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tTuple\t\t\t\t\t\t\t\t\t\t= patch_size\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= num_channels\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= is_training\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= use_labels\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= hidden_size\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= num_hidden_layers\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= num_attention_heads\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= intermediate_size\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= hidden_act\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= hidden_dropout_prob\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= attention_probs_dropout_prob\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= type_sequence_label_size\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= initializer_range\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tTuple\t\t\t\t\t\t\t\t\t\t= scope\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= encoder_stride\r\r\t\t\t\t\t\t\t\t\t\t# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= (image_size // patch_size) ** 2\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= num_patches + 1\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[int] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= None\r\t\t\t\t\t\t\t\t\t\tif self.use_labels:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= ids_tensor([self.batch_size]\t\t\t\t,\t\t\tself.type_sequence_label_size )\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= self.get_config()\r\r\t\t\t\t\t\t\t\t\t\treturn config, pixel_values, labels\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: int ):\r\t\t\t\t\t\t\t\t\t\treturn ViTConfig(\r\t\t\t\t\t\t\t\t\t\t image_size=self.image_size\t\t\t\t,\t\t\tpatch_size=self.patch_size\t\t\t\t,\t\t\tnum_channels=self.num_channels\t\t\t\t,\t\t\thidden_size=self.hidden_size\t\t\t\t,\t\t\tnum_hidden_layers=self.num_hidden_layers\t\t\t\t,\t\t\tnum_attention_heads=self.num_attention_heads\t\t\t\t,\t\t\tintermediate_size=self.intermediate_size\t\t\t\t,\t\t\thidden_act=self.hidden_act\t\t\t\t,\t\t\thidden_dropout_prob=self.hidden_dropout_prob\t\t\t\t,\t\t\tattention_probs_dropout_prob=self.attention_probs_dropout_prob\t\t\t\t,\t\t\tis_decoder=lowercase_\t\t\t\t,\t\t\tinitializer_range=self.initializer_range\t\t\t\t,\t\t\tencoder_stride=self.encoder_stride\t\t\t\t,\t\t\t)\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[int]\t\t\t\t,\t\t\tlowercase_\t\t\t\t: str\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[str]\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Union[str, Any] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tTuple\t\t\t\t\t\t\t\t\t\t= ViTModel(config=lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.to(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.eval()\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= model(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tself.parent.assertEqual(result.last_hidden_state.shape\t\t\t\t,\t\t\t(self.batch_size, self.seq_length, self.hidden_size) )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: List[str]\t\t\t\t,\t\t\tlowercase_\t\t\t\t: str\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Optional[Any]\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Optional[int] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= ViTForMaskedImageModeling(config=lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.to(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.eval()\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tTuple\t\t\t\t\t\t\t\t\t\t= model(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tself.parent.assertEqual(\r\t\t\t\t\t\t\t\t\t\t result.reconstruction.shape\t\t\t\t,\t\t\t(self.batch_size, self.num_channels, self.image_size, self.image_size) )\r\r\t\t\t\t\t\t\t\t\t\t# test greyscale images\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= 1\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= ViTForMaskedImageModeling(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.to(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.eval()\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= model(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tself.parent.assertEqual(result.reconstruction.shape\t\t\t\t,\t\t\t(self.batch_size, 1, self.image_size, self.image_size) )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: str\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Dict\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Dict\t\t\t\t,\t\t\tlowercase_\t\t\t\t: List[str] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tDict\t\t\t\t\t\t\t\t\t\t= self.type_sequence_label_size\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tAny\t\t\t\t\t\t\t\t\t\t= ViTForImageClassification(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.to(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.eval()\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= model(lowercase_\t\t\t\t,\t\t\tlabels=lowercase_ )\r\t\t\t\t\t\t\t\t\t\tself.parent.assertEqual(result.logits.shape\t\t\t\t,\t\t\t(self.batch_size, self.type_sequence_label_size) )\r\r\t\t\t\t\t\t\t\t\t\t# test greyscale images\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= 1\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= ViTForImageClassification(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.to(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tmodel.eval()\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= model(lowercase_ )\r\t\t\t\t\t\t\t\t\t\tself.parent.assertEqual(result.logits.shape\t\t\t\t,\t\t\t(self.batch_size, self.type_sequence_label_size) )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[int] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tDict\t\t\t\t\t\t\t\t\t\t= self.prepare_config_and_inputs()\r\t\t\t\t\t\t\t\t\t\t(\r\t\t\t\t\t\t\t\t\t\t (\r\t\t\t\t\t\t\t\t\t\t lowercase_\r\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t\t,\t\t\t\t\t\t(\r\t\t\t\t\t\t\t\t\t\t lowercase_\r\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t\t,\t\t\t\t\t\t(\r\t\t\t\t\t\t\t\t\t\t lowercase_\r\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t\t,\t\t\t\t\t\t\r\t\t\t\t\t\t\t\t\t\t)\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= config_and_inputs\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= {\"\"\"pixel_values\"\"\": pixel_values}\r\t\t\t\t\t\t\t\t\t\treturn config, inputs_dict\r\r\r\r\r\r@require_torch\rclass __magic_name__\t\t\t\t\t\t( _UpperCAmelCase, _UpperCAmelCase, unittest.TestCase):\r\t\t\tUpperCamelCase__\t\t\t\t= (\r\t\t\t (\r\t\t\t ViTModel,\r\t\t\t ViTForImageClassification,\r\t\t\t ViTForMaskedImageModeling,\r\t\t\t )\r\t\t\t if is_torch_available()\r\t\t\t else ()\r\t\t\t)\r\t\t\tUpperCamelCase__\t\t\t\t= (\r\t\t\t {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}\r\t\t\t if is_torch_available()\r\t\t\t else {}\r\t\t\t)\r\t\t\tUpperCamelCase__\t\t\t\t= True\r\r\t\t\tUpperCamelCase__\t\t\t\t= False\r\t\t\tUpperCamelCase__\t\t\t\t= False\r\t\t\tUpperCamelCase__\t\t\t\t= False\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Any ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tAny\t\t\t\t\t\t\t\t\t\t= ViTModelTester(self )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= ConfigTester(self\t\t\t\t,\t\t\tconfig_class=lowercase_\t\t\t\t,\t\t\thas_text_modality=lowercase_\t\t\t\t,\t\t\thidden_size=37 )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[int] ):\r\t\t\t\t\t\t\t\t\t\tself.config_tester.run_common_tests()\r\r\r\r\r\r\r\r\t\t\t@unittest.skip(reason=\"\"\"ViT does not use inputs_embeds\"\"\" )\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[Any] ):\r\t\t\t\t\t\t\t\t\t\tpass\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: List[str] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t\t,\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= self.model_tester.prepare_config_and_inputs_for_common()\r\r\t\t\t\t\t\t\t\t\t\tfor model_class in self.all_model_classes:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= model_class(lowercase_ )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsInstance(model.get_input_embeddings()\t\t\t\t,\t\t\t(nn.Module) )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tDict\t\t\t\t\t\t\t\t\t\t= model.get_output_embeddings()\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(x is None or isinstance(lowercase_\t\t\t\t,\t\t\tnn.Linear ) )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Tuple ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t\t,\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tTuple\t\t\t\t\t\t\t\t\t\t= self.model_tester.prepare_config_and_inputs_for_common()\r\r\t\t\t\t\t\t\t\t\t\tfor model_class in self.all_model_classes:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= model_class(lowercase_ )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tTuple\t\t\t\t\t\t\t\t\t\t= inspect.signature(model.forward )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# signature.parameters is an OrderedDict => so arg_names order is deterministic\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= [*signature.parameters.keys()]\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= [\"\"\"pixel_values\"\"\"]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertListEqual(arg_names[:1]\t\t\t\t,\t\t\tlowercase_ )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[int] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= self.model_tester.prepare_config_and_inputs()\r\t\t\t\t\t\t\t\t\t\tself.model_tester.create_and_check_model(*lowercase_ )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Union[str, Any] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tAny\t\t\t\t\t\t\t\t\t\t= self.model_tester.prepare_config_and_inputs()\r\t\t\t\t\t\t\t\t\t\tself.model_tester.create_and_check_for_masked_image_modeling(*lowercase_ )\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[Any] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= self.model_tester.prepare_config_and_inputs()\r\t\t\t\t\t\t\t\t\t\tself.model_tester.create_and_check_for_image_classification(*lowercase_ )\r\r\r\r\r\r\r\r\t\t\t@slow\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Union[str, Any] ):\r\t\t\t\t\t\t\t\t\t\tfor model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= ViTModel.from_pretrained(lowercase_ )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertIsNotNone(lowercase_ )\r\r\r\r\rdef \t\t\t\t\t\t\tlowerCamelCase\t( )\t\t\t-> str:\r\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= Image.open(\"\"\"./tests/fixtures/tests_samples/COCO/000000039769.png\"\"\" )\r\t\t\t\t\t\t\treturn image\r\r\r\r\r\r@require_torch\r@require_vision\rclass __magic_name__\t\t\t\t\t\t( unittest.TestCase):\r\r\r\r\r\r\r\r\t\t\t@cached_property\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Any ):\r\t\t\t\t\t\t\t\t\t\treturn ViTImageProcessor.from_pretrained(\"\"\"google/vit-base-patch16-224\"\"\" ) if is_vision_available() else None\r\r\r\r\r\r\r\r\t\t\t@slow\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Optional[int] ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tAny\t\t\t\t\t\t\t\t\t\t= ViTForImageClassification.from_pretrained(\"\"\"google/vit-base-patch16-224\"\"\" ).to(lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= self.default_image_processor\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= prepare_img()\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= image_processor(images=lowercase_\t\t\t\t,\t\t\treturn_tensors=\"\"\"pt\"\"\" ).to(lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\t# forward pass\r\t\t\t\t\t\t\t\t\t\twith torch.no_grad():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= model(**lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\t# verify the logits\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= torch.Size((1, 1000) )\r\t\t\t\t\t\t\t\t\t\tself.assertEqual(outputs.logits.shape\t\t\t\t,\t\t\tlowercase_ )\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= torch.tensor([-0.27_44, 0.82_15, -0.08_36] ).to(lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\tself.assertTrue(torch.allclose(outputs.logits[0, :3]\t\t\t\t,\t\t\tlowercase_\t\t\t\t,\t\t\tatol=1E-4 ) )\r\r\r\r\r\r\r\r\t\t\t@slow\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: str ):\r\t\t\t\t\t\t\t\t\t\t# ViT models have an `interpolate_pos_encoding` argument in their forward method,\r\t\t\t\t\t\t\t\t\t\t# allowing to interpolate the pre-trained position embeddings in order to use\r\t\t\t\t\t\t\t\t\t\t# the model on higher resolutions. The DINO model by Facebook AI leverages this\r\t\t\t\t\t\t\t\t\t\t# to visualize self-attention on higher resolution images.\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= ViTModel.from_pretrained(\"\"\"facebook/dino-vits8\"\"\" ).to(lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tstr\t\t\t\t\t\t\t\t\t\t= ViTImageProcessor.from_pretrained(\"\"\"facebook/dino-vits8\"\"\"\t\t\t\t,\t\t\tsize=480 )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= prepare_img()\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= image_processor(images=lowercase_\t\t\t\t,\t\t\treturn_tensors=\"\"\"pt\"\"\" )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= inputs.pixel_values.to(lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\t# forward pass\r\t\t\t\t\t\t\t\t\t\twith torch.no_grad():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tAny\t\t\t\t\t\t\t\t\t\t= model(lowercase_\t\t\t\t,\t\t\tinterpolate_pos_encoding=lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\t# verify the logits\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t= torch.Size((1, 3601, 384) )\r\t\t\t\t\t\t\t\t\t\tself.assertEqual(outputs.last_hidden_state.shape\t\t\t\t,\t\t\tlowercase_ )\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= torch.tensor(\r\t\t\t\t\t\t\t\t\t\t [[4.23_40, 4.39_06, -6.66_92], [4.54_63, 1.89_28, -6.72_57], [4.44_29, 0.84_96, -5.85_85]] ).to(lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\tself.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]\t\t\t\t,\t\t\tlowercase_\t\t\t\t,\t\t\tatol=1E-4 ) )\r\r\r\r\r\r\r\r\t\t\t@slow\r\t\t\t@require_accelerate\r\t\t\t@require_torch_gpu\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Dict ):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tAny\t\t\t\t\t\t\t\t\t\t= ViTModel.from_pretrained(\"\"\"facebook/dino-vits8\"\"\"\t\t\t\t,\t\t\ttorch_dtype=torch.floataa\t\t\t\t,\t\t\tdevice_map=\"\"\"auto\"\"\" )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= self.default_image_processor\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= prepare_img()\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= image_processor(images=lowercase_\t\t\t\t,\t\t\treturn_tensors=\"\"\"pt\"\"\" )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t= inputs.pixel_values.to(lowercase_ )\r\r\t\t\t\t\t\t\t\t\t\t# forward pass to make sure inference works in fp16\r\t\t\t\t\t\t\t\t\t\twith torch.no_grad():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t= model(lowercase_ )\r\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":239,"string":"239"},"style_context":{"kind":"string","value":"'''simple docstring'''\r\r\r\r\rimport sacrebleu as scb\rfrom packaging import version\rfrom sacrebleu import TER\r\rimport datasets\r\r\r_lowercase\t\t\t\t\t\t: List[str]\t\t\t\t\t\t=\t\t\t\t\t\t\"\\\\n@inproceedings{snover-etal-2006-study,\\n title = \\\"A Study of Translation Edit Rate with Targeted Human Annotation\\\",\\n author = \\\"Snover, Matthew and\\n Dorr, Bonnie and\\n Schwartz, Rich and\\n Micciulla, Linnea and\\n Makhoul, John\\\",\\n booktitle = \\\"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\\\",\\n month = aug # \\\" 8-12\\\",\\n year = \\\"2006\\\",\\n address = \\\"Cambridge, Massachusetts, USA\\\",\\n publisher = \\\"Association for Machine Translation in the Americas\\\",\\n url = \\\"https://aclanthology.org/2006.amta-papers.25\\\",\\n pages = \\\"223--231\\\",\\n}\\n@inproceedings{post-2018-call,\\n title = \\\"A Call for Clarity in Reporting {BLEU} Scores\\\",\\n author = \\\"Post, Matt\\\",\\n booktitle = \\\"Proceedings of the Third Conference on Machine Translation: Research Papers\\\",\\n month = oct,\\n year = \\\"2018\\\",\\n address = \\\"Belgium, Brussels\\\",\\n publisher = \\\"Association for Computational Linguistics\\\",\\n url = \\\"https://www.aclweb.org/anthology/W18-6319\\\",\\n pages = \\\"186--191\\\",\\n}\\n\"\r\r_lowercase\t\t\t\t\t\t: Tuple\t\t\t\t\t\t=\t\t\t\t\t\t\"\\\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\\nhere: https://github.com/jhclark/tercom.\\n\\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\\n\\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\\n\"\r\r_lowercase\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t=\t\t\t\t\t\t\"\\nProduces TER scores alongside the number of edits and reference length.\\n\\nArgs:\\n predictions (list of str): The system stream (a sequence of segments).\\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\\n Only applies if `normalized = True`. Defaults to `False`.\\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\\n\\nReturns:\\n 'score' (float): TER score (num_edits / sum_ref_lengths * 100)\\n 'num_edits' (int): The cumulative number of edits\\n 'ref_length' (float): The cumulative average reference length\\n\\nExamples:\\n Example 1:\\n >>> predictions = [\\\"does this sentence match??\\\",\\n ... \\\"what about this sentence?\\\",\\n ... \\\"What did the TER metric user say to the developer?\\\"]\\n >>> references = [[\\\"does this sentence match\\\", \\\"does this sentence match!?!\\\"],\\n ... [\\\"wHaT aBoUt ThIs SeNtEnCe?\\\", \\\"wHaT aBoUt ThIs SeNtEnCe?\\\"],\\n ... [\\\"Your jokes are...\\\", \\\"...TERrible\\\"]]\\n >>> ter = datasets.load_metric(\\\"ter\\\")\\n >>> results = ter.compute(predictions=predictions,\\n ... references=references,\\n ... case_sensitive=True)\\n >>> print(results)\\n {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\\n\\n Example 2:\\n >>> predictions = [\\\"does this sentence match??\\\",\\n ... \\\"what about this sentence?\\\"]\\n >>> references = [[\\\"does this sentence match\\\", \\\"does this sentence match!?!\\\"],\\n ... [\\\"wHaT aBoUt ThIs SeNtEnCe?\\\", \\\"wHaT aBoUt ThIs SeNtEnCe?\\\"]]\\n >>> ter = datasets.load_metric(\\\"ter\\\")\\n >>> results = ter.compute(predictions=predictions,\\n ... references=references,\\n ... case_sensitive=True)\\n >>> print(results)\\n {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\\n\\n Example 3:\\n >>> predictions = [\\\"does this sentence match??\\\",\\n ... \\\"what about this sentence?\\\"]\\n >>> references = [[\\\"does this sentence match\\\", \\\"does this sentence match!?!\\\"],\\n ... [\\\"wHaT aBoUt ThIs SeNtEnCe?\\\", \\\"wHaT aBoUt ThIs SeNtEnCe?\\\"]]\\n >>> ter = datasets.load_metric(\\\"ter\\\")\\n >>> results = ter.compute(predictions=predictions,\\n ... references=references,\\n ... normalized=True,\\n ... case_sensitive=True)\\n >>> print(results)\\n {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\\n\\n Example 4:\\n >>> predictions = [\\\"does this sentence match??\\\",\\n ... \\\"what about this sentence?\\\"]\\n >>> references = [[\\\"does this sentence match\\\", \\\"does this sentence match!?!\\\"],\\n ... [\\\"wHaT aBoUt ThIs SeNtEnCe?\\\", \\\"wHaT aBoUt ThIs SeNtEnCe?\\\"]]\\n >>> ter = datasets.load_metric(\\\"ter\\\")\\n >>> results = ter.compute(predictions=predictions,\\n ... references=references,\\n ... ignore_punct=True,\\n ... case_sensitive=False)\\n >>> print(results)\\n {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\\n\\n Example 5:\\n >>> predictions = [\\\"does this sentence match??\\\",\\n ... \\\"what about this sentence?\\\",\\n ... \\\"What did the TER metric user say to the developer?\\\"]\\n >>> references = [[\\\"does this sentence match\\\", \\\"does this sentence match!?!\\\"],\\n ... [\\\"wHaT aBoUt ThIs SeNtEnCe?\\\", \\\"wHaT aBoUt ThIs SeNtEnCe?\\\"],\\n ... [\\\"Your jokes are...\\\", \\\"...TERrible\\\"]]\\n >>> ter = datasets.load_metric(\\\"ter\\\")\\n >>> results = ter.compute(predictions=predictions,\\n ... references=references,\\n ... ignore_punct=True,\\n ... case_sensitive=False)\\n >>> print(results)\\n {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\\n\"\r\r\r\r\r\r@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)\rclass __magic_name__\t\t\t\t\t\t( datasets.Metric):\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: int ):\r\t\t\t\t\t\t\t\t\t\tif version.parse(scb.__version__ ) < version.parse(\"\"\"1.4.12\"\"\" ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ImportWarning(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\\n\"\"\"\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"You can install it with `pip install \\\"sacrebleu>=1.4.12\\\"`.\"\"\" )\r\t\t\t\t\t\t\t\t\t\treturn datasets.MetricInfo(\r\t\t\t\t\t\t\t\t\t\t description=_DESCRIPTION\t\t\t\t,\t\t\tcitation=_CITATION\t\t\t\t,\t\t\thomepage=\"\"\"http://www.cs.umd.edu/~snover/tercom/\"\"\"\t\t\t\t,\t\t\tinputs_description=_KWARGS_DESCRIPTION\t\t\t\t,\t\t\tfeatures=datasets.Features(\r\t\t\t\t\t\t\t\t\t\t {\r\t\t\t\t\t\t\t\t\t\t \"\"\"predictions\"\"\": datasets.Value(\"\"\"string\"\"\"\t\t\t\t,\t\t\tid=\"\"\"sequence\"\"\" ),\r\t\t\t\t\t\t\t\t\t\t \"\"\"references\"\"\": datasets.Sequence(datasets.Value(\"\"\"string\"\"\"\t\t\t\t,\t\t\tid=\"\"\"sequence\"\"\" )\t\t\t\t,\t\t\tid=\"\"\"references\"\"\" ),\r\t\t\t\t\t\t\t\t\t\t } )\t\t\t\t,\t\t\tcodebase_urls=[\"\"\"https://github.com/mjpost/sacreBLEU#ter\"\"\"]\t\t\t\t,\t\t\treference_urls=[\r\t\t\t\t\t\t\t\t\t\t \"\"\"https://github.com/jhclark/tercom\"\"\",\r\t\t\t\t\t\t\t\t\t\t ]\t\t\t\t,\t\t\t)\r\r\r\r\r\r\r\r\t\t\tdef \tSCREAMING_SNAKE_CASE_ (\tself\t\t\t\t: Any\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Any\t\t\t\t,\t\t\tlowercase_\t\t\t\t: Tuple\t\t\t\t,\t\t\tlowercase_\t\t\t\t: bool = False\t\t\t\t,\t\t\tlowercase_\t\t\t\t: bool = False\t\t\t\t,\t\t\tlowercase_\t\t\t\t: bool = False\t\t\t\t,\t\t\tlowercase_\t\t\t\t: bool = False\t\t\t\t,\t\t\t):\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tint\t\t\t\t\t\t\t\t\t\t= len(references[0] )\r\t\t\t\t\t\t\t\t\t\tif any(len(lowercase_ ) != references_per_prediction for refs in references ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"\"\"Sacrebleu requires the same number of references for each prediction\"\"\" )\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t= [[refs[i] for refs in references] for i in range(lowercase_ )]\r\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= TER(\r\t\t\t\t\t\t\t\t\t\t normalized=lowercase_\t\t\t\t,\t\t\tno_punct=lowercase_\t\t\t\t,\t\t\tasian_support=lowercase_\t\t\t\t,\t\t\tcase_sensitive=lowercase_\t\t\t\t,\t\t\t)\r\t\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t:\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t= sb_ter.corpus_score(lowercase_\t\t\t\t,\t\t\tlowercase_ )\r\r\t\t\t\t\t\t\t\t\t\treturn {\"score\": output.score, \"num_edits\": output.num_edits, \"ref_length\": output.ref_length}\r\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":239,"string":"239"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":241,"cells":{"code":{"kind":"string","value":"\r\n\r\n# tests directory-specific settings - this file is run automatically\r\n# by pytest before any tests are run\r\n\r\nimport sys\r\nimport warnings\r\nfrom os.path import abspath, dirname, join\r\n\r\n\r\n# allow having multiple repository checkouts and not needing to remember to rerun\r\n# 'pip install -e .[dev]' when switching between checkouts and running tests.\r\na__\t\t\t\t=\t\tabspath(join(dirname(dirname(__file__)), '''src'''))\r\nsys.path.insert(1, git_repo_path)\r\n\r\n# silence FutureWarning warnings in tests since often we can't act on them until\r\n# they become normal warnings - i.e. the tests still need to test the current functionality\r\nwarnings.simplefilter(action='''ignore''', category=FutureWarning)\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: Optional[int] ) ->\t\t\t\t\tstr:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tfrom diffusers.utils.testing_utils import pytest_addoption_shared\r\n\r\n\t\t\t\t\tpytest_addoption_shared(__a )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: Optional[int] ) ->\t\t\t\t\tstr:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tfrom diffusers.utils.testing_utils import pytest_terminal_summary_main\r\n\r\n\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\tterminalreporter.config.getoption('''--make-reports''' )\r\n\t\t\t\t\tif make_reports:\r\n\t\t\t\t\t\t\t\t\t\tpytest_terminal_summary_main(__a\t\t,id=__a )\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":355,"string":"355"},"style_context":{"kind":"string","value":"\r\n\r\nfrom typing import Dict\r\n\r\nimport numpy as np\r\n\r\nfrom ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging\r\nfrom .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException\r\n\r\n\r\nif is_tf_available():\r\n\t\t\timport tensorflow as tf\r\n\r\n\t\t\tfrom ..tf_utils import stable_softmax\r\n\r\n\r\nif is_torch_available():\r\n\t\t\timport torch\r\n\r\n\r\na__\t\t\t\t=\t\tlogging.get_logger(__name__)\r\n\r\n@add_end_docstrings(\r\n __lowercase ,\tr\"\\n top_k (`int`, defaults to 5):\\n The number of predictions to return.\\n targets (`str` or `List[str]`, *optional*):\\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\\n token will be used (with a warning, and that might be slower).\\n\\n \" ,\t)\r\nclass UpperCAmelCase_\t\t( __lowercase ):\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t) -> np.ndarray:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.framework == \"tf\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\ttf.where(input_ids == self.tokenizer.mask_token_id\t).numpy()\r\n\t\t\t\t\t\t\t\t\t\t\t\telif self.framework == \"pt\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\ttorch.nonzero(input_ids == self.tokenizer.mask_token_id\t,\t\t\t\t\t\t\tas_tuple=_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('''Unsupported framework'''\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn masked_index\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t) -> np.ndarray:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\tself.get_masked_index(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\tnp.prod(masked_index.shape\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif numel < 1:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise PipelineException(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''fill-mask'''\t,\t\t\t\t\t\t\tself.model.base_model_prefix\t,\t\t\t\t\t\t\tF\"\"\"No mask_token ({self.tokenizer.mask_token}) found on the input\"\"\"\t,\t\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t) -> Optional[int]:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif isinstance(_a\t,\t\t\t\t\t\t\t_a\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor model_input in model_inputs:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself._ensure_exactly_one_mask_token(model_input['''input_ids'''][0]\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor input_ids in model_inputs[\"input_ids\"]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself._ensure_exactly_one_mask_token(_a\t)\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a=None\t,\t\t\t\t\t\t\t**_a\t) -> Dict[str, GenericTensor]:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif return_tensors is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\tself.framework\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\tself.tokenizer(_a\t,\t\t\t\t\t\t\treturn_tensors=_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.ensure_exactly_one_mask_token(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn model_inputs\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t) -> Optional[Any]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tself.model(**_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\tmodel_inputs['''input_ids''']\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn model_outputs\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a=5\t,\t\t\t\t\t\t\t_a=None\t) -> str:\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Cap top_k if there are targets\r\n\t\t\t\t\t\t\t\t\t\t\t\tif target_ids is not None and target_ids.shape[0] < top_k:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\ttarget_ids.shape[0]\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\tmodel_outputs['''input_ids'''][0]\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tmodel_outputs['''logits''']\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.framework == \"tf\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\ttf.where(input_ids == self.tokenizer.mask_token_id\t).numpy()[:, 0]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\toutputs.numpy()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Dict \t\t\t\t=\t\toutputs[0, masked_index, :]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\tstable_softmax(_a\t,\t\t\t\t\t\t\taxis=-1\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif target_ids is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\ttf.gather_nd(tf.squeeze(_a\t,\t\t\t\t\t\t\t0\t)\t,\t\t\t\t\t\t\ttarget_ids.reshape(-1\t,\t\t\t\t\t\t\t1\t)\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\ttf.expand_dims(_a\t,\t\t\t\t\t\t\t0\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\ttf.math.top_k(_a\t,\t\t\t\t\t\t\tk=_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t, _a : Optional[Any] \t\t\t\t=\t\ttopk.values.numpy(), topk.indices.numpy()\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[Any] \t\t\t\t=\t\ttorch.nonzero(input_ids == self.tokenizer.mask_token_id\t,\t\t\t\t\t\t\tas_tuple=_a\t).squeeze(-1\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Fill mask pipeline supports only one ${mask_token} per sample\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\toutputs[0, masked_index, :]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tlogits.softmax(dim=-1\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif target_ids is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tprobs[..., target_ids]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t, _a : Optional[Any] \t\t\t\t=\t\tprobs.topk(_a\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Dict \t\t\t\t=\t\t[]\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tvalues.shape[0] == 1\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor i, (_values, _predictions) in enumerate(zip(values.tolist()\t,\t\t\t\t\t\t\tpredictions.tolist()\t)\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[Any] \t\t\t\t=\t\t[]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor v, p in zip(_values\t,\t\t\t\t\t\t\t_predictions\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Copy is important since we're going to modify this array in place\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\tinput_ids.numpy().copy()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif target_ids is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\ttarget_ids[p].tolist()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tp\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Filter padding out:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\ttokens[np.where(tokens != self.tokenizer.pad_token_id\t)]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Originally we skip special tokens to give readable output.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# For multi masks though, the other [MASK] would be removed otherwise\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# making the output look odd, so we add them back\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tself.tokenizer.decode(_a\t,\t\t\t\t\t\t\tskip_special_tokens=_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\t{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]\t), '''sequence''': sequence}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trow.append(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tresult.append(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif single_mask:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn result[0]\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn result\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a=None\t) -> Dict:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif isinstance(_a\t,\t\t\t\t\t\t\t_a\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\t[targets]\r\n\t\t\t\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\tself.tokenizer.get_vocab()\r\n\t\t\t\t\t\t\t\t\t\t\t\texcept Exception:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\t{}\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\t[]\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor target in targets:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tvocab.get(_a\t,\t\t\t\t\t\t\t_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif id_ is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\tself.tokenizer(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _a\t,\t\t\t\t\t\t\tadd_special_tokens=_a\t,\t\t\t\t\t\t\treturn_attention_mask=_a\t,\t\t\t\t\t\t\treturn_token_type_ids=_a\t,\t\t\t\t\t\t\tmax_length=1\t,\t\t\t\t\t\t\ttruncation=_a\t,\t\t\t\t\t\t\t)['''input_ids''']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif len(_a\t) == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.warning(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t F\"\"\"The specified target token `{target}` does not exist in the model vocabulary. \"\"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''We cannot replace it with anything meaningful, ignoring it'''\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\tinput_ids[0]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# XXX: If users encounter this pass\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# it becomes pretty slow, so let's make sure\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# The warning enables them to fix the input to\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# get faster performance.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.warning(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t F\"\"\"The specified target token `{target}` does not exist in the model vocabulary. \"\"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t F\"\"\"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_\t)}`.\"\"\"\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttarget_ids.append(id_\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tlist(set(_a\t)\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif len(_a\t) == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('''At least one target must be provided when passed.'''\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\tnp.array(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn target_ids\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a=None\t,\t\t\t\t\t\t\t_a=None\t) -> Tuple:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\t{}\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif targets is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tself.get_target_ids(_a\t,\t\t\t\t\t\t\t_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[Any] \t\t\t\t=\t\ttarget_ids\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif top_k is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\ttop_k\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.tokenizer.mask_token_id is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise PipelineException(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''fill-mask'''\t,\t\t\t\t\t\t\tself.model.base_model_prefix\t,\t\t\t\t\t\t\t'''The tokenizer does not define a `mask_token`.'''\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn {}, {}, postprocess_params\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __call__( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t*_a\t,\t\t\t\t\t\t\t**_a\t) -> int:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[Any] \t\t\t\t=\t\tsuper().__call__(_a\t,\t\t\t\t\t\t\t**_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif isinstance(_a\t,\t\t\t\t\t\t\t_a\t) and len(_a\t) == 1:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn outputs[0]\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn outputs\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":15,"string":"15"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":242,"cells":{"code":{"kind":"string","value":"\nimport os\nfrom shutil import copyfile\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport sentencepiece as spm\n\nfrom ...tokenization_utils import AddedToken, PreTrainedTokenizer\nfrom ...utils import logging\n\n\nUpperCAmelCase__\t\t: Dict \t\t\t= logging.get_logger(__name__)\n\nUpperCAmelCase__\t\t: Optional[int] \t\t\t= '▁'\n\nUpperCAmelCase__\t\t: List[Any] \t\t\t= {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'}\n\nUpperCAmelCase__\t\t: Any \t\t\t= {\n 'vocab_file': {\n 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model',\n },\n 'monolingual_vocab_file': {\n 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt',\n },\n}\n\nUpperCAmelCase__\t\t: Tuple \t\t\t= {'vinai/bartpho-syllable': 1024}\n\n\n\n\n\n\nclass UpperCAmelCase (\t\t\t\t\t\tSCREAMING_SNAKE_CASE__ ):\n\n\n\n\n\n '''simple docstring'''\n __UpperCamelCase\t\t: Optional[int] \t\t\t\t= VOCAB_FILES_NAMES\n __UpperCamelCase\t\t: List[str] \t\t\t\t= PRETRAINED_VOCAB_FILES_MAP\n __UpperCamelCase\t\t: Optional[int] \t\t\t\t= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n __UpperCamelCase\t\t: List[Any] \t\t\t\t= ['''input_ids''', '''attention_mask''']\n\n\n def __init__(\t\t\t\t\tself :\t\t\t\t\t\t\tDict\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[str]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tAny\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int]=\"\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tTuple=\"\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tUnion[str, Any]=\"\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[str]=\"\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int]=\"\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int]=\"\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int]=\"\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[Dict[str, Any]] = None\t\t\t,\t\t\t**lowerCAmelCase_ :\t\t\t\t\t\t\tOptional[Any]\t\t\t,\t\t\t):\n\n \"\"\"simple docstring\"\"\"\n # Mask token behave like a normal word, i.e. include the space before it\n _A: Union[str, Any]\t\t\t\t\t= AddedToken(lowerCAmelCase_\t\t\t,\t\t\tlstrip=lowerCAmelCase_\t\t\t,\t\t\trstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ ) else mask_token\n\n _A: Optional[int]\t\t\t\t\t= {} if sp_model_kwargs is None else sp_model_kwargs\n\n super().__init__(\n bos_token=lowerCAmelCase_\t\t\t,\t\t\teos_token=lowerCAmelCase_\t\t\t,\t\t\tunk_token=lowerCAmelCase_\t\t\t,\t\t\tsep_token=lowerCAmelCase_\t\t\t,\t\t\tcls_token=lowerCAmelCase_\t\t\t,\t\t\tpad_token=lowerCAmelCase_\t\t\t,\t\t\tmask_token=lowerCAmelCase_\t\t\t,\t\t\tsp_model_kwargs=self.sp_model_kwargs\t\t\t,\t\t\t**lowerCAmelCase_\t\t\t,\t\t\t)\n\n _A: int\t\t\t\t\t= vocab_file\n _A: Optional[Any]\t\t\t\t\t= monolingual_vocab_file\n _A: List[str]\t\t\t\t\t= spm.SentencePieceProcessor(**self.sp_model_kwargs )\n self.sp_model.Load(str(lowerCAmelCase_ ) )\n\n # Load the reduced vocab\n\n # Keep order of special tokens for backward compatibility\n _A: Dict\t\t\t\t\t= {}\n _A: Dict\t\t\t\t\t= 0\n for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:\n if str(lowerCAmelCase_ ) not in self.fairseq_tokens_to_ids:\n _A: str\t\t\t\t\t= cnt\n cnt += 1\n with open(lowerCAmelCase_\t\t\t,\t\t\t'''r'''\t\t\t,\t\t\tencoding='''utf-8''' ) as f:\n for line in f.readlines():\n _A: Optional[Any]\t\t\t\t\t= line.strip().split()[0]\n _A: Union[str, Any]\t\t\t\t\t= len(self.fairseq_tokens_to_ids )\n if str(lowerCAmelCase_ ) not in self.fairseq_tokens_to_ids:\n _A: Optional[int]\t\t\t\t\t= len(self.fairseq_tokens_to_ids )\n\n _A: Optional[Any]\t\t\t\t\t= {v: k for k, v in self.fairseq_tokens_to_ids.items()}\n\n\n def __getstate__(\t\t\t\t\tself :\t\t\t\t\t\t\tList[str] ):\n\n \"\"\"simple docstring\"\"\"\n _A: Optional[int]\t\t\t\t\t= self.__dict__.copy()\n _A: str\t\t\t\t\t= None\n _A: List[str]\t\t\t\t\t= self.sp_model.serialized_model_proto()\n return state\n\n\n def __setstate__(\t\t\t\t\tself :\t\t\t\t\t\t\tUnion[str, Any]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[Any] ):\n\n \"\"\"simple docstring\"\"\"\n _A: Dict\t\t\t\t\t= d\n\n # for backward compatibility\n if not hasattr(self\t\t\t,\t\t\t'''sp_model_kwargs''' ):\n _A: str\t\t\t\t\t= {}\n\n _A: str\t\t\t\t\t= spm.SentencePieceProcessor(**self.sp_model_kwargs )\n self.sp_model.LoadFromSerializedProto(self.sp_model_proto )\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tstr\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[int]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[List[int]] = None ):\n\n \"\"\"simple docstring\"\"\"\n\n if token_ids_a is None:\n return [self.cls_token_id] + token_ids_a + [self.sep_token_id]\n _A: Union[str, Any]\t\t\t\t\t= [self.cls_token_id]\n _A: int\t\t\t\t\t= [self.sep_token_id]\n return cls + token_ids_a + sep + sep + token_ids_a + sep\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tUnion[str, Any]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[int]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[List[int]] = None\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tbool = False ):\n\n \"\"\"simple docstring\"\"\"\n\n if already_has_special_tokens:\n return super().get_special_tokens_mask(\n token_ids_a=lowerCAmelCase_\t\t\t,\t\t\ttoken_ids_a=lowerCAmelCase_\t\t\t,\t\t\talready_has_special_tokens=lowerCAmelCase_ )\n\n if token_ids_a is None:\n return [1] + ([0] * len(lowerCAmelCase_ )) + [1]\n return [1] + ([0] * len(lowerCAmelCase_ )) + [1, 1] + ([0] * len(lowerCAmelCase_ )) + [1]\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tTuple\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[int]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[List[int]] = None ):\n\n \"\"\"simple docstring\"\"\"\n _A: Optional[int]\t\t\t\t\t= [self.sep_token_id]\n _A: Union[str, Any]\t\t\t\t\t= [self.cls_token_id]\n\n if token_ids_a is None:\n return len(cls + token_ids_a + sep ) * [0]\n return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]\n\n\n @property\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tUnion[str, Any] ):\n\n \"\"\"simple docstring\"\"\"\n return len(self.fairseq_ids_to_tokens )\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tTuple ):\n\n \"\"\"simple docstring\"\"\"\n _A: Any\t\t\t\t\t= {self.convert_ids_to_tokens(lowerCAmelCase_ ): i for i in range(self.vocab_size )}\n vocab.update(self.added_tokens_encoder )\n return vocab\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tList[str]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tstr ):\n\n \"\"\"simple docstring\"\"\"\n return self.sp_model.encode(lowerCAmelCase_\t\t\t,\t\t\tout_type=lowerCAmelCase_ )\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tOptional[int]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tint ):\n\n \"\"\"simple docstring\"\"\"\n if token in self.fairseq_tokens_to_ids:\n return self.fairseq_tokens_to_ids[token]\n else:\n return self.unk_token_id\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tint\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tAny ):\n\n \"\"\"simple docstring\"\"\"\n return self.fairseq_ids_to_tokens[index]\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tint\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int] ):\n\n \"\"\"simple docstring\"\"\"\n _A: Optional[Any]\t\t\t\t\t= ''''''.join(lowerCAmelCase_ ).replace(lowerCAmelCase_\t\t\t,\t\t\t''' ''' ).strip()\n return out_string\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tTuple\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tstr\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[str] = None ):\n\n \"\"\"simple docstring\"\"\"\n if not os.path.isdir(lowerCAmelCase_ ):\n logger.error(F\"\"\"Vocabulary path ({save_directory}) should be a directory\"\"\" )\n return\n _A: Any\t\t\t\t\t= os.path.join(\n lowerCAmelCase_\t\t\t,\t\t\t(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )\n _A: Optional[int]\t\t\t\t\t= os.path.join(\n lowerCAmelCase_\t\t\t,\t\t\t(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''monolingual_vocab_file''']\t\t\t,\t\t\t)\n\n if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase_ ) and os.path.isfile(self.vocab_file ):\n copyfile(self.vocab_file\t\t\t,\t\t\tlowerCAmelCase_ )\n elif not os.path.isfile(self.vocab_file ):\n with open(lowerCAmelCase_\t\t\t,\t\t\t'''wb''' ) as fi:\n _A: Optional[int]\t\t\t\t\t= self.sp_model.serialized_model_proto()\n fi.write(lowerCAmelCase_ )\n\n if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath(\n lowerCAmelCase_ ) and os.path.isfile(self.monolingual_vocab_file ):\n copyfile(self.monolingual_vocab_file\t\t\t,\t\t\tlowerCAmelCase_ )\n elif not os.path.isfile(self.monolingual_vocab_file ):\n with open(lowerCAmelCase_\t\t\t,\t\t\t'''w'''\t\t\t,\t\t\tencoding='''utf-8''' ) as fp:\n for token in self.fairseq_tokens_to_ids:\n if token not in self.all_special_tokens:\n fp.write(F\"\"\"{str(lowerCAmelCase_ )} \\n\"\"\" )\n\n return out_vocab_file, out_monolingual_vocab_file\n\n\n\n"},"code_codestyle":{"kind":"number","value":121,"string":"121"},"style_context":{"kind":"string","value":"\nfrom typing import List, Optional, Union\n\nimport numpy as np\nimport PIL\nimport torch\nfrom PIL import Image\n\nfrom ...models import UNetaDConditionModel, VQModel\nfrom ...pipelines import DiffusionPipeline\nfrom ...pipelines.pipeline_utils import ImagePipelineOutput\nfrom ...schedulers import DDPMScheduler\nfrom ...utils import (\n is_accelerate_available,\n is_accelerate_version,\n logging,\n randn_tensor,\n replace_example_docstring,\n)\n\n\nUpperCAmelCase__\t\t: Optional[int] \t\t\t= logging.get_logger(__name__) # pylint: disable=invalid-name\n\nUpperCAmelCase__\t\t: Dict \t\t\t= '\\n Examples:\\n ```py\\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\\n >>> from diffusers.utils import load_image\\n >>> import torch\\n\\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\\n ... )\\n >>> pipe_prior.to(\"cuda\")\\n\\n >>> prompt = \"A red cartoon frog, 4k\"\\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\\n\\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\\n ... )\\n >>> pipe.to(\"cuda\")\\n\\n >>> init_image = load_image(\\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\\n ... \"/kandinsky/frog.png\"\\n ... )\\n\\n >>> image = pipe(\\n ... image=init_image,\\n ... image_embeds=image_emb,\\n ... negative_image_embeds=zero_image_emb,\\n ... height=768,\\n ... width=768,\\n ... num_inference_steps=100,\\n ... strength=0.2,\\n ... ).images\\n\\n >>> image[0].save(\"red_frog.png\")\\n ```\\n'\n\n\n\n\n\n\ndef lowerCamelCase__\t\t\t\t\t\t\t(\t\t\t\t\ta\t\t,\t\ta\t\t,\t\ta=8 ) -> List[Any]:\n _A: int\t\t\t\t\t= height // scale_factor**2\n if height % scale_factor**2 != 0:\n new_height += 1\n _A: str\t\t\t\t\t= width // scale_factor**2\n if width % scale_factor**2 != 0:\n new_width += 1\n return new_height * scale_factor, new_width * scale_factor\n\n\n\n\n\n\ndef lowerCamelCase__\t\t\t\t\t\t\t(\t\t\t\t\ta\t\t,\t\ta=5_12\t\t,\t\ta=5_12 ) -> Dict:\n _A: Union[str, Any]\t\t\t\t\t= pil_image.resize((w, h)\t\t,\t\tresample=Image.BICUBIC\t\t,\t\treducing_gap=1 )\n _A: Tuple\t\t\t\t\t= np.array(pil_image.convert('''RGB''' ) )\n _A: List[str]\t\t\t\t\t= arr.astype(np.floataa ) / 127.5 - 1\n _A: Tuple\t\t\t\t\t= np.transpose(a\t\t,\t\t[2, 0, 1] )\n _A: Any\t\t\t\t\t= torch.from_numpy(a ).unsqueeze(0 )\n return image\n\n\n\n\n\n\nclass UpperCAmelCase (\t\t\t\t\t\tSCREAMING_SNAKE_CASE__ ):\n\n\n\n\n\n '''simple docstring'''\n\n\n def __init__(\t\t\t\t\tself :\t\t\t\t\t\t\tint\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tUNetaDConditionModel\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tDDPMScheduler\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tVQModel\t\t\t,\t\t\t):\n\n \"\"\"simple docstring\"\"\"\n super().__init__()\n\n self.register_modules(\n unet=lowerCAmelCase_\t\t\t,\t\t\tscheduler=lowerCAmelCase_\t\t\t,\t\t\tmovq=lowerCAmelCase_\t\t\t,\t\t\t)\n _A: List[Any]\t\t\t\t\t= 2 ** (len(self.movq.config.block_out_channels ) - 1)\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tList[str]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tUnion[str, Any]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[Any]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tUnion[str, Any] ):\n\n \"\"\"simple docstring\"\"\"\n # get the original timestep using init_timestep\n _A: Union[str, Any]\t\t\t\t\t= min(int(num_inference_steps * strength )\t\t\t,\t\t\tlowerCAmelCase_ )\n\n _A: str\t\t\t\t\t= max(num_inference_steps - init_timestep\t\t\t,\t\t\t0 )\n _A: str\t\t\t\t\t= self.scheduler.timesteps[t_start:]\n\n return timesteps, num_inference_steps - t_start\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tList[str]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[str]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tstr\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[Any]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tList[Any]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tTuple\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int]=None ):\n\n \"\"\"simple docstring\"\"\"\n if not isinstance(lowerCAmelCase_\t\t\t,\t\t\t(torch.Tensor, PIL.Image.Image, list) ):\n raise ValueError(\n F\"\"\"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowerCAmelCase_ )}\"\"\" )\n\n _A: Optional[int]\t\t\t\t\t= image.to(device=lowerCAmelCase_\t\t\t,\t\t\tdtype=lowerCAmelCase_ )\n\n _A: Union[str, Any]\t\t\t\t\t= batch_size * num_images_per_prompt\n\n if image.shape[1] == 4:\n _A: Optional[int]\t\t\t\t\t= image\n\n else:\n if isinstance(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ ) and len(lowerCAmelCase_ ) != batch_size:\n raise ValueError(\n F\"\"\"You have passed a list of generators of length {len(lowerCAmelCase_ )}, but requested an effective batch\"\"\"\n F\"\"\" size of {batch_size}. Make sure the batch size matches the length of the generators.\"\"\" )\n\n elif isinstance(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ ):\n _A: List[Any]\t\t\t\t\t= [\n self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(lowerCAmelCase_ )\n ]\n _A: Optional[Any]\t\t\t\t\t= torch.cat(lowerCAmelCase_\t\t\t,\t\t\tdim=0 )\n else:\n _A: Optional[int]\t\t\t\t\t= self.movq.encode(lowerCAmelCase_ ).latent_dist.sample(lowerCAmelCase_ )\n\n _A: int\t\t\t\t\t= self.movq.config.scaling_factor * init_latents\n\n _A: Optional[Any]\t\t\t\t\t= torch.cat([init_latents]\t\t\t,\t\t\tdim=0 )\n\n _A: Any\t\t\t\t\t= init_latents.shape\n _A: Optional[Any]\t\t\t\t\t= randn_tensor(lowerCAmelCase_\t\t\t,\t\t\tgenerator=lowerCAmelCase_\t\t\t,\t\t\tdevice=lowerCAmelCase_\t\t\t,\t\t\tdtype=lowerCAmelCase_ )\n\n # get latents\n _A: Union[str, Any]\t\t\t\t\t= self.scheduler.add_noise(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ )\n\n _A: List[str]\t\t\t\t\t= init_latents\n\n return latents\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tOptional[int]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[int]=0 ):\n\n \"\"\"simple docstring\"\"\"\n if is_accelerate_available():\n from accelerate import cpu_offload\n else:\n raise ImportError('''Please install accelerate via `pip install accelerate`''' )\n\n _A: Any\t\t\t\t\t= torch.device(F\"\"\"cuda:{gpu_id}\"\"\" )\n\n _A: int\t\t\t\t\t= [\n self.unet,\n self.movq,\n ]\n for cpu_offloaded_model in models:\n if cpu_offloaded_model is not None:\n cpu_offload(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ )\n\n\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tAny\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tAny=0 ):\n\n \"\"\"simple docstring\"\"\"\n if is_accelerate_available() and is_accelerate_version('''>='''\t\t\t,\t\t\t'''0.17.0.dev0''' ):\n from accelerate import cpu_offload_with_hook\n else:\n raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' )\n\n _A: Any\t\t\t\t\t= torch.device(F\"\"\"cuda:{gpu_id}\"\"\" )\n\n if self.device.type != \"cpu\":\n self.to('''cpu'''\t\t\t,\t\t\tsilence_dtype_warnings=lowerCAmelCase_ )\n torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)\n\n _A: int\t\t\t\t\t= None\n for cpu_offloaded_model in [self.unet, self.movq]:\n _A\t\t\t, _A: List[Any]\t\t\t\t\t= cpu_offload_with_hook(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tprev_module_hook=lowerCAmelCase_ )\n\n # We'll offload the last model manually.\n _A: Tuple\t\t\t\t\t= hook\n\n\n @property\n # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device\n def __magic_name__\t\t\t\t(\t\t\t\t\tself :\t\t\t\t\t\t\tList[Any] ):\n\n \"\"\"simple docstring\"\"\"\n if not hasattr(self.unet\t\t\t,\t\t\t'''_hf_hook''' ):\n return self.device\n for module in self.unet.modules():\n if (\n hasattr(lowerCAmelCase_\t\t\t,\t\t\t'''_hf_hook''' )\n and hasattr(module._hf_hook\t\t\t,\t\t\t'''execution_device''' )\n and module._hf_hook.execution_device is not None\n ):\n return torch.device(module._hf_hook.execution_device )\n return self.device\n\n\n @torch.no_grad()\n @replace_example_docstring(lowerCAmelCase_ )\n def __call__(\t\t\t\t\tself :\t\t\t\t\t\t\tOptional[Any]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tUnion[torch.FloatTensor, List[torch.FloatTensor]]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tUnion[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tUnion[torch.FloatTensor, List[torch.FloatTensor]]\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tint = 5_1_2\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tint = 5_1_2\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tint = 1_0_0\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tfloat = 4.0\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tfloat = 0.3\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tint = 1\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[Union[torch.Generator, List[torch.Generator]]] = None\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tOptional[str] = \"pil\"\t\t\t,\t\t\tlowerCAmelCase_ :\t\t\t\t\t\t\tbool = True\t\t\t,\t\t\t):\n\n \"\"\"simple docstring\"\"\"\n _A: Any\t\t\t\t\t= self._execution_device\n\n _A: Any\t\t\t\t\t= guidance_scale > 1.0\n\n if isinstance(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ ):\n _A: Any\t\t\t\t\t= torch.cat(lowerCAmelCase_\t\t\t,\t\t\tdim=0 )\n _A: int\t\t\t\t\t= image_embeds.shape[0]\n if isinstance(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ ):\n _A: Dict\t\t\t\t\t= torch.cat(lowerCAmelCase_\t\t\t,\t\t\tdim=0 )\n\n if do_classifier_free_guidance:\n _A: Any\t\t\t\t\t= image_embeds.repeat_interleave(lowerCAmelCase_\t\t\t,\t\t\tdim=0 )\n _A: str\t\t\t\t\t= negative_image_embeds.repeat_interleave(lowerCAmelCase_\t\t\t,\t\t\tdim=0 )\n\n _A: Dict\t\t\t\t\t= torch.cat([negative_image_embeds, image_embeds]\t\t\t,\t\t\tdim=0 ).to(dtype=self.unet.dtype\t\t\t,\t\t\tdevice=lowerCAmelCase_ )\n\n if not isinstance(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ ):\n _A: List[str]\t\t\t\t\t= [image]\n if not all(isinstance(lowerCAmelCase_\t\t\t,\t\t\t(PIL.Image.Image, torch.Tensor) ) for i in image ):\n raise ValueError(\n F\"\"\"Input is in incorrect format: {[type(lowerCAmelCase_ ) for i in image]}. Currently, we only support PIL image and pytorch tensor\"\"\" )\n\n _A: List[str]\t\t\t\t\t= torch.cat([prepare_image(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ ) for i in image]\t\t\t,\t\t\tdim=0 )\n _A: Tuple\t\t\t\t\t= image.to(dtype=image_embeds.dtype\t\t\t,\t\t\tdevice=lowerCAmelCase_ )\n\n _A: Optional[Any]\t\t\t\t\t= self.movq.encode(lowerCAmelCase_ )['''latents''']\n _A: Optional[int]\t\t\t\t\t= latents.repeat_interleave(lowerCAmelCase_\t\t\t,\t\t\tdim=0 )\n self.scheduler.set_timesteps(lowerCAmelCase_\t\t\t,\t\t\tdevice=lowerCAmelCase_ )\n _A\t\t\t, _A: List[Any]\t\t\t\t\t= self.get_timesteps(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ )\n _A: Dict\t\t\t\t\t= timesteps[:1].repeat(batch_size * num_images_per_prompt )\n _A\t\t\t, _A: Optional[int]\t\t\t\t\t= downscale_height_and_width(lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tself.movq_scale_factor )\n _A: Any\t\t\t\t\t= self.prepare_latents(\n lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\timage_embeds.dtype\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_ )\n for i, t in enumerate(self.progress_bar(lowerCAmelCase_ ) ):\n # expand the latents if we are doing classifier free guidance\n _A: Dict\t\t\t\t\t= torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents\n\n _A: str\t\t\t\t\t= {'''image_embeds''': image_embeds}\n _A: Optional[int]\t\t\t\t\t= self.unet(\n sample=lowerCAmelCase_\t\t\t,\t\t\ttimestep=lowerCAmelCase_\t\t\t,\t\t\tencoder_hidden_states=lowerCAmelCase_\t\t\t,\t\t\tadded_cond_kwargs=lowerCAmelCase_\t\t\t,\t\t\treturn_dict=lowerCAmelCase_\t\t\t,\t\t\t)[0]\n\n if do_classifier_free_guidance:\n _A\t\t\t, _A: str\t\t\t\t\t= noise_pred.split(latents.shape[1]\t\t\t,\t\t\tdim=1 )\n _A\t\t\t, _A: int\t\t\t\t\t= noise_pred.chunk(2 )\n _A\t\t\t, _A: int\t\t\t\t\t= variance_pred.chunk(2 )\n _A: Dict\t\t\t\t\t= noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)\n _A: List[str]\t\t\t\t\t= torch.cat([noise_pred, variance_pred_text]\t\t\t,\t\t\tdim=1 )\n\n if not (\n hasattr(self.scheduler.config\t\t\t,\t\t\t'''variance_type''' )\n and self.scheduler.config.variance_type in [\"learned\", \"learned_range\"]\n ):\n _A\t\t\t, _A: Optional[Any]\t\t\t\t\t= noise_pred.split(latents.shape[1]\t\t\t,\t\t\tdim=1 )\n\n # compute the previous noisy sample x_t -> x_t-1\n _A: Any\t\t\t\t\t= self.scheduler.step(\n lowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tlowerCAmelCase_\t\t\t,\t\t\tgenerator=lowerCAmelCase_\t\t\t,\t\t\t)[0]\n\n # post-processing\n _A: Tuple\t\t\t\t\t= self.movq.decode(lowerCAmelCase_\t\t\t,\t\t\tforce_not_quantize=lowerCAmelCase_ )['''sample''']\n\n if output_type not in [\"pt\", \"np\", \"pil\"]:\n raise ValueError(F\"\"\"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}\"\"\" )\n\n if output_type in [\"np\", \"pil\"]:\n _A: int\t\t\t\t\t= image * 0.5 + 0.5\n _A: Any\t\t\t\t\t= image.clamp(0\t\t\t,\t\t\t1 )\n _A: Any\t\t\t\t\t= image.cpu().permute(0\t\t\t,\t\t\t2\t\t\t,\t\t\t3\t\t\t,\t\t\t1 ).float().numpy()\n\n if output_type == \"pil\":\n _A: Union[str, Any]\t\t\t\t\t= self.numpy_to_pil(lowerCAmelCase_ )\n\n if not return_dict:\n return (image,)\n\n return ImagePipelineOutput(images=lowerCAmelCase_ )\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":121,"string":"121"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":243,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\nimport os\r\nfrom collections.abc import Iterator\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef snake_case( __magic_name__ = \".\" )\t\t\t->\t\t\t\t\t\t\tIterator[str]:\r\n\r\n\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n for dir_path, dir_names, filenames in os.walk(__magic_name__ ):\r\n lowercase : Tuple =\t\t\t[d for d in dir_names if d != '''scripts''' and d[0] not in '''._''']\r\n for filename in filenames:\r\n if filename == \"__init__.py\":\r\n continue\r\n if os.path.splitext(__magic_name__ )[1] in (\".py\", \".ipynb\"):\r\n yield os.path.join(__magic_name__\t\t\t,\t\t__magic_name__ ).lstrip('''./''' )\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef snake_case( __magic_name__ )\t\t\t->\t\t\t\t\t\t\tDict:\r\n\r\n\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n return F\"\"\"{i * ' '}*\"\"\" if i else \"\\n##\"\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef snake_case( __magic_name__\t\t\t,\t\t__magic_name__ )\t\t\t->\t\t\t\t\t\t\tstr:\r\n\r\n\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n lowercase : Dict =\t\t\told_path.split(os.sep )\r\n for i, new_part in enumerate(new_path.split(os.sep ) ):\r\n if (i + 1 > len(__magic_name__ ) or old_parts[i] != new_part) and new_part:\r\n print(F\"\"\"{md_prefix(__magic_name__ )} {new_part.replace('_'\t\t\t,\t\t' ' ).title()}\"\"\" )\r\n return new_path\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef snake_case( __magic_name__ = \".\" )\t\t\t->\t\t\t\t\t\t\tNone:\r\n\r\n\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n lowercase : str =\t\t\t''''''\r\n for filepath in sorted(good_file_paths(__magic_name__ ) ):\r\n lowercase ,\tlowercase : Optional[int] =\t\t\tos.path.split(__magic_name__ )\r\n if filepath != old_path:\r\n lowercase : str =\t\t\tprint_path(__magic_name__\t\t\t,\t\t__magic_name__ )\r\n lowercase : Optional[int] =\t\t\t(filepath.count(os.sep ) + 1) if filepath else 0\r\n lowercase : Optional[Any] =\t\t\tF\"\"\"{filepath}/{filename}\"\"\".replace(''' '''\t\t\t,\t\t'''%20''' )\r\n lowercase : List[str] =\t\t\tos.path.splitext(filename.replace('''_'''\t\t\t,\t\t''' ''' ).title() )[0]\r\n print(F\"\"\"{md_prefix(__magic_name__ )} [{filename}]({url})\"\"\" )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print_directory_md('.')"},"code_codestyle":{"kind":"number","value":116,"string":"116"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\nfrom sklearn.metrics import mean_squared_error\r\n\r\nimport datasets\r\n\r\n\r\nlowerCAmelCase_\t\t\t\t\t\t=\t\t\t'\\\\n@article{scikit-learn,\\n title={Scikit-learn: Machine Learning in {P}ython},\\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\\n journal={Journal of Machine Learning Research},\\n volume={12},\\n pages={2825--2830},\\n year={2011}\\n}\\n'\r\n\r\nlowerCAmelCase_\t\t\t\t\t\t=\t\t\t'\\\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\\nand actual values.\\n'\r\n\r\n\r\nlowerCAmelCase_\t\t\t\t\t\t=\t\t\t'\\nArgs:\\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\\n Estimated target values.\\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\\n Ground truth (correct) target values.\\n sample_weight: array-like of shape (n_samples,), default=None\\n Sample weights.\\n multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\\n\\n \"raw_values\" : Returns a full set of errors in case of multioutput input.\\n\\n \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\\n\\n squared : bool, default=True\\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\\n\\nReturns:\\n mse : mean squared error.\\nExamples:\\n\\n >>> mse_metric = datasets.load_metric(\"mse\")\\n >>> predictions = [2.5, 0.0, 2, 8]\\n >>> references = [3, -0.5, 2, 7]\\n >>> results = mse_metric.compute(predictions=predictions, references=references)\\n >>> print(results)\\n {\\'mse\\': 0.375}\\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\\n >>> print(rmse_result)\\n {\\'mse\\': 0.6123724356957945}\\n\\n If you\\'re using multi-dimensional lists, then set the config as follows :\\n\\n >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\\n >>> references = [[0, 2], [-1, 2], [8, -5]]\\n >>> results = mse_metric.compute(predictions=predictions, references=references)\\n >>> print(results)\\n {\\'mse\\': 0.7083333333333334}\\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\\'raw_values\\')\\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\\n {\\'mse\\': array([0.41666667, 1. ])}\\n'\r\n@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION\t\t\t\t)\r\nclass \t\t\t\t\t\t_A ( datasets.Metric\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __a ( self\t\t: List[Any]\t\t\t\t)\t\t-> Optional[Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n return datasets.MetricInfo(\r\n description=_DESCRIPTION\t\t\t\t,\t\t\t\t\t\tcitation=_CITATION\t\t\t\t,\t\t\t\t\t\tinputs_description=_KWARGS_DESCRIPTION\t\t\t\t,\t\t\t\t\t\tfeatures=datasets.Features(self._get_feature_types()\t\t\t\t)\t\t\t\t,\t\t\t\t\t\treference_urls=[\r\n '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html'''\r\n ]\t\t\t\t,\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __a ( self\t\t: List[Any]\t\t\t\t)\t\t-> int:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n if self.config_name == \"multilist\":\r\n return {\r\n \"predictions\": datasets.Sequence(datasets.Value('''float'''\t\t\t\t)\t\t\t\t),\r\n \"references\": datasets.Sequence(datasets.Value('''float'''\t\t\t\t)\t\t\t\t),\r\n }\r\n else:\r\n return {\r\n \"predictions\": datasets.Value('''float'''\t\t\t\t),\r\n \"references\": datasets.Value('''float'''\t\t\t\t),\r\n }\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __a ( self\t\t: Any\t\t\t\t,\t\t\t\t\t\t_A\t\t: Dict\t\t\t\t,\t\t\t\t\t\t_A\t\t: Any\t\t\t\t,\t\t\t\t\t\t_A\t\t: Any=None\t\t\t\t,\t\t\t\t\t\t_A\t\t: Any=\"uniform_average\"\t\t\t\t,\t\t\t\t\t\t_A\t\t: Optional[Any]=True\t\t\t\t)\t\t-> Dict:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n lowercase : Any =\t\t\tmean_squared_error(\r\n _A\t\t\t\t,\t\t\t\t\t\t_A\t\t\t\t,\t\t\t\t\t\tsample_weight=_A\t\t\t\t,\t\t\t\t\t\tmultioutput=_A\t\t\t\t,\t\t\t\t\t\tsquared=_A\t\t\t\t)\r\n\r\n return {\"mse\": mse}"},"style_context_codestyle":{"kind":"number","value":116,"string":"116"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":244,"cells":{"code":{"kind":"string","value":"\n\n\n'''simple docstring'''\n\n\n\nfrom __future__ import annotations\n\nimport numpy as np\nfrom numpy import floataa\nfrom numpy.typing import NDArray\n\n\n\ndef \t\t\tUpperCAmelCase__\t\t\t\t\t(\tUpperCAmelCase_ :\t\t\t\tNDArray[floataa] , UpperCAmelCase_ :\t\t\t\tNDArray[floataa] , UpperCAmelCase_ :\t\t\t\tlist[int] , UpperCAmelCase_ :\t\t\t\tint , ) ->\t\tlist[float]:\n __lowerCamelCase\t\t\t\t, __lowerCamelCase :\tOptional[int]\t\t\t\t\t\t\t\t=\t\tcoefficient_matrix.shape\n __lowerCamelCase\t\t\t\t, __lowerCamelCase :\tDict\t\t\t\t\t\t\t\t=\t\tconstant_matrix.shape\n\n if rowsa != colsa:\n __lowerCamelCase :\tUnion[str, Any]\t\t\t\t\t\t\t\t=\t\tF'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}'\n raise ValueError(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n if colsa != 1:\n __lowerCamelCase :\tint\t\t\t\t\t\t\t\t=\t\tF'Constant matrix must be nx1 but received {rowsa}x{colsa}'\n raise ValueError(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n if rowsa != rowsa:\n __lowerCamelCase :\tTuple\t\t\t\t\t\t\t\t=\t\t(\n 'Coefficient and constant matrices dimensions must be nxn and nx1 but '\n F'received {rowsa}x{colsa} and {rowsa}x{colsa}'\n )\n raise ValueError(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n if len(UpperCAmelCase_\t\t\t\t\t\t\t) != rowsa:\n __lowerCamelCase :\tOptional[Any]\t\t\t\t\t\t\t\t=\t\t(\n 'Number of initial values must be equal to number of rows in coefficient '\n F'matrix but received {len(UpperCAmelCase_\t\t\t\t\t\t\t)} and {rowsa}'\n )\n raise ValueError(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n if iterations <= 0:\n raise ValueError('Iterations must be at least 1'\t\t\t\t\t\t\t)\n\n __lowerCamelCase :\tNDArray[floataa]\t\t\t\t\t\t\t\t=\t\tnp.concatenate(\n (coefficient_matrix, constant_matrix) , axis=1\t\t\t\t\t\t\t)\n\n __lowerCamelCase\t\t\t\t, __lowerCamelCase :\tDict\t\t\t\t\t\t\t\t=\t\ttable.shape\n\n strictly_diagonally_dominant(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n # Iterates the whole matrix for given number of times\n for _ in range(UpperCAmelCase_\t\t\t\t\t\t\t):\n __lowerCamelCase :\tOptional[int]\t\t\t\t\t\t\t\t=\t\t[]\n for row in range(UpperCAmelCase_\t\t\t\t\t\t\t):\n __lowerCamelCase :\tAny\t\t\t\t\t\t\t\t=\t\t0\n for col in range(UpperCAmelCase_\t\t\t\t\t\t\t):\n if col == row:\n __lowerCamelCase :\tUnion[str, Any]\t\t\t\t\t\t\t\t=\t\ttable[row][col]\n elif col == cols - 1:\n __lowerCamelCase :\tOptional[int]\t\t\t\t\t\t\t\t=\t\ttable[row][col]\n else:\n temp += (-1) * table[row][col] * init_val[col]\n __lowerCamelCase :\tUnion[str, Any]\t\t\t\t\t\t\t\t=\t\t(temp + val) / denom\n new_val.append(UpperCAmelCase_\t\t\t\t\t\t\t)\n __lowerCamelCase :\tOptional[Any]\t\t\t\t\t\t\t\t=\t\tnew_val\n\n return [float(UpperCAmelCase_\t\t\t\t\t\t\t) for i in new_val]\n\n\n\ndef \t\t\tUpperCAmelCase__\t\t\t\t\t(\tUpperCAmelCase_ :\t\t\t\tNDArray[floataa]\t\t\t\t\t\t\t) ->\t\tbool:\n __lowerCamelCase\t\t\t\t, __lowerCamelCase :\tOptional[int]\t\t\t\t\t\t\t\t=\t\ttable.shape\n\n __lowerCamelCase :\tstr\t\t\t\t\t\t\t\t=\t\tTrue\n\n for i in range(0 , UpperCAmelCase_\t\t\t\t\t\t\t):\n __lowerCamelCase :\tint\t\t\t\t\t\t\t\t=\t\t0\n for j in range(0 , cols - 1\t\t\t\t\t\t\t):\n if i == j:\n continue\n else:\n total += table[i][j]\n\n if table[i][i] <= total:\n raise ValueError('Coefficient matrix is not strictly diagonally dominant'\t\t\t\t\t\t\t)\n\n return is_diagonally_dominant\n\n\n# Test Cases\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":185,"string":"185"},"style_context":{"kind":"string","value":"\n\n\n'''simple docstring'''\n\n\n\nfrom . import (\n albert,\n align,\n altclip,\n audio_spectrogram_transformer,\n auto,\n autoformer,\n bark,\n bart,\n barthez,\n bartpho,\n beit,\n bert,\n bert_generation,\n bert_japanese,\n bertweet,\n big_bird,\n bigbird_pegasus,\n biogpt,\n bit,\n blenderbot,\n blenderbot_small,\n blip,\n blip_a,\n bloom,\n bridgetower,\n byta,\n camembert,\n canine,\n chinese_clip,\n clap,\n clip,\n clipseg,\n codegen,\n conditional_detr,\n convbert,\n convnext,\n convnextva,\n cpm,\n cpmant,\n ctrl,\n cvt,\n dataavec,\n deberta,\n deberta_va,\n decision_transformer,\n deformable_detr,\n deit,\n deprecated,\n deta,\n detr,\n dialogpt,\n dinat,\n distilbert,\n dit,\n donut,\n dpr,\n dpt,\n efficientformer,\n efficientnet,\n electra,\n encodec,\n encoder_decoder,\n ernie,\n ernie_m,\n esm,\n falcon,\n flaubert,\n flava,\n fnet,\n focalnet,\n fsmt,\n funnel,\n git,\n glpn,\n gpta,\n gpt_bigcode,\n gpt_neo,\n gpt_neox,\n gpt_neox_japanese,\n gpt_swa,\n gptj,\n gptsan_japanese,\n graphormer,\n groupvit,\n herbert,\n hubert,\n ibert,\n imagegpt,\n informer,\n instructblip,\n jukebox,\n layoutlm,\n layoutlmva,\n layoutlmva,\n layoutxlm,\n led,\n levit,\n lilt,\n llama,\n longformer,\n longta,\n luke,\n lxmert,\n mam_aaa,\n marian,\n markuplm,\n maskaformer,\n maskformer,\n mbart,\n mbartaa,\n mega,\n megatron_bert,\n megatron_gpta,\n mgp_str,\n mluke,\n mobilebert,\n mobilenet_va,\n mobilenet_va,\n mobilevit,\n mobilevitva,\n mpnet,\n mra,\n mta,\n musicgen,\n mvp,\n nat,\n nezha,\n nllb,\n nllb_moe,\n nystromformer,\n oneformer,\n open_llama,\n openai,\n opt,\n owlvit,\n pegasus,\n pegasus_x,\n perceiver,\n phobert,\n pixastruct,\n plbart,\n poolformer,\n prophetnet,\n qdqbert,\n rag,\n realm,\n reformer,\n regnet,\n rembert,\n resnet,\n roberta,\n roberta_prelayernorm,\n roc_bert,\n roformer,\n rwkv,\n sam,\n segformer,\n sew,\n sew_d,\n speech_encoder_decoder,\n speech_to_text,\n speech_to_text_a,\n speechta,\n splinter,\n squeezebert,\n swiftformer,\n swin,\n swinasr,\n swinva,\n switch_transformers,\n ta,\n table_transformer,\n tapas,\n time_series_transformer,\n timesformer,\n timm_backbone,\n transfo_xl,\n trocr,\n tvlt,\n umta,\n unispeech,\n unispeech_sat,\n upernet,\n videomae,\n vilt,\n vision_encoder_decoder,\n vision_text_dual_encoder,\n visual_bert,\n vit,\n vit_hybrid,\n vit_mae,\n vit_msn,\n vivit,\n wavaveca,\n wavaveca_conformer,\n wavaveca_phoneme,\n wavaveca_with_lm,\n wavlm,\n whisper,\n x_clip,\n xglm,\n xlm,\n xlm_prophetnet,\n xlm_roberta,\n xlm_roberta_xl,\n xlnet,\n xmod,\n yolos,\n yoso,\n)\n\n\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":185,"string":"185"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":245,"cells":{"code":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\n\n\n\n\nfrom __future__ import annotations\n\n\n\n\n\ndef \t\t\t\t\t\t__snake_case( _lowerCAmelCase\t\t\t\t\t, _lowerCAmelCase\t\t)\t\t->\t\t\tbool:\n\n\n if len(_snake_case\t\t) == 0:\n return False\n snake_case__ : Dict \t\t\t\t\t\t=\t\t\t\tlen(_snake_case\t\t) // 2\n if a_list[midpoint] == item:\n return True\n if item < a_list[midpoint]:\n return binary_search(a_list[:midpoint]\t\t\t\t\t, _snake_case\t\t)\n else:\n return binary_search(a_list[midpoint + 1 :]\t\t\t\t\t, _snake_case\t\t)\n\n\nif __name__ == \"__main__\":\n __a \t=\t\tinput(\"Enter numbers separated by comma:\\n\").strip()\n __a \t=\t\t[int(item.strip()) for item in user_input.split(\",\")]\n __a \t=\t\tint(input(\"Enter the number to be found in the list:\\n\").strip())\n __a \t=\t\t\"\" if binary_search(sequence, target) else \"not \"\n print(F\"{target} was {not_str}found in {sequence}\")\n"},"code_codestyle":{"kind":"number","value":369,"string":"369"},"style_context":{"kind":"string","value":"\r\r\r\r'''simple docstring'''\r\r\r\r\r\rfrom queue import Queue\rfrom typing import TYPE_CHECKING, Optional\r\r\rif TYPE_CHECKING:\r from ..models.auto import AutoTokenizer\r\r\r\r\r\r\r\rclass UpperCAmelCase_\t:\r \"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tOptional[Any]\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tOptional[int]\t\t\t\t\t\t):\r raise NotImplementedError()\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tOptional[int]\t\t\t\t\t\t):\r raise NotImplementedError()\r\r\r\r\r\r\r\rclass UpperCAmelCase_\t(\t_a ):\r \"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\r def __init__( self :\t\t\t\t\tTuple\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\t\"AutoTokenizer\"\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tbool = False\t\t\t,\t\t\t\t\t**snake_case_ :\t\t\t\t\tTuple\t\t\t\t\t\t):\r snake_case__ : Tuple \t\t\t\t\t\t=\t\t\t\ttokenizer\r snake_case__ : List[str] \t\t\t\t\t\t=\t\t\t\tskip_prompt\r snake_case__ : Optional[int] \t\t\t\t\t\t=\t\t\t\tdecode_kwargs\r\r # variables used in the streaming process\r snake_case__ : Optional[int] \t\t\t\t\t\t=\t\t\t\t[]\r snake_case__ : Optional[int] \t\t\t\t\t\t=\t\t\t\t0\r snake_case__ : List[Any] \t\t\t\t\t\t=\t\t\t\tTrue\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tList[str]\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tint\t\t\t\t\t\t):\r if len(value.shape\t\t\t\t\t\t) > 1 and value.shape[0] > 1:\r raise ValueError(\"\"\"TextStreamer only supports batch size 1\"\"\"\t\t\t\t\t\t)\r elif len(value.shape\t\t\t\t\t\t) > 1:\r snake_case__ : Optional[Any] \t\t\t\t\t\t=\t\t\t\tvalue[0]\r\r if self.skip_prompt and self.next_tokens_are_prompt:\r snake_case__ : List[Any] \t\t\t\t\t\t=\t\t\t\tFalse\r return\r\r # Add the new token to the cache and decodes the entire thing.\r self.token_cache.extend(value.tolist()\t\t\t\t\t\t)\r snake_case__ : Tuple \t\t\t\t\t\t=\t\t\t\tself.tokenizer.decode(self.token_cache\t\t\t,\t\t\t\t\t**self.decode_kwargs\t\t\t\t\t\t)\r\r # After the symbol for a new line, we flush the cache.\r if text.endswith(\"\"\"\\n\"\"\"\t\t\t\t\t\t):\r snake_case__ : int \t\t\t\t\t\t=\t\t\t\ttext[self.print_len :]\r snake_case__ : Optional[int] \t\t\t\t\t\t=\t\t\t\t[]\r snake_case__ : int \t\t\t\t\t\t=\t\t\t\t0\r # If the last token is a CJK character, we print the characters.\r elif len(snake_case_\t\t\t\t\t\t) > 0 and self._is_chinese_char(ord(text[-1]\t\t\t\t\t\t)\t\t\t\t\t\t):\r snake_case__ : str \t\t\t\t\t\t=\t\t\t\ttext[self.print_len :]\r self.print_len += len(snake_case_\t\t\t\t\t\t)\r # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,\r # which may change with the subsequent token -- there are probably smarter ways to do this!)\r else:\r snake_case__ : Dict \t\t\t\t\t\t=\t\t\t\ttext[self.print_len : text.rfind(\"\"\" \"\"\"\t\t\t\t\t\t) + 1]\r self.print_len += len(snake_case_\t\t\t\t\t\t)\r\r self.on_finalized_text(snake_case_\t\t\t\t\t\t)\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tint\t\t\t\t\t\t):\r # Flush the cache, if it exists\r if len(self.token_cache\t\t\t\t\t\t) > 0:\r snake_case__ : Union[str, Any] \t\t\t\t\t\t=\t\t\t\tself.tokenizer.decode(self.token_cache\t\t\t,\t\t\t\t\t**self.decode_kwargs\t\t\t\t\t\t)\r snake_case__ : Optional[Any] \t\t\t\t\t\t=\t\t\t\ttext[self.print_len :]\r snake_case__ : Tuple \t\t\t\t\t\t=\t\t\t\t[]\r snake_case__ : int \t\t\t\t\t\t=\t\t\t\t0\r else:\r snake_case__ : int \t\t\t\t\t\t=\t\t\t\t\"\"\"\"\"\"\r\r snake_case__ : Union[str, Any] \t\t\t\t\t\t=\t\t\t\tTrue\r self.on_finalized_text(snake_case_\t\t\t,\t\t\t\t\tstream_end=snake_case_\t\t\t\t\t\t)\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tOptional[int]\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tstr\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tbool = False\t\t\t\t\t\t):\r print(snake_case_\t\t\t,\t\t\t\t\tflush=snake_case_\t\t\t,\t\t\t\t\tend=\"\"\"\"\"\" if not stream_end else None\t\t\t\t\t\t)\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tint\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tOptional[int]\t\t\t\t\t\t):\r # This defines a \"chinese character\" as anything in the CJK Unicode block:\r # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\r #\r # Note that the CJK Unicode block is NOT all Japanese and Korean characters,\r # despite its name. The modern Korean Hangul alphabet is a different block,\r # as is Japanese Hiragana and Katakana. Those alphabets are used to write\r # space-separated words, so they are not treated specially and handled\r # like the all of the other languages.\r if (\r (cp >= 0x4E00 and cp <= 0x9FFF)\r or (cp >= 0x3400 and cp <= 0x4DBF) #\r or (cp >= 0x20000 and cp <= 0x2A6DF) #\r or (cp >= 0x2A700 and cp <= 0x2B73F) #\r or (cp >= 0x2B740 and cp <= 0x2B81F) #\r or (cp >= 0x2B820 and cp <= 0x2CEAF) #\r or (cp >= 0xF900 and cp <= 0xFAFF)\r or (cp >= 0x2F800 and cp <= 0x2FA1F) #\r ): #\r return True\r\r return False\r\r\r\r\r\r\r\rclass UpperCAmelCase_\t(\t_a ):\r \"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\r def __init__( self :\t\t\t\t\tOptional[int]\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\t\"AutoTokenizer\"\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tbool = False\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tOptional[float] = None\t\t\t,\t\t\t\t\t**snake_case_ :\t\t\t\t\tList[Any]\t\t\t\t\t\t):\r super().__init__(snake_case_\t\t\t,\t\t\t\t\tsnake_case_\t\t\t,\t\t\t\t\t**snake_case_\t\t\t\t\t\t)\r snake_case__ : Dict \t\t\t\t\t\t=\t\t\t\tQueue()\r snake_case__ : List[Any] \t\t\t\t\t\t=\t\t\t\tNone\r snake_case__ : int \t\t\t\t\t\t=\t\t\t\ttimeout\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tDict\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tstr\t\t\t,\t\t\t\t\tsnake_case_ :\t\t\t\t\tbool = False\t\t\t\t\t\t):\r self.text_queue.put(snake_case_\t\t\t,\t\t\t\t\ttimeout=self.timeout\t\t\t\t\t\t)\r if stream_end:\r self.text_queue.put(self.stop_signal\t\t\t,\t\t\t\t\ttimeout=self.timeout\t\t\t\t\t\t)\r\r\r\r\r def __iter__( self :\t\t\t\t\tList[str]\t\t\t\t\t\t):\r return self\r\r\r\r\r def lowerCamelCase\t( self :\t\t\t\t\tstr\t\t\t\t\t\t):\r snake_case__ : List[Any] \t\t\t\t\t\t=\t\t\t\tself.text_queue.get(timeout=self.timeout\t\t\t\t\t\t)\r if value == self.stop_signal:\r raise StopIteration()\r else:\r return value\r"},"style_context_codestyle":{"kind":"number","value":43,"string":"43"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":246,"cells":{"code":{"kind":"string","value":"\n\n\n\n\n\n'''simple docstring'''\n\n\nimport datasets\n\nfrom .evaluate import evaluate\n\n\n_lowerCamelCase :\t\tList[str] \t\t\t=\t\t\t\t'\\\\n@article{hendrycks2021cuad,\\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\\n journal={arXiv preprint arXiv:2103.06268},\\n year={2021}\\n}\\n'\n\n_lowerCamelCase :\t\tList[Any] \t\t\t=\t\t\t\t'\\nThis metric wrap the official scoring script for version 1 of the Contract\\nUnderstanding Atticus Dataset (CUAD).\\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\\n'\n\n_lowerCamelCase :\t\tDict \t\t\t=\t\t\t\t'\\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\\nArgs:\\n predictions: List of question-answers dictionaries with the following key-values:\\n - \\'id\\': id of the question-answer pair as given in the references (see below)\\n - \\'prediction_text\\': list of possible texts for the answer, as a list of strings\\n depending on a threshold on the confidence probability of each prediction.\\n references: List of question-answers dictionaries with the following key-values:\\n - \\'id\\': id of the question-answer pair (see above),\\n - \\'answers\\': a Dict in the CUAD dataset format\\n {\\n \\'text\\': list of possible texts for the answer, as a list of strings\\n \\'answer_start\\': list of start positions for the answer, as a list of ints\\n }\\n Note that answer_start values are not taken into account to compute the metric.\\nReturns:\\n \\'exact_match\\': Exact match (the normalized answer exactly match the gold answer)\\n \\'f1\\': The F-score of predicted tokens versus the gold answer\\n \\'aupr\\': Area Under the Precision-Recall curve\\n \\'prec_at_80_recall\\': Precision at 80% recall\\n \\'prec_at_90_recall\\': Precision at 90% recall\\nExamples:\\n >>> predictions = [{\\'prediction_text\\': [\\'The seller:\\', \\'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\\'], \\'id\\': \\'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\\'}]\\n >>> references = [{\\'answers\\': {\\'answer_start\\': [143, 49], \\'text\\': [\\'The seller:\\', \\'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\\']}, \\'id\\': \\'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\\'}]\\n >>> cuad_metric = datasets.load_metric(\"cuad\")\\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\\n >>> print(results)\\n {\\'exact_match\\': 100.0, \\'f1\\': 100.0, \\'aupr\\': 0.0, \\'prec_at_80_recall\\': 1.0, \\'prec_at_90_recall\\': 1.0}\\n'\n\n\n\n@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION\t\t\t\t\t\t, _KWARGS_DESCRIPTION )\nclass \t\t\t\t\t\t\t__UpperCAmelCase (\t\t\t\tdatasets.Metric ):\n\n\n\n\n\n\n\n\t\t'''simple docstring'''\n\n\n\n\n\n\n\n\t\tdef \t\t\t\tA (self :\t\t\t\t\tint\t\t\t\t\t):\n\t\t\treturn datasets.MetricInfo(\n\t\t\t description=_DESCRIPTION\t\t\t\t\t,\t\t\t\t\tcitation=_CITATION\t\t\t\t\t,\t\t\t\t\tinputs_description=_KWARGS_DESCRIPTION\t\t\t\t\t,\t\t\t\t\tfeatures=datasets.Features(\n\t\t\t {\n\t\t\t \"\"\"predictions\"\"\": {\n\t\t\t \"\"\"id\"\"\": datasets.Value(\"\"\"string\"\"\"\t\t\t\t\t),\n\t\t\t \"\"\"prediction_text\"\"\": datasets.features.Sequence(datasets.Value(\"\"\"string\"\"\"\t\t\t\t\t)\t\t\t\t\t),\n\t\t\t },\n\t\t\t \"\"\"references\"\"\": {\n\t\t\t \"\"\"id\"\"\": datasets.Value(\"\"\"string\"\"\"\t\t\t\t\t),\n\t\t\t \"\"\"answers\"\"\": datasets.features.Sequence(\n\t\t\t {\n\t\t\t \"\"\"text\"\"\": datasets.Value(\"\"\"string\"\"\"\t\t\t\t\t),\n\t\t\t \"\"\"answer_start\"\"\": datasets.Value(\"\"\"int32\"\"\"\t\t\t\t\t),\n\t\t\t }\t\t\t\t\t),\n\t\t\t },\n\t\t\t }\t\t\t\t\t)\t\t\t\t\t,\t\t\t\t\tcodebase_urls=[\"\"\"https://www.atticusprojectai.org/cuad\"\"\"]\t\t\t\t\t,\t\t\t\t\treference_urls=[\"\"\"https://www.atticusprojectai.org/cuad\"\"\"]\t\t\t\t\t,\t\t\t\t\t)\n\n\n\n\n\n\n\n\t\tdef \t\t\t\tA (self :\t\t\t\t\tDict\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tOptional[Any]\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tAny\t\t\t\t\t):\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\t{prediction[\"\"\"id\"\"\"]: prediction[\"\"\"prediction_text\"\"\"] for prediction in predictions}\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\t[\n\t\t\t {\n\t\t\t \"\"\"paragraphs\"\"\": [\n\t\t\t {\n\t\t\t \"\"\"qas\"\"\": [\n\t\t\t {\n\t\t\t \"\"\"answers\"\"\": [{\"\"\"text\"\"\": answer_text} for answer_text in ref[\"\"\"answers\"\"\"][\"\"\"text\"\"\"]],\n\t\t\t \"\"\"id\"\"\": ref[\"\"\"id\"\"\"],\n\t\t\t }\n\t\t\t for ref in references\n\t\t\t ]\n\t\t\t }\n\t\t\t ]\n\t\t\t }\n\t\t\t]\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tevaluate(dataset=_lowerCAmelCase\t\t\t\t\t,\t\t\t\t\tpredictions=_lowerCAmelCase\t\t\t\t\t)\n\t\t\treturn score\n\n"},"code_codestyle":{"kind":"number","value":258,"string":"258"},"style_context":{"kind":"string","value":"\n\n\n\n\n\n'''simple docstring'''\n\n\nfrom typing import List, Union\n\nfrom ..utils import (\n add_end_docstrings,\n is_tf_available,\n is_torch_available,\n is_vision_available,\n logging,\n requires_backends,\n)\nfrom .base import PIPELINE_INIT_ARGS, Pipeline\n\n\nif is_vision_available():\n\t\t\t\tfrom PIL import Image\n\n\t\t\t\tfrom ..image_utils import load_image\n\nif is_tf_available():\n\t\t\t\timport tensorflow as tf\n\n\t\t\t\tfrom ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\n\t\t\t\tfrom ..tf_utils import stable_softmax\n\nif is_torch_available():\n\t\t\t\tfrom ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\n\n_lowerCamelCase :\t\tUnion[str, Any] \t\t\t=\t\t\t\tlogging.get_logger(__name__)\n\n\n\n@add_end_docstrings(A__ )\nclass \t\t\t\t\t\t\t__UpperCAmelCase (\t\t\t\tA__ ):\n\n\n\n\n\n\n\n\t\t'''simple docstring'''\n\n\n\n\n\n\n\n\t\tdef __init__(self :\t\t\t\t\tTuple\t\t\t\t\t,\t\t\t\t\t*_lowerCAmelCase :\t\t\t\t\tList[str]\t\t\t\t\t,\t\t\t\t\t**_lowerCAmelCase :\t\t\t\t\tList[str]\t\t\t\t\t):\n\t\t\tsuper().__init__(*_lowerCAmelCase\t\t\t\t\t,\t\t\t\t\t**_lowerCAmelCase\t\t\t\t\t)\n\t\t\trequires_backends(self\t\t\t\t\t,\t\t\t\t\t\"\"\"vision\"\"\"\t\t\t\t\t)\n\t\t\tself.check_model_type(\n\t\t\t TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\n\t\t\t if self.framework == \"\"\"tf\"\"\"\n\t\t\t else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\t\t\t\t\t)\n\n\n\n\n\n\n\n\t\tdef \t\t\t\tA (self :\t\t\t\t\tAny\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tstr=None\t\t\t\t\t):\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\t{}\n\t\t\tif top_k is not None:\n\t\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\ttop_k\n\t\t\treturn {}, {}, postprocess_params\n\n\n\n\n\n\n\n\t\tdef __call__(self :\t\t\t\t\tstr\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tUnion[str, List[str], \"Image.Image\", List[\"Image.Image\"]]\t\t\t\t\t,\t\t\t\t\t**_lowerCAmelCase :\t\t\t\t\tint\t\t\t\t\t):\n\t\t\treturn super().__call__(_lowerCAmelCase\t\t\t\t\t,\t\t\t\t\t**_lowerCAmelCase\t\t\t\t\t)\n\n\n\n\n\n\n\n\t\tdef \t\t\t\tA (self :\t\t\t\t\tList[str]\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tList[Any]\t\t\t\t\t):\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tload_image(_lowerCAmelCase\t\t\t\t\t)\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tself.image_processor(images=_lowerCAmelCase\t\t\t\t\t,\t\t\t\t\treturn_tensors=self.framework\t\t\t\t\t)\n\t\t\treturn model_inputs\n\n\n\n\n\n\n\n\t\tdef \t\t\t\tA (self :\t\t\t\t\tUnion[str, Any]\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tOptional[int]\t\t\t\t\t):\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tself.model(**_lowerCAmelCase\t\t\t\t\t)\n\t\t\treturn model_outputs\n\n\n\n\n\n\n\n\t\tdef \t\t\t\tA (self :\t\t\t\t\tOptional[Any]\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tUnion[str, Any]\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase :\t\t\t\t\tint=5\t\t\t\t\t):\n\t\t\tif top_k > self.model.config.num_labels:\n\t\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tself.model.config.num_labels\n\n\t\t\tif self.framework == \"pt\":\n\t\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tmodel_outputs.logits.softmax(-1\t\t\t\t\t)[0]\n\t\t\t\tA ,\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tprobs.topk(_lowerCAmelCase\t\t\t\t\t)\n\t\t\telif self.framework == \"tf\":\n\t\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tstable_softmax(model_outputs.logits\t\t\t\t\t,\t\t\t\t\taxis=-1\t\t\t\t\t)[0]\n\t\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\ttf.math.top_k(_lowerCAmelCase\t\t\t\t\t,\t\t\t\t\tk=_lowerCAmelCase\t\t\t\t\t)\n\t\t\t\tA ,\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\ttopk.values.numpy(), topk.indices.numpy()\n\t\t\telse:\n\t\t\t\traise ValueError(F\"\"\"Unsupported framework: {self.framework}\"\"\"\t\t\t\t\t)\n\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tscores.tolist()\n\t\t\tA\t\t\t\t\t\t\t =\t\t\t\t\tids.tolist()\n\t\t\treturn [{\"score\": score, \"label\": self.model.config.idalabel[_id]} for score, _id in zip(_lowerCAmelCase\t\t\t\t\t,\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t)]\n\n"},"style_context_codestyle":{"kind":"number","value":258,"string":"258"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":247,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nimport argparse\r\nimport os\r\nimport re\r\n\r\n\r\n_snake_case\t\t\t\t:\t\t\t\tList[str] \t\t\t\t\t\t\t=\t\t'src/transformers/models/auto'\r\n\r\n\r\n# re pattern that matches mapping introductions:\r\n# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict\r\n_snake_case\t\t\t\t:\t\t\t\tAny \t\t\t\t\t\t\t=\t\tre.compile(R'[A-Z_]+_MAPPING(\\s+|_[A-Z_]+\\s+)=\\s+OrderedDict')\r\n# re pattern that matches identifiers in mappings\r\n_snake_case\t\t\t\t:\t\t\t\tList[str] \t\t\t\t\t\t\t=\t\tre.compile(R'\\s*\\(\\s*\"(\\S[^\"]+)\"')\r\ndef \t\tsnake_case_ (UpperCamelCase\t: str\t\t\t,\t\t\t\t\t\tUpperCamelCase\t: bool = False\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\t\t\t\t\t\t\twith open(UpperCamelCase\t\t\t,\t\t\t\t\t\t'''r'''\t\t\t,\t\t\t\t\t\tencoding='''utf-8'''\t\t\t\t) as f:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= f.read()\r\n\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= content.split('''\\n'''\t\t\t\t)\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= []\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= 0\r\n\t\t\t\t\t\t\twhile line_idx < len(UpperCamelCase\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif _re_intro_mapping.search(lines[line_idx]\t\t\t\t) is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= len(re.search(R'''^(\\s*)\\S'''\t\t\t,\t\t\t\t\t\tlines[line_idx]\t\t\t\t).groups()[0]\t\t\t\t) + 8\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Start of a new mapping!\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhile not lines[line_idx].startswith(''' ''' * indent + '''('''\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew_lines.append(lines[line_idx]\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tline_idx += 1\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= []\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhile lines[line_idx].strip() != \"]\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Blocks either fit in one line or not\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif lines[line_idx].strip() == \"(\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= line_idx\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhile not lines[line_idx].startswith(''' ''' * indent + ''')'''\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tline_idx += 1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblocks.append('''\\n'''.join(lines[start_idx : line_idx + 1]\t\t\t\t)\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblocks.append(lines[line_idx]\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tline_idx += 1\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Sort blocks by their identifiers\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= sorted(UpperCamelCase\t\t\t,\t\t\t\t\t\tkey=lambda UpperCamelCase\t\t\t\t: _re_identifier.search(UpperCamelCase\t\t\t\t).groups()[0]\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew_lines += blocks\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew_lines.append(lines[line_idx]\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tline_idx += 1\r\n\r\n\t\t\t\t\t\t\tif overwrite:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twith open(UpperCamelCase\t\t\t,\t\t\t\t\t\t'''w'''\t\t\t,\t\t\t\t\t\tencoding='''utf-8'''\t\t\t\t) as f:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tf.write('''\\n'''.join(UpperCamelCase\t\t\t\t)\t\t\t\t)\r\n\t\t\t\t\t\t\telif \"\\n\".join(UpperCamelCase\t\t\t\t) != content:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn True\r\ndef \t\tsnake_case_ (UpperCamelCase\t: bool = False\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= [os.path.join(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t\t) for f in os.listdir(UpperCamelCase\t\t\t\t) if f.endswith('''.py'''\t\t\t\t)]\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= [sort_auto_mapping(UpperCamelCase\t\t\t,\t\t\t\t\t\toverwrite=UpperCamelCase\t\t\t\t) for fname in fnames]\r\n\r\n\t\t\t\t\t\t\tif not overwrite and any(UpperCamelCase\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a \t\t\t\t\t= [f for f, d in zip(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t\t) if d]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f'The following files have auto mappings that need sorting: {\", \".join(UpperCamelCase\t\t\t\t)}. Run `make style` to fix'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ''' this.'''\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\t_snake_case\t\t\t\t:\t\t\t\tTuple \t\t\t\t\t\t\t=\t\targparse.ArgumentParser()\r\n\t\t\t\tparser.add_argument('--check_only', action="https://huggingface.co/datasets/infinityofspace/python_codestyles-mixed1-500/viewer/default/store_true", help='Whether to only check or fix style.')\r\n\t\t\t\t_snake_case\t\t\t\t:\t\t\t\tTuple \t\t\t\t\t\t\t=\t\tparser.parse_args()\r\n\r\n\t\t\t\tsort_all_auto_mappings(not args.check_only)\r\n\r\n"},"code_codestyle":{"kind":"number","value":179,"string":"179"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nfrom __future__ import annotations\r\ndef \t\tsnake_case_ (UpperCamelCase\t: list[int]\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\t\t\t\t\t\t\tif not nums:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn 0\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= nums[0]\r\n\t\t\t\t\t\t\t_a \t\t\t\t\t= 0\r\n\t\t\t\t\t\t\tfor num in nums[1:]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t,\t\t\t\t\t\t\t_a \t\t\t\t\t= (\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t max_excluding + num,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t max(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\treturn max(UpperCamelCase\t\t\t,\t\t\t\t\t\tUpperCamelCase\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\timport doctest\r\n\r\n\t\t\t\tdoctest.testmod()\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":179,"string":"179"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":248,"cells":{"code":{"kind":"string","value":"\n\n\n\nimport os\nfrom shutil import copyfile\nfrom typing import List, Optional, Tuple\n\nimport sentencepiece as spm\n\nfrom ...tokenization_utils import PreTrainedTokenizer\nfrom ...utils import logging\n\n\nlowerCamelCase__\t= logging.get_logger(__name__)\n\nlowerCamelCase__\t= {\"\"\"vocab_file\"\"\": \"\"\"sentencepiece.model\"\"\"}\n\nlowerCamelCase__\t= {\n \"\"\"vocab_file\"\"\": {\n \"\"\"google/rembert\"\"\": \"\"\"https://huggingface.co/google/rembert/resolve/main/sentencepiece.model\"\"\",\n },\n}\n\nlowerCamelCase__\t= {\n \"\"\"google/rembert\"\"\": 256,\n}\n\n\n\n\n\n\nclass SCREAMING_SNAKE_CASE\t(\t\t\t\t\t\t\tlowerCamelCase__ ):\n\t\t\t\t\t\t\t__lowerCamelCase\t\t:\t\tTuple\t\t\t=VOCAB_FILES_NAMES\n\t\t\t\t\t\t\t__lowerCamelCase\t\t:\t\tstr\t\t\t=PRETRAINED_VOCAB_FILES_MAP\n\t\t\t\t\t\t\t__lowerCamelCase\t\t:\t\tOptional[int]\t\t\t=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__( self\t\t\t\t\t\t:\t\t\t\t\t\tstr\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tList[str]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tDict=False\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tList[Any]=True\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tstr=True\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tint=\"[CLS]\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tList[str]=\"[SEP]\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tDict=\"[UNK]\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tstr=\"[SEP]\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tAny=\"[PAD]\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tTuple=\"[CLS]\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tstr=\"[MASK]\"\t\t\t\t\t, **__lowercase\t\t\t\t\t\t:\t\t\t\t\t\tDict\t\t\t\t\t, ):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(\n\t\t\t\t\t\t\t\t\t\t\t do_lower_case=__lowercase\t\t\t\t\t, remove_space=__lowercase\t\t\t\t\t, keep_accents=__lowercase\t\t\t\t\t, bos_token=__lowercase\t\t\t\t\t, eos_token=__lowercase\t\t\t\t\t, unk_token=__lowercase\t\t\t\t\t, sep_token=__lowercase\t\t\t\t\t, pad_token=__lowercase\t\t\t\t\t, cls_token=__lowercase\t\t\t\t\t, mask_token=__lowercase\t\t\t\t\t, **__lowercase\t\t\t\t\t, )\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tdo_lower_case\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tremove_space\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tkeep_accents\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tvocab_file\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tspm.SentencePieceProcessor()\n\t\t\t\t\t\t\t\t\t\t\tself.sp_model.Load(__lowercase\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\t@property\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tAny\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\treturn len(self.sp_model\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tOptional[Any]\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t{self.convert_ids_to_tokens(__lowercase\t\t): i for i in range(self.vocab_size\t\t)}\n\t\t\t\t\t\t\t\t\t\t\tvocab.update(self.added_tokens_encoder\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn vocab\n\n\n\n\n\n\t\t\t\t\t\t\tdef __getstate__( self\t\t\t\t\t\t:\t\t\t\t\t\tTuple\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.__dict__.copy()\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tNone\n\t\t\t\t\t\t\t\t\t\t\treturn state\n\n\n\n\n\n\t\t\t\t\t\t\tdef __setstate__( self\t\t\t\t\t\t:\t\t\t\t\t\tTuple\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tAny\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\td\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tspm.SentencePieceProcessor()\n\t\t\t\t\t\t\t\t\t\t\tself.sp_model.Load(self.vocab_file\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tstr\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int]=False\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.sp_model.EncodeAsPieces(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn pieces\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tstr\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[Any]\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\treturn self.sp_model.PieceToId(__lowercase\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[Any]\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\treturn self.sp_model.IdToPiece(__lowercase\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tOptional[Any]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tTuple\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.sp_model.decode_pieces(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\treturn out_string\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tList[str]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tList[int]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[List[int]] = None\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t[self.sep_token_id]\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t[self.cls_token_id]\n\t\t\t\t\t\t\t\t\t\t\tif token_ids_a is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn cls + token_ids_a + sep\n\t\t\t\t\t\t\t\t\t\t\treturn cls + token_ids_a + sep + token_ids_a + sep\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tint\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tList[int]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[List[int]] = None\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tbool = False\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\n\t\t\t\t\t\t\t\t\t\t\tif already_has_special_tokens:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif token_ids_a is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"You should not supply a second sequence if the provided sequence of \"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"ids is already formatted with special tokens for the model.\"\"\"\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]\n\n\t\t\t\t\t\t\t\t\t\t\tif token_ids_a is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn [1] + ([0] * len(__lowercase\t\t)) + [1] + ([0] * len(__lowercase\t\t)) + [1]\n\t\t\t\t\t\t\t\t\t\t\treturn [1] + ([0] * len(__lowercase\t\t)) + [1]\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tList[int]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[List[int]] = None\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t[self.sep_token_id]\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t[self.cls_token_id]\n\n\t\t\t\t\t\t\t\t\t\t\tif token_ids_a is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn len(cls + token_ids_a + sep\t\t) * [0]\n\t\t\t\t\t\t\t\t\t\t\treturn len(cls + token_ids_a + sep\t\t) * [0] + len(token_ids_a + sep\t\t) * [1]\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tint\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tstr\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[str] = None\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\tif not os.path.isdir(__lowercase\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.error(\"\"\"Vocabulary path ({}) should be a directory\"\"\".format(__lowercase\t\t)\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tos.path.join(\n\t\t\t\t\t\t\t\t\t\t\t __lowercase\t\t\t\t\t, (filename_prefix + \"\"\"-\"\"\" if filename_prefix else \"\"\"\"\"\") + VOCAB_FILES_NAMES[\"\"\"vocab_file\"\"\"]\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif os.path.abspath(self.vocab_file\t\t) != os.path.abspath(__lowercase\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcopyfile(self.vocab_file\t\t\t\t\t, __lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\treturn (out_vocab_file,)\n"},"code_codestyle":{"kind":"number","value":302,"string":"302"},"style_context":{"kind":"string","value":"\n\n\n\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Union\n\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom ..configuration_utils import ConfigMixin, register_to_config\nfrom ..utils import BaseOutput\nfrom .attention import BasicTransformerBlock\nfrom .attention_processor import AttentionProcessor, AttnProcessor\nfrom .embeddings import TimestepEmbedding, Timesteps\nfrom .modeling_utils import ModelMixin\n\n\n\n\n\n\n@dataclass\nclass SCREAMING_SNAKE_CASE\t(\t\t\t\t\t\t\tlowerCamelCase__ ):\n\t\t\t\t\t\t\t__lowerCamelCase\t\t:\t\ttorch.FloatTensor\n\n\n\n\n\n\nclass SCREAMING_SNAKE_CASE\t(\t\t\t\t\t\t\tlowerCamelCase__\t,\t\t\t\t\tlowerCamelCase__ ):\n\n\n\n\n\n\t\t\t\t\t\t\t@register_to_config\n\t\t\t\t\t\t\tdef __init__( self\t\t\t\t\t\t:\t\t\t\t\t\tDict\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tint = 32\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tint = 64\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tint = 20\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tint = 768\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tAny=77\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int]=4\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tfloat = 0.0\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tstr = \"silu\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[str] = None\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[str] = None\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[str] = \"linear\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[str] = \"prd\"\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int] = None\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int] = None\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int] = None\t\t\t\t\t, ):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnum_attention_heads\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tattention_head_dim\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnum_attention_heads * attention_head_dim\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tadditional_embeddings\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttime_embed_dim or inner_dim\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tembedding_proj_dim or embedding_dim\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tclip_embed_dim or embedding_dim\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tTimesteps(__lowercase\t\t\t\t\t, __lowercase\t\t\t\t\t, 0\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tTimestepEmbedding(__lowercase\t\t\t\t\t, __lowercase\t\t\t\t\t, out_dim=__lowercase\t\t\t\t\t, act_fn=__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Linear(__lowercase\t\t\t\t\t, __lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif embedding_proj_norm_type is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tNone\n\t\t\t\t\t\t\t\t\t\t\telif embedding_proj_norm_type == \"layer\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.LayerNorm(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(F\"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}\"\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Linear(__lowercase\t\t\t\t\t, __lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif encoder_hid_proj_type is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tNone\n\t\t\t\t\t\t\t\t\t\t\telif encoder_hid_proj_type == \"linear\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Linear(__lowercase\t\t\t\t\t, __lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(F\"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}\"\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Parameter(torch.zeros(1\t\t\t\t\t, num_embeddings + additional_embeddings\t\t\t\t\t, __lowercase\t\t)\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif added_emb_type == \"prd\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Parameter(torch.zeros(1\t\t\t\t\t, 1\t\t\t\t\t, __lowercase\t\t)\t\t)\n\t\t\t\t\t\t\t\t\t\t\telif added_emb_type is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tNone\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t F\"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`.\"\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.ModuleList(\n\t\t\t\t\t\t\t\t\t\t\t [\n\t\t\t\t\t\t\t\t\t\t\t BasicTransformerBlock(\n\t\t\t\t\t\t\t\t\t\t\t __lowercase\t\t\t\t\t, __lowercase\t\t\t\t\t, __lowercase\t\t\t\t\t, dropout=__lowercase\t\t\t\t\t, activation_fn=\"\"\"gelu\"\"\"\t\t\t\t\t, attention_bias=__lowercase\t\t\t\t\t, )\n\t\t\t\t\t\t\t\t\t\t\t for d in range(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\t ]\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif norm_in_type == \"layer\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.LayerNorm(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\telif norm_in_type is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tNone\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(F\"Unsupported norm_in_type: {norm_in_type}.\"\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.LayerNorm(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Linear(__lowercase\t\t\t\t\t, __lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttorch.full(\n\t\t\t\t\t\t\t\t\t\t\t [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]\t\t\t\t\t, -10000.0\t\t)\n\t\t\t\t\t\t\t\t\t\t\tcausal_attention_mask.triu_(1\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tcausal_attention_mask[None, ...]\n\t\t\t\t\t\t\t\t\t\t\tself.register_buffer(\"\"\"causal_attention_mask\"\"\"\t\t\t\t\t, __lowercase\t\t\t\t\t, persistent=__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Parameter(torch.zeros(1\t\t\t\t\t, __lowercase\t\t)\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tnn.Parameter(torch.zeros(1\t\t\t\t\t, __lowercase\t\t)\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\t@property\n\t\t\t\t\t\t\t# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tList[str]\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t{}\n\n\t\t\t\t\t\t\t\t\t\t\tdef fn_recursive_add_processors(__lowercase\t\t\t\t\t\t:\t\t\t\t\t\tstr\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\ttorch.nn.Module\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tDict[str, AttentionProcessor]\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif hasattr(__lowercase\t\t\t\t\t, \"\"\"set_processor\"\"\"\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tmodule.processor\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor sub_name, child in module.named_children():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfn_recursive_add_processors(F\"{name}.{sub_name}\"\t\t\t\t\t, __lowercase\t\t\t\t\t, __lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn processors\n\n\t\t\t\t\t\t\t\t\t\t\tfor name, module in self.named_children():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfn_recursive_add_processors(__lowercase\t\t\t\t\t, __lowercase\t\t\t\t\t, __lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\treturn processors\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tList[str]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tUnion[AttentionProcessor, Dict[str, AttentionProcessor]]\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tlen(self.attn_processors.keys()\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif isinstance(__lowercase\t\t\t\t\t, __lowercase\t\t) and len(__lowercase\t\t) != count:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t F\"A dict of processors was passed, but the number of processors {len(__lowercase\t\t)} does not match the\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t F\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tdef fn_recursive_attn_processor(__lowercase\t\t\t\t\t\t:\t\t\t\t\t\tstr\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\ttorch.nn.Module\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tDict\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif hasattr(__lowercase\t\t\t\t\t, \"\"\"set_processor\"\"\"\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not isinstance(__lowercase\t\t\t\t\t, __lowercase\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmodule.set_processor(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmodule.set_processor(processor.pop(F\"{name}.processor\"\t\t)\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor sub_name, child in module.named_children():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfn_recursive_attn_processor(F\"{name}.{sub_name}\"\t\t\t\t\t, __lowercase\t\t\t\t\t, __lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tfor name, module in self.named_children():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfn_recursive_attn_processor(__lowercase\t\t\t\t\t, __lowercase\t\t\t\t\t, __lowercase\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tList[str]\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\tself.set_attn_processor(AttnProcessor()\t\t)\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[int]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tUnion[torch.Tensor, float, int]\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\ttorch.FloatTensor\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[torch.FloatTensor] = None\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tOptional[torch.BoolTensor] = None\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tbool = True\t\t\t\t\t, ):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\thidden_states.shape[0]\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttimestep\n\t\t\t\t\t\t\t\t\t\t\tif not torch.is_tensor(__lowercase\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttorch.tensor([timesteps]\t\t\t\t\t, dtype=torch.long\t\t\t\t\t, device=hidden_states.device\t\t)\n\t\t\t\t\t\t\t\t\t\t\telif torch.is_tensor(__lowercase\t\t) and len(timesteps.shape\t\t) == 0:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttimesteps[None].to(hidden_states.device\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t# broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttimesteps * torch.ones(__lowercase\t\t\t\t\t, dtype=timesteps.dtype\t\t\t\t\t, device=timesteps.device\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.time_proj(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t# timesteps does not contain any weights and will always return f32 tensors\n\t\t\t\t\t\t\t\t\t\t\t# but time_embedding might be fp16, so we need to cast here.\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttimesteps_projected.to(dtype=self.dtype\t\t)\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.time_embedding(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif self.embedding_proj_norm is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.embedding_proj_norm(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.embedding_proj(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\tif self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.encoder_hidden_states_proj(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\telif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"\"\"`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set\"\"\"\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.proj_in(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.positional_embedding.to(hidden_states.dtype\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t[]\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t0\n\n\t\t\t\t\t\t\t\t\t\t\tif encoder_hidden_states is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tadditional_embeds.append(__lowercase\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tadditional_embeddings_len += encoder_hidden_states.shape[1]\n\n\t\t\t\t\t\t\t\t\t\t\tif len(proj_embeddings.shape\t\t) == 2:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tproj_embeddings[:, None, :]\n\n\t\t\t\t\t\t\t\t\t\t\tif len(hidden_states.shape\t\t) == 2:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\thidden_states[:, None, :]\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tadditional_embeds + [\n\t\t\t\t\t\t\t\t\t\t\t proj_embeddings,\n\t\t\t\t\t\t\t\t\t\t\t time_embeddings[:, None, :],\n\t\t\t\t\t\t\t\t\t\t\t hidden_states,\n\t\t\t\t\t\t\t\t\t\t\t]\n\n\t\t\t\t\t\t\t\t\t\t\tif self.prd_embedding is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.prd_embedding.to(hidden_states.dtype\t\t).expand(__lowercase\t\t\t\t\t, -1\t\t\t\t\t, -1\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tadditional_embeds.append(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\ttorch.cat(\n\t\t\t\t\t\t\t\t\t\t\t __lowercase\t\t\t\t\t, dim=1\t\t\t\t\t, )\n\n\t\t\t\t\t\t\t\t\t\t\t# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tadditional_embeddings_len + proj_embeddings.shape[1] + 1\n\t\t\t\t\t\t\t\t\t\t\tif positional_embeddings.shape[1] < hidden_states.shape[1]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tF.pad(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t __lowercase\t\t\t\t\t, (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t additional_embeddings_len,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t )\t\t\t\t\t, value=0.0\t\t\t\t\t, )\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\thidden_states + positional_embeddings\n\n\t\t\t\t\t\t\t\t\t\t\tif attention_mask is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t(1 - attention_mask.to(hidden_states.dtype\t\t)) * -10000.0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tF.pad(__lowercase\t\t\t\t\t, (0, self.additional_embeddings)\t\t\t\t\t, value=0.0\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t(attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tattention_mask.repeat_interleave(self.config.num_attention_heads\t\t\t\t\t, dim=0\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif self.norm_in is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.norm_in(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tfor block in self.transformer_blocks:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tblock(__lowercase\t\t\t\t\t, attention_mask=__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.norm_out(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif self.prd_embedding is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\thidden_states[:, -1]\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\thidden_states[:, additional_embeddings_len:]\n\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\tself.proj_to_clip_embeddings(__lowercase\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\tif not return_dict:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn (predicted_image_embedding,)\n\n\t\t\t\t\t\t\t\t\t\t\treturn PriorTransformerOutput(predicted_image_embedding=__lowercase\t\t)\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tdef UpperCamelCase_ ( self\t\t\t\t\t\t:\t\t\t\t\t\tAny\t\t\t\t\t, __lowercase\t\t\t\t\t\t:\t\t\t\t\t\tTuple\t\t):\n\n\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\n\t\t\t\t\t\t\t\t\t\t\t__a =\t\t\t\t\t\t(prior_latents * self.clip_std) + self.clip_mean\n\t\t\t\t\t\t\t\t\t\t\treturn prior_latents\n"},"style_context_codestyle":{"kind":"number","value":302,"string":"302"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":249,"cells":{"code":{"kind":"string","value":"import argparse\r\nimport logging\r\nimport os\r\nfrom pathlib import Path\r\nfrom typing import Any, Dict\r\n\r\nimport pytorch_lightning as pl\r\nfrom pytorch_lightning.utilities import rank_zero_info\r\n\r\nfrom transformers import (\r\n AdamW,\r\n AutoConfig,\r\n AutoModel,\r\n AutoModelForPreTraining,\r\n AutoModelForQuestionAnswering,\r\n AutoModelForSeqaSeqLM,\r\n AutoModelForSequenceClassification,\r\n AutoModelForTokenClassification,\r\n AutoModelWithLMHead,\r\n AutoTokenizer,\r\n PretrainedConfig,\r\n PreTrainedTokenizer,\r\n)\r\nfrom transformers.optimization import (\r\n Adafactor,\r\n get_cosine_schedule_with_warmup,\r\n get_cosine_with_hard_restarts_schedule_with_warmup,\r\n get_linear_schedule_with_warmup,\r\n get_polynomial_decay_schedule_with_warmup,\r\n)\r\nfrom transformers.utils.versions import require_version\r\n\r\n\r\n_lowerCamelCase :\t\t\t\tAny \t\t\t=\t\t\t\t\t\tlogging.getLogger(__name__)\r\n\r\nrequire_version('''pytorch_lightning>=1.0.4''')\r\n\r\n_lowerCamelCase :\t\t\t\tAny \t\t\t=\t\t\t\t\t\t{\r\n '''base''': AutoModel,\r\n '''sequence-classification''': AutoModelForSequenceClassification,\r\n '''question-answering''': AutoModelForQuestionAnswering,\r\n '''pretraining''': AutoModelForPreTraining,\r\n '''token-classification''': AutoModelForTokenClassification,\r\n '''language-modeling''': AutoModelWithLMHead,\r\n '''summarization''': AutoModelForSeqaSeqLM,\r\n '''translation''': AutoModelForSeqaSeqLM,\r\n}\r\n\r\n\r\n# update this and the import above to support new schedulers from transformers.optimization\r\n_lowerCamelCase :\t\t\t\tOptional[int] \t\t\t=\t\t\t\t\t\t{\r\n '''linear''': get_linear_schedule_with_warmup,\r\n '''cosine''': get_cosine_schedule_with_warmup,\r\n '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,\r\n '''polynomial''': get_polynomial_decay_schedule_with_warmup,\r\n # '': get_constant_schedule, # not supported for now\r\n # '': get_constant_schedule_with_warmup, # not supported for now\r\n}\r\n_lowerCamelCase :\t\t\t\tstr \t\t\t=\t\t\t\t\t\tsorted(arg_to_scheduler.keys())\r\n_lowerCamelCase :\t\t\t\tDict \t\t\t=\t\t\t\t\t\t'''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}'''\r\n\r\n\r\nclass lowercase ( pl.LightningModule ):\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __init__( self\t\t\t\t: int\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: argparse.Namespace\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: int=None\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Union[str, Any]=\"base\"\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: int=None\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Optional[Any]=None\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Optional[Any]=None\t\t,\t\t\t\t\t\t\t**_UpperCamelCase\t\t\t\t: Dict\t\t,\t\t\t\t\t\t\t) ->\t\t\tList[Any]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\r\n\t\t\t\t\t\t\t\t\t\t\t\t# TODO: move to self.save_hyperparameters()\r\n\t\t\t\t\t\t\t\t\t\t\t\t# self.save_hyperparameters()\r\n\t\t\t\t\t\t\t\t\t\t\t\t# can also expand arguments into trainer signature for easier reading\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.save_hyperparameters(_UpperCamelCase )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = 0\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = Path(self.hparams.output_dir )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.hparams.cache_dir if self.hparams.cache_dir else None\r\n\t\t\t\t\t\t\t\t\t\t\t\tif config is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path\t\t,\t\t\t\t\t\t\t**({\"num_labels\": num_labels} if num_labels is not None else {})\t\t,\t\t\t\t\t\t\tcache_dir=_UpperCamelCase\t\t,\t\t\t\t\t\t\t**_UpperCamelCase\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = config\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = (\"encoder_layerdrop\", \"decoder_layerdrop\", \"dropout\", \"attention_dropout\")\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor p in extra_model_params:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif getattr(self.hparams\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t,\t\t\t\t\t\t\t_UpperCamelCase ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tassert hasattr(self.config\t\t,\t\t\t\t\t\t\t_UpperCamelCase ), F\"model config doesn't have a `{p}` attribute\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsetattr(self.config\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t,\t\t\t\t\t\t\tgetattr(self.hparams\t\t,\t\t\t\t\t\t\t_UpperCamelCase ) )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif tokenizer is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path\t\t,\t\t\t\t\t\t\tcache_dir=_UpperCamelCase\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = tokenizer\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = MODEL_MODES[mode]\r\n\t\t\t\t\t\t\t\t\t\t\t\tif model is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.model_type.from_pretrained(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t self.hparams.model_name_or_path\t\t,\t\t\t\t\t\t\tfrom_tf=bool(\".ckpt\" in self.hparams.model_name_or_path )\t\t,\t\t\t\t\t\t\tconfig=self.config\t\t,\t\t\t\t\t\t\tcache_dir=_UpperCamelCase\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = model\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Optional[Any]\t\t,\t\t\t\t\t\t\t*_UpperCamelCase\t\t\t\t: List[Any]\t\t,\t\t\t\t\t\t\t**_UpperCamelCase\t\t\t\t: Dict ) ->\t\t\tOptional[int]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.model_type.from_pretrained(*_UpperCamelCase\t\t,\t\t\t\t\t\t\t**_UpperCamelCase )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: str ) ->\t\t\tDict:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = arg_to_scheduler[self.hparams.lr_scheduler]\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = get_schedule_func(\r\n\t\t\t\t\t\t\t\t\t\t\t\t self.opt\t\t,\t\t\t\t\t\t\tnum_warmup_steps=self.hparams.warmup_steps\t\t,\t\t\t\t\t\t\tnum_training_steps=self.total_steps() )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = {\"scheduler\": scheduler, \"interval\": \"step\", \"frequency\": 1}\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn scheduler\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: int ) ->\t\t\tint:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.model\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = [\"bias\", \"LayerNorm.weight\"]\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = [\r\n\t\t\t\t\t\t\t\t\t\t\t\t {\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"params\": [\r\n\t\t\t\t\t\t\t\t\t\t\t\t p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay )\r\n\t\t\t\t\t\t\t\t\t\t\t\t ], # check this named paramters\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"weight_decay\": self.hparams.weight_decay,\r\n\t\t\t\t\t\t\t\t\t\t\t\t },\r\n\t\t\t\t\t\t\t\t\t\t\t\t {\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"params\": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )],\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"weight_decay\": 0.0,\r\n\t\t\t\t\t\t\t\t\t\t\t\t },\r\n\t\t\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.hparams.adafactor:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = Adafactor(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _UpperCamelCase\t\t,\t\t\t\t\t\t\tlr=self.hparams.learning_rate\t\t,\t\t\t\t\t\t\tscale_parameter=_UpperCamelCase\t\t,\t\t\t\t\t\t\trelative_step=_UpperCamelCase )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = AdamW(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _UpperCamelCase\t\t,\t\t\t\t\t\t\tlr=self.hparams.learning_rate\t\t,\t\t\t\t\t\t\teps=self.hparams.adam_epsilon )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = optimizer\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.get_lr_scheduler()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn [optimizer], [scheduler]\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Tuple\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Dict\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Tuple ) ->\t\t\tOptional[Any]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.validation_step(_UpperCamelCase\t\t,\t\t\t\t\t\t\t_UpperCamelCase )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Optional[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Union[str, Any] ) ->\t\t\tOptional[Any]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.validation_end(_UpperCamelCase )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Tuple ) ->\t\t\tint:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = max(1\t\t,\t\t\t\t\t\t\tself.hparams.gpus ) # TODO: consider num_tpu_cores\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn (self.dataset_size / effective_batch_size) * self.hparams.max_epochs\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Any\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Tuple ) ->\t\t\tOptional[Any]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif stage == \"test\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = len(self.test_dataloader().dataset )\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.get_dataloader(\"train\"\t\t,\t\t\t\t\t\t\tself.hparams.train_batch_size\t\t,\t\t\t\t\t\t\tshuffle=_UpperCamelCase )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = len(self.train_dataloader().dataset )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Dict\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: str\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: int\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: bool = False ) ->\t\t\tOptional[int]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\traise NotImplementedError(\"You must implement this for your task\" )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Any ) ->\t\t\tstr:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.train_loader\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: str ) ->\t\t\tint:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.get_dataloader(\"dev\"\t\t,\t\t\t\t\t\t\tself.hparams.eval_batch_size\t\t,\t\t\t\t\t\t\tshuffle=_UpperCamelCase )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Dict ) ->\t\t\tUnion[str, Any]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.get_dataloader(\"test\"\t\t,\t\t\t\t\t\t\tself.hparams.eval_batch_size\t\t,\t\t\t\t\t\t\tshuffle=_UpperCamelCase )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: List[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Any ) ->\t\t\tAny:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn os.path.join(\r\n\t\t\t\t\t\t\t\t\t\t\t\t self.hparams.data_dir\t\t,\t\t\t\t\t\t\t\"cached_{}_{}_{}\".format(\r\n\t\t\t\t\t\t\t\t\t\t\t\t _UpperCamelCase\t\t,\t\t\t\t\t\t\tlist(filter(_UpperCamelCase\t\t,\t\t\t\t\t\t\tself.hparams.model_name_or_path.split(\"/\" ) ) ).pop()\t\t,\t\t\t\t\t\t\tstr(self.hparams.max_seq_length )\t\t,\t\t\t\t\t\t\t)\t\t,\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t@pl.utilities.rank_zero_only\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Optional[int]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Dict[str, Any] ) ->\t\t\tNone:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.output_dir.joinpath(\"best_tfmr\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.step_count\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.model.save_pretrained(_UpperCamelCase )\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.tokenizer.save_pretrained(_UpperCamelCase )\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t@staticmethod\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( _UpperCamelCase\t\t\t\t: List[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Optional[int] ) ->\t\t\tAny:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--model_name_or_path\"\t\t,\t\t\t\t\t\t\tdefault=_UpperCamelCase\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\trequired=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Path to pretrained model or model identifier from huggingface.co/models\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--config_name\"\t\t,\t\t\t\t\t\t\tdefault=\"\"\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Pretrained config name or path if not the same as model_name\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--tokenizer_name\"\t\t,\t\t\t\t\t\t\tdefault=_UpperCamelCase\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Pretrained tokenizer name or path if not the same as model_name\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--cache_dir\"\t\t,\t\t\t\t\t\t\tdefault=str(Path(_UpperCamelCase ).parent / \"test_run\" / \"cache\" )\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Where do you want to store the pre-trained models downloaded from huggingface.co\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--encoder_layerdrop\"\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Encoder layer dropout probability (Optional). Goes into model.config\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--decoder_layerdrop\"\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Decoder layer dropout probability (Optional). Goes into model.config\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--dropout\"\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Dropout probability (Optional). Goes into model.config\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--attention_dropout\"\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Attention dropout probability (Optional). Goes into model.config\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--learning_rate\"\t\t,\t\t\t\t\t\t\tdefault=5e-5\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"The initial learning rate for Adam.\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"--lr_scheduler\"\t\t,\t\t\t\t\t\t\tdefault=\"linear\"\t\t,\t\t\t\t\t\t\tchoices=_UpperCamelCase\t\t,\t\t\t\t\t\t\tmetavar=_UpperCamelCase\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Learning rate scheduler\"\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--weight_decay\"\t\t,\t\t\t\t\t\t\tdefault=0.0\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Weight decay if we apply some.\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--adam_epsilon\"\t\t,\t\t\t\t\t\t\tdefault=1e-8\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Epsilon for Adam optimizer.\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--warmup_steps\"\t\t,\t\t\t\t\t\t\tdefault=0\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"Linear warmup over warmup_steps.\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--num_workers\"\t\t,\t\t\t\t\t\t\tdefault=4\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase\t\t,\t\t\t\t\t\t\thelp=\"kwarg passed to DataLoader\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--num_train_epochs\"\t\t,\t\t\t\t\t\t\tdest=\"max_epochs\"\t\t,\t\t\t\t\t\t\tdefault=3\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--train_batch_size\"\t\t,\t\t\t\t\t\t\tdefault=32\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--eval_batch_size\"\t\t,\t\t\t\t\t\t\tdefault=32\t\t,\t\t\t\t\t\t\ttype=_UpperCamelCase )\r\n\t\t\t\t\t\t\t\t\t\t\t\tparser.add_argument(\"--adafactor\"\t\t,\t\t\t\t\t\t\taction=\"store_true\" )\r\n\r\n\r\n\r\nclass lowercase ( pl.Callback ):\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Optional[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: List[str]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Any ) ->\t\t\tTuple:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif (\r\n\t\t\t\t\t\t\t\t\t\t\t\t trainer.is_global_zero and trainer.global_rank == 0\r\n\t\t\t\t\t\t\t\t\t\t\t\t): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpl_module.model.rag.retriever.init_retrieval() # better to use hook functions.\r\n\r\n\r\n\r\nclass lowercase ( pl.Callback ):\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Optional[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Dict\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: int ) ->\t\t\tOptional[int]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor name, param in pl_module.model.rag.named_parameters():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif param.grad is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint(_UpperCamelCase )\r\n\r\n\r\n\r\nclass lowercase ( pl.Callback ):\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Optional[int]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: Optional[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: int ) ->\t\t\tList[Any]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = trainer.lr_schedulers[0][\"scheduler\"]\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = {F\"lr_group_{i}\": lr for i, lr in enumerate(lr_scheduler.get_lr() )}\r\n\t\t\t\t\t\t\t\t\t\t\t\tpl_module.logger.log_metrics(_UpperCamelCase )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: str\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: pl.Trainer\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: pl.LightningModule ) ->\t\t\tList[str]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\trank_zero_info(\"***** Validation results *****\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = trainer.callback_metrics\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Log results\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor key in sorted(_UpperCamelCase ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif key not in [\"log\", \"progress_bar\"]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trank_zero_info(\"{} = {}\\n\".format(_UpperCamelCase\t\t,\t\t\t\t\t\t\tstr(metrics[key] ) ) )\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: List[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: pl.Trainer\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: pl.LightningModule ) ->\t\t\tDict:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\trank_zero_info(\"***** Test results *****\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = trainer.callback_metrics\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Log and save results to file\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = os.path.join(pl_module.hparams.output_dir\t\t,\t\t\t\t\t\t\t\"test_results.txt\" )\r\n\t\t\t\t\t\t\t\t\t\t\t\twith open(_UpperCamelCase\t\t,\t\t\t\t\t\t\t\"w\" ) as writer:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in sorted(_UpperCamelCase ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif key not in [\"log\", \"progress_bar\"]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trank_zero_info(\"{} = {}\\n\".format(_UpperCamelCase\t\t,\t\t\t\t\t\t\tstr(metrics[key] ) ) )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twriter.write(\"{} = {}\\n\".format(_UpperCamelCase\t\t,\t\t\t\t\t\t\tstr(metrics[key] ) ) )\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t__lowerCamelCase\t\t\t\t\t\t\t(UpperCAmelCase__ :\t\t\t\t\t\t\tstr ,\tUpperCAmelCase__ :\t\t\t\t\t\t\tTuple\t\t\t\t\t):\r\n\t\t\t\t\t# To allow all pl args uncomment the following line\r\n\t\t\t\t\t# parser = pl.Trainer.add_argparse_args(parser)\r\n\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t \"--output_dir\" ,\tdefault=str(Path(UpperCAmelCase__\t\t\t\t\t).parent / \"test_run\" / \"model_checkpoints\"\t\t\t\t\t) ,\ttype=UpperCAmelCase__ ,\thelp=\"The output directory where the model predictions and checkpoints will be written.\" ,\t)\r\n\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t \"--fp16\" ,\taction=\"store_true\" ,\thelp=\"Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit\" ,\t)\r\n\r\n\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t \"--fp16_opt_level\" ,\ttype=UpperCAmelCase__ ,\tdefault=\"O2\" ,\thelp=(\r\n\t\t\t\t\t \"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].\"\r\n\t\t\t\t\t \"See details at https://nvidia.github.io/apex/amp.html\"\r\n\t\t\t\t\t ) ,\t)\r\n\t\t\t\t\tparser.add_argument(\"--n_tpu_cores\" ,\tdest=\"tpu_cores\" ,\ttype=UpperCAmelCase__\t\t\t\t\t)\r\n\t\t\t\t\tparser.add_argument(\"--max_grad_norm\" ,\tdest=\"gradient_clip_val\" ,\tdefault=1.0 ,\ttype=UpperCAmelCase__ ,\thelp=\"Max gradient norm\"\t\t\t\t\t)\r\n\t\t\t\t\tparser.add_argument(\"--do_train\" ,\taction=\"store_true\" ,\thelp=\"Whether to run training.\"\t\t\t\t\t)\r\n\t\t\t\t\tparser.add_argument(\"--do_predict\" ,\taction=\"store_true\" ,\thelp=\"Whether to run predictions on the test set.\"\t\t\t\t\t)\r\n\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t \"--gradient_accumulation_steps\" ,\tdest=\"accumulate_grad_batches\" ,\ttype=UpperCAmelCase__ ,\tdefault=1 ,\thelp=\"Number of updates steps to accumulate before performing a backward/update pass.\" ,\t)\r\n\t\t\t\t\tparser.add_argument(\"--seed\" ,\ttype=UpperCAmelCase__ ,\tdefault=4_2 ,\thelp=\"random seed for initialization\"\t\t\t\t\t)\r\n\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t \"--data_dir\" ,\tdefault=str(Path(UpperCAmelCase__\t\t\t\t\t).parent / \"test_run\" / \"dummy-train-data\"\t\t\t\t\t) ,\ttype=UpperCAmelCase__ ,\thelp=\"The input data dir. Should contain the training files for the CoNLL-2003 NER task.\" ,\t)\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t__lowerCamelCase\t\t\t\t\t\t\t(UpperCAmelCase__ :\t\t\t\t\t\t\tBaseTransformer ,\tUpperCAmelCase__ :\t\t\t\t\t\t\targparse.Namespace ,\tUpperCAmelCase__ :\t\t\t\t\t\t\tOptional[int]=None ,\tUpperCAmelCase__ :\t\t\t\t\t\t\tDict=True ,\tUpperCAmelCase__ :\t\t\t\t\t\t\tList[str]=[] ,\tUpperCAmelCase__ :\t\t\t\t\t\t\tstr=None ,\tUpperCAmelCase__ :\t\t\t\t\t\t\tOptional[Any]=None ,\t**UpperCAmelCase__ :\t\t\t\t\t\t\tUnion[str, Any] ,\t):\r\n\t\t\t\t\tpl.seed_everything(args.seed\t\t\t\t\t)\r\n\r\n\t\t\t\t\t# init model\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = Path(model.hparams.output_dir\t\t\t\t\t)\r\n\t\t\t\t\todir.mkdir(exist_ok=UpperCAmelCase__\t\t\t\t\t)\r\n\r\n\t\t\t\t\t# add custom checkpoints\r\n\t\t\t\t\tif checkpoint_callback is None:\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = pl.callbacks.ModelCheckpoint(\r\n\t\t\t\t\t\t\t\t\t\t filepath=args.output_dir ,\tprefix=\"checkpoint\" ,\tmonitor=\"val_loss\" ,\tmode=\"min\" ,\tsave_top_k=1\t\t\t\t\t)\r\n\t\t\t\t\tif early_stopping_callback:\r\n\t\t\t\t\t\t\t\t\t\textra_callbacks.append(UpperCAmelCase__\t\t\t\t\t)\r\n\t\t\t\t\tif logging_callback is None:\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = LoggingCallback()\r\n\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = {}\r\n\r\n\t\t\t\t\tif args.fpaa:\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = 1_6\r\n\r\n\t\t\t\t\tif args.gpus > 1:\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = \"auto\"\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = \"ddp\"\r\n\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = args.accumulate_grad_batches\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = None\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = \"auto\"\r\n\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = pl.Trainer.from_argparse_args(\r\n\t\t\t\t\t UpperCAmelCase__ ,\tweights_summary=UpperCAmelCase__ ,\tcallbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] ,\tlogger=UpperCAmelCase__ ,\tval_check_interval=1 ,\tnum_sanity_val_steps=2 ,\t**UpperCAmelCase__ ,\t)\r\n\r\n\t\t\t\t\tif args.do_train:\r\n\t\t\t\t\t\t\t\t\t\ttrainer.fit(UpperCAmelCase__\t\t\t\t\t)\r\n\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tprint(\"RAG modeling tests with new set functions successfuly executed!\"\t\t\t\t\t)\r\n\t\t\t\t\treturn trainer\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":206,"string":"206"},"style_context":{"kind":"string","value":"from dataclasses import dataclass\r\nfrom typing import Tuple\r\n\r\nimport numpy as np\r\nimport torch\r\n\r\n\r\n@dataclass\r\nclass lowercase :\r\n\t\t\t\t\t\t\tlowercase__ : torch.Tensor # [batch_size x 3]\r\n\t\t\t\t\t\t\tlowercase__ : torch.Tensor # [batch_size x 3]\r\n\t\t\t\t\t\t\tlowercase__ : torch.Tensor # [batch_size x 3]\r\n\t\t\t\t\t\t\tlowercase__ : torch.Tensor # [batch_size x 3]\r\n\t\t\t\t\t\t\tlowercase__ : int\r\n\t\t\t\t\t\t\tlowercase__ : int\r\n\t\t\t\t\t\t\tlowercase__ : float\r\n\t\t\t\t\t\t\tlowercase__ : float\r\n\t\t\t\t\t\t\tlowercase__ : Tuple[int]\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: str ) ->\t\t\tDict:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tassert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0]\r\n\t\t\t\t\t\t\t\t\t\t\t\tassert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3\r\n\t\t\t\t\t\t\t\t\t\t\t\tassert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: int ) ->\t\t\tstr:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn torch.from_numpy(np.array([self.width, self.height]\t\t,\t\t\t\t\t\t\tdtype=np.floataa ) )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Tuple ) ->\t\t\tList[str]:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn torch.from_numpy(np.array([self.x_fov, self.y_fov]\t\t,\t\t\t\t\t\t\tdtype=np.floataa ) )\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Any ) ->\t\t\ttorch.Tensor:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = torch.arange(self.height * self.width )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = torch.stack(\r\n\t\t\t\t\t\t\t\t\t\t\t\t [\r\n\t\t\t\t\t\t\t\t\t\t\t\t pixel_indices % self.width,\r\n\t\t\t\t\t\t\t\t\t\t\t\t torch.div(_UpperCamelCase\t\t,\t\t\t\t\t\t\tself.width\t\t,\t\t\t\t\t\t\trounding_mode=\"trunc\" ),\r\n\t\t\t\t\t\t\t\t\t\t\t\t ]\t\t,\t\t\t\t\t\t\taxis=1\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn coords\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t@property\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Any ) ->\t\t\tTuple:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE ,\t\t\t\t*SCREAMING_SNAKE_CASE = self.shape\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = int(np.prod(_UpperCamelCase ) )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.get_image_coords()\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = torch.broadcast_to(coords.unsqueeze(0 )\t\t,\t\t\t\t\t\t\t[batch_size * inner_batch_size, *coords.shape] )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.get_camera_rays(_UpperCamelCase )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = rays.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\tinner_batch_size * self.height * self.width\t\t,\t\t\t\t\t\t\t2\t\t,\t\t\t\t\t\t\t3 )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn rays\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: Optional[int]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: torch.Tensor ) ->\t\t\ttorch.Tensor:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE ,\t\t\t\t*SCREAMING_SNAKE_CASE ,\t\t\t\tSCREAMING_SNAKE_CASE = coords.shape\r\n\t\t\t\t\t\t\t\t\t\t\t\tassert n_coords == 2\r\n\t\t\t\t\t\t\t\t\t\t\t\tassert batch_size == self.origin.shape[0]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = coords.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\t-1\t\t,\t\t\t\t\t\t\t2 )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.resolution()\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = self.fov()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = (flat.float() / (res - 1)) * 2 - 1\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = fracs * torch.tan(fov / 2 )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = fracs.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\t-1\t\t,\t\t\t\t\t\t\t2 )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = (\r\n\t\t\t\t\t\t\t\t\t\t\t\t self.z.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\t1\t\t,\t\t\t\t\t\t\t3 )\r\n\t\t\t\t\t\t\t\t\t\t\t\t + self.x.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\t1\t\t,\t\t\t\t\t\t\t3 ) * fracs[:, :, :1]\r\n\t\t\t\t\t\t\t\t\t\t\t\t + self.y.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\t1\t\t,\t\t\t\t\t\t\t3 ) * fracs[:, :, 1:]\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = directions / directions.norm(dim=-1\t\t,\t\t\t\t\t\t\tkeepdim=_UpperCamelCase )\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = torch.stack(\r\n\t\t\t\t\t\t\t\t\t\t\t\t [\r\n\t\t\t\t\t\t\t\t\t\t\t\t torch.broadcast_to(self.origin.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\t1\t\t,\t\t\t\t\t\t\t3 )\t\t,\t\t\t\t\t\t\t[batch_size, directions.shape[1], 3] ),\r\n\t\t\t\t\t\t\t\t\t\t\t\t directions,\r\n\t\t\t\t\t\t\t\t\t\t\t\t ]\t\t,\t\t\t\t\t\t\tdim=2\t\t,\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn rays.view(_UpperCamelCase\t\t,\t\t\t\t\t\t\t*_UpperCamelCase\t\t,\t\t\t\t\t\t\t2\t\t,\t\t\t\t\t\t\t3 )\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef \t\t__snake_case( self\t\t\t\t: List[Any]\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: int\t\t,\t\t\t\t\t\t\t_UpperCamelCase\t\t\t\t: int ) ->\t\t\t\"DifferentiableProjectiveCamera\":\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tassert width * self.height == height * self.width, \"The aspect ratio should not change.\"\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn DifferentiableProjectiveCamera(\r\n\t\t\t\t\t\t\t\t\t\t\t\t origin=self.origin\t\t,\t\t\t\t\t\t\tx=self.x\t\t,\t\t\t\t\t\t\ty=self.y\t\t,\t\t\t\t\t\t\tz=self.z\t\t,\t\t\t\t\t\t\twidth=_UpperCamelCase\t\t,\t\t\t\t\t\t\theight=_UpperCamelCase\t\t,\t\t\t\t\t\t\tx_fov=self.x_fov\t\t,\t\t\t\t\t\t\ty_fov=self.y_fov\t\t,\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t__lowerCamelCase\t\t\t\t\t\t\t(UpperCAmelCase__ :\t\t\t\t\t\t\tint\t\t\t\t\t):\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = []\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = []\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = []\r\n\t\t\t\t\tSCREAMING_SNAKE_CASE = []\r\n\t\t\t\t\tfor theta in np.linspace(0 ,\t2 * np.pi ,\tnum=2_0\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = np.array([np.sin(UpperCAmelCase__\t\t\t\t\t), np.cos(UpperCAmelCase__\t\t\t\t\t), -0.5]\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tz /= np.sqrt(np.sum(z**2\t\t\t\t\t)\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = -z * 4\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = np.array([np.cos(UpperCAmelCase__\t\t\t\t\t), -np.sin(UpperCAmelCase__\t\t\t\t\t), 0.0]\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE = np.cross(UpperCAmelCase__ ,\tUpperCAmelCase__\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\torigins.append(UpperCAmelCase__\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\txs.append(UpperCAmelCase__\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tys.append(UpperCAmelCase__\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tzs.append(UpperCAmelCase__\t\t\t\t\t)\r\n\t\t\t\t\treturn DifferentiableProjectiveCamera(\r\n\t\t\t\t\t origin=torch.from_numpy(np.stack(UpperCAmelCase__ ,\taxis=0\t\t\t\t\t)\t\t\t\t\t).float() ,\tx=torch.from_numpy(np.stack(UpperCAmelCase__ ,\taxis=0\t\t\t\t\t)\t\t\t\t\t).float() ,\ty=torch.from_numpy(np.stack(UpperCAmelCase__ ,\taxis=0\t\t\t\t\t)\t\t\t\t\t).float() ,\tz=torch.from_numpy(np.stack(UpperCAmelCase__ ,\taxis=0\t\t\t\t\t)\t\t\t\t\t).float() ,\twidth=UpperCAmelCase__ ,\theight=UpperCAmelCase__ ,\tx_fov=0.7 ,\ty_fov=0.7 ,\tshape=(1, len(UpperCAmelCase__\t\t\t\t\t)) ,\t)\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":206,"string":"206"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":250,"cells":{"code":{"kind":"string","value":"\rfrom collections import UserDict\rfrom typing import Union\r\rimport numpy as np\rimport requests\r\rfrom ..utils import (\r add_end_docstrings,\r logging,\r)\rfrom .audio_classification import ffmpeg_read\rfrom .base import PIPELINE_INIT_ARGS, Pipeline\r\r\r_UpperCAmelCase\t\t\t\t\t: Any = logging.get_logger(__name__)\r\r\r@add_end_docstrings(_SCREAMING_SNAKE_CASE )\rclass \t\t\t\tlowercase\t\t\t\t\t(\t\t_SCREAMING_SNAKE_CASE ):\r\r\r\r\t\tdef __init__( self\t\t\t\t, **A_ ) ->\t\t\t\t\tTuple:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tsuper().__init__(**A_ )\r\r\t\t\t\tif self.framework != \"pt\":\r\t\t\t\t\t\traise ValueError(F'''The {self.__class__} is only available in PyTorch.''' )\r\t\t\t\t# No specific FOR_XXX available yet\r\r\r\r\t\tdef __call__( self\t\t\t\t, A_\t\t\t\t, **A_ ) ->\t\t\t\t\tstr:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\treturn super().__call__(A_\t\t\t\t, **A_ )\r\r\r\r\t\tdef __UpperCamelCase ( self\t\t\t\t, **A_ ) ->\t\t\t\t\tUnion[str, Any]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= {}\r\t\t\t\tif \"candidate_labels\" in kwargs:\r\t\t\t\t\t\tUpperCamelCase\t\t= kwargs['candidate_labels']\r\t\t\t\tif \"hypothesis_template\" in kwargs:\r\t\t\t\t\t\tUpperCamelCase\t\t= kwargs['hypothesis_template']\r\r\t\t\t\treturn preprocess_params, {}, {}\r\r\r\r\t\tdef __UpperCamelCase ( self\t\t\t\t, A_\t\t\t\t, A_=None\t\t\t\t, A_=\"This is a sound of {}.\" ) ->\t\t\t\t\tTuple:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tif isinstance(A_\t\t\t\t, A_ ):\r\t\t\t\t\t\tif audio.startswith('http://' ) or audio.startswith('https://' ):\r\t\t\t\t\t\t\t\t# We need to actually check for a real protocol, otherwise it's impossible to use a local file\r\t\t\t\t\t\t\t\t# like http_huggingface_co.png\r\t\t\t\t\t\t\t\tUpperCamelCase\t\t= requests.get(A_ ).content\r\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\twith open(A_\t\t\t\t, 'rb' ) as f:\r\t\t\t\t\t\t\t\t\t\tUpperCamelCase\t\t= f.read()\r\r\t\t\t\tif isinstance(A_\t\t\t\t, A_ ):\r\t\t\t\t\t\tUpperCamelCase\t\t= ffmpeg_read(A_\t\t\t\t, self.feature_extractor.sampling_rate )\r\r\t\t\t\tif not isinstance(A_\t\t\t\t, np.ndarray ):\r\t\t\t\t\t\traise ValueError('We expect a numpy ndarray as input' )\r\t\t\t\tif len(audio.shape ) != 1:\r\t\t\t\t\t\traise ValueError('We expect a single channel audio input for ZeroShotAudioClassificationPipeline' )\r\r\t\t\t\tUpperCamelCase\t\t= self.feature_extractor(\r\t\t\t\t [audio]\t\t\t\t, sampling_rate=self.feature_extractor.sampling_rate\t\t\t\t, return_tensors='pt' )\r\t\t\t\tUpperCamelCase\t\t= candidate_labels\r\t\t\t\tUpperCamelCase\t\t= [hypothesis_template.format(A_ ) for x in candidate_labels]\r\t\t\t\tUpperCamelCase\t\t= self.tokenizer(A_\t\t\t\t, return_tensors=self.framework\t\t\t\t, padding=A_ )\r\t\t\t\tUpperCamelCase\t\t= [text_inputs]\r\t\t\t\treturn inputs\r\r\r\r\t\tdef __UpperCamelCase ( self\t\t\t\t, A_ ) ->\t\t\t\t\tList[str]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= model_inputs.pop('candidate_labels' )\r\t\t\t\tUpperCamelCase\t\t= model_inputs.pop('text_inputs' )\r\t\t\t\tif isinstance(text_inputs[0]\t\t\t\t, A_ ):\r\t\t\t\t\t\tUpperCamelCase\t\t= text_inputs[0]\r\t\t\t\telse:\r\t\t\t\t\t\t# Batching case.\r\t\t\t\t\t\tUpperCamelCase\t\t= text_inputs[0][0]\r\r\t\t\t\tUpperCamelCase\t\t= self.model(**A_\t\t\t\t, **A_ )\r\r\t\t\t\tUpperCamelCase\t\t= {\r\t\t\t\t 'candidate_labels': candidate_labels,\r\t\t\t\t 'logits': outputs.logits_per_audio,\r\t\t\t\t}\r\t\t\t\treturn model_outputs\r\r\r\r\t\tdef __UpperCamelCase ( self\t\t\t\t, A_ ) ->\t\t\t\t\tTuple:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= model_outputs.pop('candidate_labels' )\r\t\t\t\tUpperCamelCase\t\t= model_outputs['logits'][0]\r\r\t\t\t\tif self.framework == \"pt\":\r\t\t\t\t\t\tUpperCamelCase\t\t= logits.softmax(dim=0 )\r\t\t\t\t\t\tUpperCamelCase\t\t= probs.tolist()\r\t\t\t\telse:\r\t\t\t\t\t\traise ValueError('`tf` framework not supported.' )\r\r\t\t\t\tUpperCamelCase\t\t= [\r\t\t\t\t {'score': score, 'label': candidate_label}\r\t\t\t\t for score, candidate_label in sorted(zip(A_\t\t\t\t, A_ )\t\t\t\t, key=lambda A_ : -x[0] )\r\t\t\t\t]\r\t\t\t\treturn result\r"},"code_codestyle":{"kind":"number","value":222,"string":"222"},"style_context":{"kind":"string","value":"\rimport os\rimport tempfile\rimport unittest\rfrom pathlib import Path\r\rfrom transformers import AutoConfig, is_torch_available\rfrom transformers.testing_utils import require_torch, torch_device\r\r\rif is_torch_available():\r\t\t\t\t\tfrom transformers import PyTorchBenchmark, PyTorchBenchmarkArguments\r\r\r@require_torch\rclass \t\t\t\tlowercase\t\t\t\t\t(\t\tunittest.TestCase ):\r\r\r\r\t\tdef __UpperCamelCase ( self\t\t\t\t, A_ ) ->\t\t\t\t\tList[str]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tfor model_result in results.values():\r\t\t\t\t\t\tfor batch_size, sequence_length in zip(model_result['bs']\t\t\t\t, model_result['ss'] ):\r\t\t\t\t\t\t\t\tUpperCamelCase\t\t= model_result['result'][batch_size][sequence_length]\r\t\t\t\t\t\t\t\tself.assertIsNotNone(A_ )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tTuple:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_inference_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_inference_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tAny:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sgugger/tiny-distilbert-classification'\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, only_pretrain_model=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_inference_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_inference_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tAny:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, torchscript=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_inference_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_inference_result )\r\r\r\r\t\t@unittest.skipIf(torch_device == 'cpu'\t\t\t\t, 'Cant do half precision' )\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tList[str]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, fpaa=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_inference_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_inference_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tstr:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= AutoConfig.from_pretrained(A_ )\r\t\t\t\t# set architectures equal to `None`\r\t\t\t\tUpperCamelCase\t\t= None\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_\t\t\t\t, configs=[config] )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_inference_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_inference_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tList[str]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_train_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_train_result )\r\r\r\r\t\t@unittest.skipIf(torch_device == 'cpu'\t\t\t\t, 'Can\\'t do half precision' )\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tTuple:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, fpaa=A_\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_train_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_train_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tTuple:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= AutoConfig.from_pretrained(A_ )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_\t\t\t\t, configs=[config] )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_inference_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_inference_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tOptional[Any]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tinier_bart'\r\t\t\t\tUpperCamelCase\t\t= AutoConfig.from_pretrained(A_ )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_\t\t\t\t, configs=[config] )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_inference_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_inference_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tOptional[Any]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\tUpperCamelCase\t\t= AutoConfig.from_pretrained(A_ )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_\t\t\t\t, configs=[config] )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_train_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_train_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tAny:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tinier_bart'\r\t\t\t\tUpperCamelCase\t\t= AutoConfig.from_pretrained(A_ )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_\t\t\t\t, configs=[config] )\r\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\tself.check_results_dict_not_empty(results.time_train_result )\r\t\t\t\tself.check_results_dict_not_empty(results.memory_train_result )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tstr:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\t\t\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, save_to_csv=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, inference_time_csv_file=os.path.join(A_\t\t\t\t, 'inf_time.csv' )\t\t\t\t, train_memory_csv_file=os.path.join(A_\t\t\t\t, 'train_mem.csv' )\t\t\t\t, inference_memory_csv_file=os.path.join(A_\t\t\t\t, 'inf_mem.csv' )\t\t\t\t, train_time_csv_file=os.path.join(A_\t\t\t\t, 'train_time.csv' )\t\t\t\t, env_info_csv_file=os.path.join(A_\t\t\t\t, 'env.csv' )\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\t\t\tbenchmark.run()\r\t\t\t\t\t\tself.assertTrue(Path(os.path.join(A_\t\t\t\t, 'inf_time.csv' ) ).exists() )\r\t\t\t\t\t\tself.assertTrue(Path(os.path.join(A_\t\t\t\t, 'train_time.csv' ) ).exists() )\r\t\t\t\t\t\tself.assertTrue(Path(os.path.join(A_\t\t\t\t, 'inf_mem.csv' ) ).exists() )\r\t\t\t\t\t\tself.assertTrue(Path(os.path.join(A_\t\t\t\t, 'train_mem.csv' ) ).exists() )\r\t\t\t\t\t\tself.assertTrue(Path(os.path.join(A_\t\t\t\t, 'env.csv' ) ).exists() )\r\r\r\r\t\tdef __UpperCamelCase ( self ) ->\t\t\t\t\tList[Any]:\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\t\t\t\tUpperCamelCase\t\t= 'sshleifer/tiny-gpt2'\r\r\t\t\t\tdef _check_summary_is_not_empty(A_ ):\r\t\t\t\t\t\tself.assertTrue(hasattr(A_\t\t\t\t, 'sequential' ) )\r\t\t\t\t\t\tself.assertTrue(hasattr(A_\t\t\t\t, 'cumulative' ) )\r\t\t\t\t\t\tself.assertTrue(hasattr(A_\t\t\t\t, 'current' ) )\r\t\t\t\t\t\tself.assertTrue(hasattr(A_\t\t\t\t, 'total' ) )\r\r\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\t\t\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmarkArguments(\r\t\t\t\t\t\t models=[MODEL_ID]\t\t\t\t, training=A_\t\t\t\t, inference=A_\t\t\t\t, sequence_lengths=[8]\t\t\t\t, batch_sizes=[1]\t\t\t\t, log_filename=os.path.join(A_\t\t\t\t, 'log.txt' )\t\t\t\t, log_print=A_\t\t\t\t, trace_memory_line_by_line=A_\t\t\t\t, multi_process=A_\t\t\t\t, )\r\t\t\t\t\t\tUpperCamelCase\t\t= PyTorchBenchmark(A_ )\r\t\t\t\t\t\tUpperCamelCase\t\t= benchmark.run()\r\t\t\t\t\t\t_check_summary_is_not_empty(result.inference_summary )\r\t\t\t\t\t\t_check_summary_is_not_empty(result.train_summary )\r\t\t\t\t\t\tself.assertTrue(Path(os.path.join(A_\t\t\t\t, 'log.txt' ) ).exists() )\r"},"style_context_codestyle":{"kind":"number","value":222,"string":"222"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":251,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\nfrom collections.abc import Callable\r\n\r\nimport numpy as np\r\n\r\n\r\n\r\ndef _lowerCAmelCase\t( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase\t\t\t\t) -> np.ndarray:\r\n\r\n\r\n\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\tsnake_case__ :\t\t\t\tList[Any]\t\t\t\t\t\t\t= int(np.ceil((x_end - xa) / step_size\t\t\t\t)\t\t\t\t)\r\n\t\t\t\tsnake_case__ :\t\t\t\tList[str]\t\t\t\t\t\t\t= np.zeros((n + 1,)\t\t\t\t)\r\n\t\t\t\tsnake_case__ :\t\t\t\tAny\t\t\t\t\t\t\t= ya\r\n\t\t\t\tsnake_case__ :\t\t\t\tList[Any]\t\t\t\t\t\t\t= xa\r\n\r\n\t\t\t\tfor k in range(__lowerCAmelCase\t\t\t\t):\r\n\t\t\t\t\t\t\t\tsnake_case__ :\t\t\t\tList[Any]\t\t\t\t\t\t\t= y[k] + step_size * ode_func(__lowerCAmelCase , y[k]\t\t\t\t)\r\n\t\t\t\t\t\t\t\tx += step_size\r\n\r\n\t\t\t\treturn y\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\timport doctest\r\n\r\n\t\t\t\tdoctest.testmod()\r\n\r\n"},"code_codestyle":{"kind":"number","value":44,"string":"44"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\nimport os\r\nimport unittest\r\n\r\nfrom transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer\r\n\r\nfrom ...test_tokenization_common import TokenizerTesterMixin\r\n\r\n\r\nclass \t\t\t\ta\t\t\t\t\t\t\t( __lowerCamelCase ,\t\t\t\t\t\t\tunittest.TestCase ):\r\n\t\t__lowerCAmelCase : Dict \t\t\t\t\t\t\t= TransfoXLTokenizer\r\n\t\t__lowerCAmelCase : Union[str, Any] \t\t\t\t\t\t\t= False\r\n\t\t__lowerCAmelCase : List[str] \t\t\t\t\t\t\t= False\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:Union[str, Any] ):\r\n\t\t\t\t\t\tsuper().setUp()\r\n\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tOptional[int]\t\t\t\t\t\t\t= [\r\n\t\t\t\t\t\t '''''',\r\n\t\t\t\t\t\t '''[CLS]''',\r\n\t\t\t\t\t\t '''[SEP]''',\r\n\t\t\t\t\t\t '''want''',\r\n\t\t\t\t\t\t '''unwanted''',\r\n\t\t\t\t\t\t '''wa''',\r\n\t\t\t\t\t\t '''un''',\r\n\t\t\t\t\t\t '''running''',\r\n\t\t\t\t\t\t ''',''',\r\n\t\t\t\t\t\t '''low''',\r\n\t\t\t\t\t\t '''l''',\r\n\t\t\t\t\t\t]\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tOptional[Any]\t\t\t\t\t\t\t= os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['''vocab_file'''] )\r\n\t\t\t\t\t\twith open(self.vocab_file ,'''w''' ,encoding='''utf-8''' ) as vocab_writer:\r\n\t\t\t\t\t\t\t\t\t\tvocab_writer.write(''''''.join([x + '''\\n''' for x in vocab_tokens] ) )\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:int ,**__lowercase\t\t\t\t\t:Any ):\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tstr\t\t\t\t\t\t\t= True\r\n\t\t\t\t\t\treturn TransfoXLTokenizer.from_pretrained(self.tmpdirname ,**__lowercase )\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:int ,__lowercase\t\t\t\t\t:Optional[int] ):\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tint\t\t\t\t\t\t\t= ''' UNwanted , running'''\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tList[Any]\t\t\t\t\t\t\t= ''' unwanted, running'''\r\n\t\t\t\t\t\treturn input_text, output_text\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:Union[str, Any] ):\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tOptional[Any]\t\t\t\t\t\t\t= TransfoXLTokenizer(vocab_file=self.vocab_file ,lower_case=__lowercase )\r\n\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tTuple\t\t\t\t\t\t\t= tokenizer.tokenize(''' UNwanted , running''' )\r\n\t\t\t\t\t\tself.assertListEqual(__lowercase ,['''''', '''unwanted''', ''',''', '''running'''] )\r\n\r\n\t\t\t\t\t\tself.assertListEqual(tokenizer.convert_tokens_to_ids(__lowercase ) ,[0, 4, 8, 7] )\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:Union[str, Any] ):\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tList[Any]\t\t\t\t\t\t\t= TransfoXLTokenizer(lower_case=__lowercase )\r\n\r\n\t\t\t\t\t\tself.assertListEqual(\r\n\t\t\t\t\t\t tokenizer.tokenize(''' \\tHeLLo ! how \\n Are yoU ? ''' ) ,['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] )\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:Tuple ):\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tOptional[Any]\t\t\t\t\t\t\t= TransfoXLTokenizer(lower_case=__lowercase )\r\n\r\n\t\t\t\t\t\tself.assertListEqual(\r\n\t\t\t\t\t\t tokenizer.tokenize(''' \\tHeLLo ! how \\n Are yoU ? ''' ) ,['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:Optional[int] ):\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tAny\t\t\t\t\t\t\t= TransfoXLTokenizer(lower_case=__lowercase )\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tList[str]\t\t\t\t\t\t\t= '''Hello (bracket) and side-scrolled [and] Henry\\'s $5,000 with 3.34 m. What\\'s up!?'''\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t= [\r\n\t\t\t\t\t\t '''Hello''',\r\n\t\t\t\t\t\t '''(''',\r\n\t\t\t\t\t\t '''bracket''',\r\n\t\t\t\t\t\t ''')''',\r\n\t\t\t\t\t\t '''and''',\r\n\t\t\t\t\t\t '''side''',\r\n\t\t\t\t\t\t '''@-@''',\r\n\t\t\t\t\t\t '''scrolled''',\r\n\t\t\t\t\t\t '''[''',\r\n\t\t\t\t\t\t '''and''',\r\n\t\t\t\t\t\t ''']''',\r\n\t\t\t\t\t\t '''Henry''',\r\n\t\t\t\t\t\t '''\\'s''',\r\n\t\t\t\t\t\t '''$''',\r\n\t\t\t\t\t\t '''5''',\r\n\t\t\t\t\t\t '''@,@''',\r\n\t\t\t\t\t\t '''000''',\r\n\t\t\t\t\t\t '''with''',\r\n\t\t\t\t\t\t '''3''',\r\n\t\t\t\t\t\t '''@.@''',\r\n\t\t\t\t\t\t '''34''',\r\n\t\t\t\t\t\t '''m''',\r\n\t\t\t\t\t\t '''.''',\r\n\t\t\t\t\t\t '''What''',\r\n\t\t\t\t\t\t '''\\'s''',\r\n\t\t\t\t\t\t '''up''',\r\n\t\t\t\t\t\t '''!''',\r\n\t\t\t\t\t\t '''?''',\r\n\t\t\t\t\t\t]\r\n\r\n\t\t\t\t\t\tself.assertListEqual(tokenizer.tokenize(__lowercase ) ,__lowercase )\r\n\r\n\t\t\t\t\t\tself.assertEqual(tokenizer.convert_tokens_to_string(__lowercase ) ,__lowercase )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\tdef __lowerCamelCase (\t\t\t\t\tself\t\t\t\t\t:Optional[Any] ):\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tAny\t\t\t\t\t\t\t= self.get_tokenizer()\r\n\t\t\t\t\t\tsnake_case__ :\t\t\t\tOptional[Any]\t\t\t\t\t\t\t= len(__lowercase )\r\n\r\n\t\t\t\t\t\ttokenizer.add_tokens(['''new1''', '''new2'''] )\r\n\t\t\t\t\t\ttokenizer.move_added_token('''new1''' ,1 )\r\n\r\n\t\t\t\t\t\t# Check that moved token is not copied (duplicate)\r\n\t\t\t\t\t\tself.assertEqual(len(__lowercase ) ,original_len + 2 )\r\n\t\t\t\t\t\t# Check that token is moved to specified id\r\n\t\t\t\t\t\tself.assertEqual(tokenizer.encode('''new1''' ) ,[1] )\r\n\t\t\t\t\t\tself.assertEqual(tokenizer.decode([1] ) ,'''new1''' )\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":44,"string":"44"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":252,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nimport math\r\n\r\nimport qiskit\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t__lowerCamelCase\t\t\t\t( A__ = 1 ,\t\t\t\t\t\tA__ = 1 ,\t\t\t\t\t\tA__ = 1 ) ->\tqiskit.result.counts.Counts:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n if (\r\n isinstance(A__ ,\t\t\t\t\t\tA__ )\r\n or isinstance(A__ ,\t\t\t\t\t\tA__ )\r\n or isinstance(A__ ,\t\t\t\t\t\tA__ )\r\n ):\r\n raise TypeError('inputs must be integers.' )\r\n\r\n if (input_a < 0) or (input_a < 0) or (carry_in < 0):\r\n raise ValueError('inputs must be positive.' )\r\n\r\n if (\r\n (math.floor(A__ ) != input_a)\r\n or (math.floor(A__ ) != input_a)\r\n or (math.floor(A__ ) != carry_in)\r\n ):\r\n raise ValueError('inputs must be exact integers.' )\r\n\r\n if (input_a > 2) or (input_a > 2) or (carry_in > 2):\r\n raise ValueError('inputs must be less or equal to 2.' )\r\n\r\n # build registers\r\n UpperCamelCase\t\t\t\t\t= qiskit.QuantumRegister(4 ,\t\t\t\t\t\t'qr' )\r\n UpperCamelCase\t\t\t\t\t= qiskit.ClassicalRegister(2 ,\t\t\t\t\t\t'cr' )\r\n # list the entries\r\n UpperCamelCase\t\t\t\t\t= [input_a, input_a, carry_in]\r\n\r\n UpperCamelCase\t\t\t\t\t= qiskit.QuantumCircuit(A__ ,\t\t\t\t\t\tA__ )\r\n\r\n for i in range(0 ,\t\t\t\t\t\t3 ):\r\n if entry[i] == 2:\r\n quantum_circuit.h(A__ ) # for hadamard entries\r\n elif entry[i] == 1:\r\n quantum_circuit.x(A__ ) # for 1 entries\r\n elif entry[i] == 0:\r\n quantum_circuit.i(A__ ) # for 0 entries\r\n\r\n # build the circuit\r\n quantum_circuit.ccx(0 ,\t\t\t\t\t\t1 ,\t\t\t\t\t\t3 ) # ccx = toffoli gate\r\n quantum_circuit.cx(0 ,\t\t\t\t\t\t1 )\r\n quantum_circuit.ccx(1 ,\t\t\t\t\t\t2 ,\t\t\t\t\t\t3 )\r\n quantum_circuit.cx(1 ,\t\t\t\t\t\t2 )\r\n quantum_circuit.cx(0 ,\t\t\t\t\t\t1 )\r\n\r\n quantum_circuit.measure([2, 3] ,\t\t\t\t\t\tA__ ) # measure the last two qbits\r\n\r\n UpperCamelCase\t\t\t\t\t= qiskit.Aer.get_backend('aer_simulator' )\r\n UpperCamelCase\t\t\t\t\t= qiskit.execute(A__ ,\t\t\t\t\t\tA__ ,\t\t\t\t\t\tshots=1_000 )\r\n\r\n return job.result().get_counts(A__ )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(f'''Total sum count for state is: {quantum_full_adder(1, 1, 1)}''')\r\n\r\n"},"code_codestyle":{"kind":"number","value":28,"string":"28"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nfrom io import BytesIO\r\nfrom typing import List, Union\r\n\r\nimport requests\r\n\r\nfrom ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends\r\nfrom .base import PIPELINE_INIT_ARGS, Pipeline\r\n\r\n\r\nif is_decord_available():\r\n import numpy as np\r\n from decord import VideoReader\r\n\r\n\r\nif is_torch_available():\r\n from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING\r\n\r\n_lowerCamelCase\t: Any \t=\tlogging.get_logger(__name__)\r\n\r\n@add_end_docstrings(_a\t\t)\r\nclass SCREAMING_SNAKE_CASE ( _a\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n def __init__( self :\t\t\t\t\tAny ,\t\t\t\t\t\t*UpperCamelCase__ :\t\t\t\t\tDict ,\t\t\t\t\t\t**UpperCamelCase__ :\t\t\t\t\tUnion[str, Any] ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n super().__init__(*UpperCamelCase__ ,\t\t\t\t\t\t**UpperCamelCase__ )\r\n requires_backends(self ,\t\t\t\t\t\t'decord' )\r\n self.check_model_type(UpperCamelCase__ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n def A ( self :\t\t\t\t\tOptional[int] ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tOptional[int]=None ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tOptional[Any]=None ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tOptional[Any]=None ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n UpperCamelCase\t\t\t\t\t= {}\r\n if frame_sampling_rate is not None:\r\n UpperCamelCase\t\t\t\t\t= frame_sampling_rate\r\n if num_frames is not None:\r\n UpperCamelCase\t\t\t\t\t= num_frames\r\n\r\n UpperCamelCase\t\t\t\t\t= {}\r\n if top_k is not None:\r\n UpperCamelCase\t\t\t\t\t= top_k\r\n return preprocess_params, {}, postprocess_params\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __call__( self :\t\t\t\t\tList[str] ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tUnion[str, List[str]] ,\t\t\t\t\t\t**UpperCamelCase__ :\t\t\t\t\tDict ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n return super().__call__(UpperCamelCase__ ,\t\t\t\t\t\t**UpperCamelCase__ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n def A ( self :\t\t\t\t\tTuple ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tUnion[str, Any] ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tTuple=None ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tTuple=1 ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n if num_frames is None:\r\n UpperCamelCase\t\t\t\t\t= self.model.config.num_frames\r\n\r\n if video.startswith('http://' ) or video.startswith('https://' ):\r\n UpperCamelCase\t\t\t\t\t= BytesIO(requests.get(UpperCamelCase__ ).content )\r\n\r\n UpperCamelCase\t\t\t\t\t= VideoReader(UpperCamelCase__ )\r\n videoreader.seek(0 )\r\n\r\n UpperCamelCase\t\t\t\t\t= 0\r\n UpperCamelCase\t\t\t\t\t= num_frames * frame_sampling_rate - 1\r\n UpperCamelCase\t\t\t\t\t= np.linspace(UpperCamelCase__ ,\t\t\t\t\t\tUpperCamelCase__ ,\t\t\t\t\t\tnum=UpperCamelCase__ ,\t\t\t\t\t\tdtype=np.intaa )\r\n\r\n UpperCamelCase\t\t\t\t\t= videoreader.get_batch(UpperCamelCase__ ).asnumpy()\r\n UpperCamelCase\t\t\t\t\t= list(UpperCamelCase__ )\r\n\r\n UpperCamelCase\t\t\t\t\t= self.image_processor(UpperCamelCase__ ,\t\t\t\t\t\treturn_tensors=self.framework )\r\n return model_inputs\r\n\r\n\r\n\r\n\r\n\r\n\r\n def A ( self :\t\t\t\t\tUnion[str, Any] ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tList[str] ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n UpperCamelCase\t\t\t\t\t= self.model(**UpperCamelCase__ )\r\n return model_outputs\r\n\r\n\r\n\r\n\r\n\r\n\r\n def A ( self :\t\t\t\t\tint ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tstr ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tList[Any]=5 ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n if top_k > self.model.config.num_labels:\r\n UpperCamelCase\t\t\t\t\t= self.model.config.num_labels\r\n\r\n if self.framework == \"pt\":\r\n UpperCamelCase\t\t\t\t\t= model_outputs.logits.softmax(-1 )[0]\r\n UpperCamelCase\t\t\t\t, UpperCamelCase\t\t\t\t\t= probs.topk(UpperCamelCase__ )\r\n else:\r\n raise ValueError(f\"\"\"Unsupported framework: {self.framework}\"\"\" )\r\n\r\n UpperCamelCase\t\t\t\t\t= scores.tolist()\r\n UpperCamelCase\t\t\t\t\t= ids.tolist()\r\n return [{\"score\": score, \"label\": self.model.config.idalabel[_id]} for score, _id in zip(UpperCamelCase__ ,\t\t\t\t\t\tUpperCamelCase__ )]\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":28,"string":"28"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":253,"cells":{"code":{"kind":"string","value":"\n\n\n\nimport gc\nimport unittest\n\nimport numpy as np\nimport torch\nfrom transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer\n\nfrom diffusers import (\n AutoencoderKL,\n DDIMScheduler,\n StableDiffusionSAGPipeline,\n UNetaDConditionModel,\n)\nfrom diffusers.utils import slow, torch_device\nfrom diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu\n\nfrom ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS\nfrom ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin\n\n\nenable_full_determinism()\n\n\n\n\n\nclass lowerCAmelCase_\t\t( _UpperCAmelCase\t, _UpperCAmelCase\t, unittest.TestCase\t\t\t\t\t\t\t):\n UpperCAmelCase__ : Any \t\t\t\t\t= StableDiffusionSAGPipeline\n UpperCAmelCase__ : Union[str, Any] \t\t\t\t\t= TEXT_TO_IMAGE_PARAMS\n UpperCAmelCase__ : List[Any] \t\t\t\t\t= TEXT_TO_IMAGE_BATCH_PARAMS\n UpperCAmelCase__ : Any \t\t\t\t\t= TEXT_TO_IMAGE_IMAGE_PARAMS\n UpperCAmelCase__ : List[str] \t\t\t\t\t= TEXT_TO_IMAGE_IMAGE_PARAMS\n UpperCAmelCase__ : Union[str, Any] \t\t\t\t\t= False\n def snake_case_\t( self\t)\t\t\t\t\t->\t\tstr:\n torch.manual_seed(0\t)\n UpperCamelCase : str\t\t\t\t\t\t = UNetaDConditionModel(\n block_out_channels=(32, 64), layers_per_block=2, sample_size=32, in_channels=4, out_channels=4, down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D'), up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D'), cross_attention_dim=32, )\n UpperCamelCase : Any\t\t\t\t\t\t = DDIMScheduler(\n beta_start=0.0_00_85, beta_end=0.0_12, beta_schedule='scaled_linear', clip_sample=lowercase_, set_alpha_to_one=lowercase_, )\n torch.manual_seed(0\t)\n UpperCamelCase : Dict\t\t\t\t\t\t = AutoencoderKL(\n block_out_channels=[32, 64], in_channels=3, out_channels=3, down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'], up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'], latent_channels=4, )\n torch.manual_seed(0\t)\n UpperCamelCase : Any\t\t\t\t\t\t = CLIPTextConfig(\n bos_token_id=0, eos_token_id=2, hidden_size=32, intermediate_size=37, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1000, )\n UpperCamelCase : Dict\t\t\t\t\t\t = CLIPTextModel(lowercase_\t)\n UpperCamelCase : int\t\t\t\t\t\t = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'\t)\n\n UpperCamelCase : Dict\t\t\t\t\t\t = {\n \"\"\"unet\"\"\": unet,\n \"\"\"scheduler\"\"\": scheduler,\n \"\"\"vae\"\"\": vae,\n \"\"\"text_encoder\"\"\": text_encoder,\n \"\"\"tokenizer\"\"\": tokenizer,\n \"\"\"safety_checker\"\"\": None,\n \"\"\"feature_extractor\"\"\": None,\n }\n return components\n def snake_case_\t( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=0\t)\t\t\t\t\t->\t\tList[str]:\n if str(lowercase_\t).startswith('mps'\t):\n UpperCamelCase : Tuple\t\t\t\t\t\t = torch.manual_seed(lowercase_\t)\n else:\n UpperCamelCase : str\t\t\t\t\t\t = torch.Generator(device=lowercase_\t).manual_seed(lowercase_\t)\n UpperCamelCase : Any\t\t\t\t\t\t = {\n \"\"\"prompt\"\"\": \"\"\".\"\"\",\n \"\"\"generator\"\"\": generator,\n \"\"\"num_inference_steps\"\"\": 2,\n \"\"\"guidance_scale\"\"\": 1.0,\n \"\"\"sag_scale\"\"\": 1.0,\n \"\"\"output_type\"\"\": \"\"\"numpy\"\"\",\n }\n return inputs\n\n\n\n\n\n\n def snake_case_\t( self\t)\t\t\t\t\t->\t\tUnion[str, Any]:\n super().test_inference_batch_single_identical(expected_max_diff=3e-3\t)\n\n\n\n\n\n\n@slow\n@require_torch_gpu\nclass lowerCAmelCase_\t\t( unittest.TestCase\t\t\t\t\t\t\t):\n def snake_case_\t( self\t)\t\t\t\t\t->\t\tDict:\n # clean up the VRAM after each test\n super().tearDown()\n gc.collect()\n torch.cuda.empty_cache()\n def snake_case_\t( self\t)\t\t\t\t\t->\t\tList[Any]:\n UpperCamelCase : str\t\t\t\t\t\t = StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'\t)\n UpperCamelCase : Optional[int]\t\t\t\t\t\t = sag_pipe.to(lowercase_\t)\n sag_pipe.set_progress_bar_config(disable=lowercase_\t)\n\n UpperCamelCase : str\t\t\t\t\t\t = \"\"\".\"\"\"\n UpperCamelCase : List[Any]\t\t\t\t\t\t = torch.manual_seed(0\t)\n UpperCamelCase : int\t\t\t\t\t\t = sag_pipe(\n [prompt], generator=lowercase_, guidance_scale=7.5, sag_scale=1.0, num_inference_steps=20, output_type='np'\t)\n\n UpperCamelCase : Dict\t\t\t\t\t\t = output.images\n\n UpperCamelCase : Union[str, Any]\t\t\t\t\t\t = image[0, -3:, -3:, -1]\n\n assert image.shape == (1, 512, 512, 3)\n UpperCamelCase : List[str]\t\t\t\t\t\t = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]\t)\n\n assert np.abs(image_slice.flatten() - expected_slice\t).max() < 5e-2\n def snake_case_\t( self\t)\t\t\t\t\t->\t\tint:\n UpperCamelCase : Tuple\t\t\t\t\t\t = StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'\t)\n UpperCamelCase : Tuple\t\t\t\t\t\t = sag_pipe.to(lowercase_\t)\n sag_pipe.set_progress_bar_config(disable=lowercase_\t)\n\n UpperCamelCase : str\t\t\t\t\t\t = \"\"\".\"\"\"\n UpperCamelCase : Any\t\t\t\t\t\t = torch.manual_seed(0\t)\n UpperCamelCase : Optional[int]\t\t\t\t\t\t = sag_pipe(\n [prompt], generator=lowercase_, guidance_scale=7.5, sag_scale=1.0, num_inference_steps=20, output_type='np'\t)\n\n UpperCamelCase : str\t\t\t\t\t\t = output.images\n\n UpperCamelCase : Optional[Any]\t\t\t\t\t\t = image[0, -3:, -3:, -1]\n\n assert image.shape == (1, 512, 512, 3)\n UpperCamelCase : Any\t\t\t\t\t\t = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]\t)\n\n assert np.abs(image_slice.flatten() - expected_slice\t).max() < 5e-2\n\n\n\n\n\n\n def snake_case_\t( self\t)\t\t\t\t\t->\t\tint:\n UpperCamelCase : List[str]\t\t\t\t\t\t = StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'\t)\n UpperCamelCase : Union[str, Any]\t\t\t\t\t\t = sag_pipe.to(lowercase_\t)\n sag_pipe.set_progress_bar_config(disable=lowercase_\t)\n\n UpperCamelCase : Optional[Any]\t\t\t\t\t\t = \"\"\".\"\"\"\n UpperCamelCase : List[str]\t\t\t\t\t\t = torch.manual_seed(0\t)\n UpperCamelCase : int\t\t\t\t\t\t = sag_pipe(\n [prompt], width=768, height=512, generator=lowercase_, guidance_scale=7.5, sag_scale=1.0, num_inference_steps=20, output_type='np', )\n\n UpperCamelCase : int\t\t\t\t\t\t = output.images\n\n assert image.shape == (1, 512, 768, 3)\n\n\n\n"},"code_codestyle":{"kind":"number","value":371,"string":"371"},"style_context":{"kind":"string","value":"\n\n\n\nimport argparse\nimport shlex\n\nimport runhouse as rh\n\n\nif __name__ == \"__main__\":\n # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access\n # setup instructions, if using on-demand hardware\n\n # If user passes --user --host --key_path , fill them in as BYO cluster\n # If user passes --instance --provider , fill them in as on-demand cluster\n # Throw an error if user passes both BYO and on-demand cluster args\n # Otherwise, use default values\n __UpperCAmelCase\t =\targparse.ArgumentParser()\n parser.add_argument('''--user''', type=str, default='''ubuntu''')\n parser.add_argument('''--host''', type=str, default='''localhost''')\n parser.add_argument('''--key_path''', type=str, default=None)\n parser.add_argument('''--instance''', type=str, default='''V100:1''')\n parser.add_argument('''--provider''', type=str, default='''cheapest''')\n parser.add_argument('''--use_spot''', type=bool, default=False)\n parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''')\n __UpperCAmelCase , __UpperCAmelCase\t =\tparser.parse_known_args()\n if args.host != \"localhost\":\n if args.instance != \"V100:1\" or args.provider != \"cheapest\":\n raise ValueError('''Cannot specify both BYO and on-demand cluster args''')\n __UpperCAmelCase\t =\trh.cluster(\n name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path}\n )\n else:\n __UpperCAmelCase\t =\trh.cluster(\n name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot\n )\n __UpperCAmelCase\t =\targs.example.rsplit('''/''', 1)[0]\n\n # Set up remote environment\n cluster.install_packages(['''pip:./''']) # Installs transformers from local source\n # Note transformers is copied into the home directory on the remote machine, so we can install from there\n cluster.run([F\"\"\"pip install -r transformers/examples/{example_dir}/requirements.txt\"\"\"])\n cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117'''])\n\n # Run example. You can bypass the CLI wrapper and paste your own code here.\n cluster.run([F\"\"\"python transformers/examples/{args.example} {\" \".join(shlex.quote(arg) for arg in unknown)}\"\"\"])\n\n # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI):\n # from my_script... import train\n # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard']\n # launch_train_gpu = rh.function(fn=train,\n # system=gpu,\n # reqs=reqs,\n # name='train_bert_glue')\n #\n # We can pass in arguments just like we would to a function:\n # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16\n # stream_logs=True)\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":103,"string":"103"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":254,"cells":{"code":{"kind":"string","value":"'''simple docstring'''\r\r\r\r\rdef __lowerCAmelCase (\t\t\t\t\t\t\tUpperCamelCase__\t\t\t\t)\t-> int:\r if not isinstance(UpperCamelCase__\t\t\t\t, UpperCamelCase__\t\t\t\t):\r raise ValueError('''Input must be an integer'''\t\t\t\t)\r if input_num <= 0:\r raise ValueError('''Input must be positive'''\t\t\t\t)\r return sum(\r divisor for divisor in range(1\t\t\t\t, input_num // 2 + 1\t\t\t\t) if input_num % divisor == 0\t\t\t\t)\r\r\rif __name__ == \"__main__\":\r import doctest\r\r doctest.testmod()\r"},"code_codestyle":{"kind":"number","value":67,"string":"67"},"style_context":{"kind":"string","value":"'''simple docstring'''\r\r\r\r\rimport torch\rfrom transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel\r\r\r\r\rclass a__ ( UpperCAmelCase__ ):\r lowerCamelCase : Dict\t\t\t\t\t\t\t=\"M-CLIP\"\r\r\r\r\r\r\r def __init__( self\t\t:\t\tTuple ,\t\t\t\ta\t\t:\t\tOptional[int]=10_24 ,\t\t\t\ta\t\t:\t\tTuple=7_68 ,\t\t\t\t**a\t\t:\t\tList[str] ):\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r\r __lowerCamelCase\t\t= transformerDimSize\r __lowerCamelCase\t\t= imageDimSize\r super().__init__(**a )\r\r\r\r\rclass a__ ( UpperCAmelCase__ ):\r lowerCamelCase : Optional[Any]\t\t\t\t\t\t\t=MCLIPConfig\r\r\r\r\r\r\r def __init__( self\t\t:\t\tstr ,\t\t\t\ta\t\t:\t\tList[Any] ,\t\t\t\t*a\t\t:\t\tDict ,\t\t\t\t**a\t\t:\t\tstr ):\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r\r super().__init__(a ,\t\t\t\t*a ,\t\t\t\t**a )\r __lowerCamelCase\t\t= XLMRobertaModel(a )\r __lowerCamelCase\t\t= torch.nn.Linear(\r in_features=config.transformerDimensions ,\t\t\t\tout_features=config.numDims )\r\r\r\r\r\r\r def SCREAMING_SNAKE_CASE__ ( self\t\t:\t\tUnion[str, Any] ,\t\t\t\ta\t\t:\t\tint ,\t\t\t\ta\t\t:\t\tList[Any] ):\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r\r __lowerCamelCase\t\t= self.transformer(input_ids=a ,\t\t\t\tattention_mask=a )[0]\r __lowerCamelCase\t\t= (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None]\r return self.LinearTransformation(a ), embs\r"},"style_context_codestyle":{"kind":"number","value":67,"string":"67"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":255,"cells":{"code":{"kind":"string","value":"\n\n\nimport json\nimport os\nimport unittest\n\nfrom transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast\nfrom transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES\nfrom transformers.testing_utils import require_tokenizers\n\nfrom ...test_tokenization_common import TokenizerTesterMixin\n\n\n\n\n\n\n\n@require_tokenizers\nclass \t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t( lowerCamelCase__\t\t\t\t\t, unittest.TestCase\t\t\t\t):\n A\t\t\t:\t\t\t\t\t\t\tList[str] \t\t\t\t\t\t\t= GPTaTokenizer\n A\t\t\t:\t\t\t\t\t\t\tint \t\t\t\t\t\t\t= GPTaTokenizerFast\n A\t\t\t:\t\t\t\t\t\t\tint \t\t\t\t\t\t\t= True\n A\t\t\t:\t\t\t\t\t\t\tTuple \t\t\t\t\t\t\t= {'add_prefix_space': True}\n A\t\t\t:\t\t\t\t\t\t\tDict \t\t\t\t\t\t\t= False\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n super().setUp()\n\n # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\t[\n \"l\",\n \"o\",\n \"w\",\n \"e\",\n \"r\",\n \"s\",\n \"t\",\n \"i\",\n \"d\",\n \"n\",\n \"\\u0120\",\n \"\\u0120l\",\n \"\\u0120n\",\n \"\\u0120lo\",\n \"\\u0120low\",\n \"er\",\n \"\\u0120lowest\",\n \"\\u0120newer\",\n \"\\u0120wider\",\n \"\",\n \"<|endoftext|>\",\n ]\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\tdict(zip(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, range(len(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\t[\"#version: 0.2\", \"\\u0120 l\", \"\\u0120l o\", \"\\u0120lo w\", \"e r\", \"\"]\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\t{\"unk_token\": \"\"}\n\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\tos.path.join(self.tmpdirname\t\t\t\t\t\t\t, VOCAB_FILES_NAMES['''vocab_file''']\t\t\t\t\t\t)\n lowercase :\t\t\t\tDict \t\t\t\t=\t\t\t\t\t\tos.path.join(self.tmpdirname\t\t\t\t\t\t\t, VOCAB_FILES_NAMES['''merges_file''']\t\t\t\t\t\t)\n with open(self.vocab_file\t\t\t\t\t\t\t, '''w'''\t\t\t\t\t\t\t, encoding='''utf-8'''\t\t\t\t\t\t) as fp:\n fp.write(json.dumps(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t) + '''\\n'''\t\t\t\t\t\t)\n with open(self.merges_file\t\t\t\t\t\t\t, '''w'''\t\t\t\t\t\t\t, encoding='''utf-8'''\t\t\t\t\t\t) as fp:\n fp.write('''\\n'''.join(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t, **SCREAMING_SNAKE_CASE__\t\t\t\t\t\t):\n kwargs.update(self.special_tokens_map\t\t\t\t\t\t)\n return GPTaTokenizer.from_pretrained(self.tmpdirname\t\t\t\t\t\t\t, **SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t, **SCREAMING_SNAKE_CASE__\t\t\t\t\t\t):\n kwargs.update(self.special_tokens_map\t\t\t\t\t\t)\n return GPTaTokenizerFast.from_pretrained(self.tmpdirname\t\t\t\t\t\t\t, **SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t):\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\t\"lower newer\"\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\t\"lower newer\"\n return input_text, output_text\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\tGPTaTokenizer(self.vocab_file\t\t\t\t\t\t\t, self.merges_file\t\t\t\t\t\t\t, **self.special_tokens_map\t\t\t\t\t\t)\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\t\"lower newer\"\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\t[\"\\u0120low\", \"er\", \"\\u0120\", \"n\", \"e\", \"w\", \"er\"]\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\ttokenizer.tokenize(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_prefix_space=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n self.assertListEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\ttokens + [tokenizer.unk_token]\n lowercase :\t\t\t\tint \t\t\t\t=\t\t\t\t\t\t[14, 15, 10, 9, 3, 2, 15, 19]\n self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n\n\n\n\n if not self.test_rust_tokenizer:\n return\n\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\tself.get_tokenizer()\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\tself.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\t\"lower newer\"\n\n # Testing tokenization\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer.tokenize(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_prefix_space=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\trust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n self.assertListEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n # Testing conversion to ids without special tokens\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_special_tokens=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_prefix_space=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\trust_tokenizer.encode(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_special_tokens=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n self.assertListEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n # Testing conversion to ids with special tokens\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\tself.get_rust_tokenizer(add_prefix_space=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_prefix_space=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\trust_tokenizer.encode(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n self.assertListEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n # Testing the unknown token\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\ttokens + [rust_tokenizer.unk_token]\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\t[14, 15, 10, 9, 3, 2, 15, 19]\n self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t, *SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, **SCREAMING_SNAKE_CASE__\t\t\t\t\t\t):\n pass\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=15\t\t\t\t\t\t):\n\n\n\n\n for tokenizer, pretrained_name, kwargs in self.tokenizers_list:\n with self.subTest(f\"\"\"{tokenizer.__class__.__name__} ({pretrained_name})\"\"\"\t\t\t\t\t\t):\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\tself.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, **SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n # Simple input\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\t\"This is a simple input\"\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\t[\"This is a simple input 1\", \"This is a simple input 2\"]\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\t(\"This is a simple input\", \"This is a pair\")\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\t[\n (\"This is a simple input 1\", \"This is a simple input 2\"),\n (\"This is a simple pair 1\", \"This is a simple pair 2\"),\n ]\n\n # Simple input tests\n self.assertRaises(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, tokenizer_r.encode\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, max_length=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t)\n\n # Simple input\n self.assertRaises(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, tokenizer_r.encode_plus\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, max_length=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t)\n\n # Simple input\n self.assertRaises(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, tokenizer_r.batch_encode_plus\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, max_length=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t\t, )\n\n # Pair input\n self.assertRaises(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, tokenizer_r.encode\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, max_length=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t)\n\n # Pair input\n self.assertRaises(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, tokenizer_r.encode_plus\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, max_length=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t)\n\n # Pair input\n self.assertRaises(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, tokenizer_r.batch_encode_plus\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, max_length=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t\t, )\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n lowercase :\t\t\t\tDict \t\t\t\t=\t\t\t\t\t\tGPTaTokenizer.from_pretrained(self.tmpdirname\t\t\t\t\t\t\t, pad_token=''''''\t\t\t\t\t\t)\n\n # Simple input\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\t\"This is a simple input\"\n lowercase :\t\t\t\tOptional[int] \t\t\t\t=\t\t\t\t\t\t[\"This is a simple input looooooooong\", \"This is a simple input\"]\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\t(\"This is a simple input\", \"This is a pair\")\n lowercase :\t\t\t\tDict \t\t\t\t=\t\t\t\t\t\t[\n (\"This is a simple input loooooong\", \"This is a simple input\"),\n (\"This is a simple pair loooooong\", \"This is a simple pair\"),\n ]\n\n lowercase :\t\t\t\tint \t\t\t\t=\t\t\t\t\t\ttokenizer.pad_token_id\n\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\ttokenizer(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t\t, max_length=30\t\t\t\t\t\t\t, return_tensors='''np'''\t\t\t\t\t\t)\n lowercase :\t\t\t\tint \t\t\t\t=\t\t\t\t\t\ttokenizer(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, truncate=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, return_tensors='''np'''\t\t\t\t\t\t)\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\ttokenizer(*SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding='''max_length'''\t\t\t\t\t\t\t, max_length=60\t\t\t\t\t\t\t, return_tensors='''np'''\t\t\t\t\t\t)\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, padding=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, truncate=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, return_tensors='''np'''\t\t\t\t\t\t)\n\n # s\n # test single string max_length padding\n self.assertEqual(out_s['''input_ids'''].shape[-1]\t\t\t\t\t\t\t, 30\t\t\t\t\t\t)\n self.assertTrue(pad_token_id in out_s['''input_ids''']\t\t\t\t\t\t)\n self.assertTrue(0 in out_s['''attention_mask''']\t\t\t\t\t\t)\n\n # s2\n # test automatic padding\n self.assertEqual(out_sa['''input_ids'''].shape[-1]\t\t\t\t\t\t\t, 33\t\t\t\t\t\t)\n # long slice doesn't have padding\n self.assertFalse(pad_token_id in out_sa['''input_ids'''][0]\t\t\t\t\t\t)\n self.assertFalse(0 in out_sa['''attention_mask'''][0]\t\t\t\t\t\t)\n # short slice does have padding\n self.assertTrue(pad_token_id in out_sa['''input_ids'''][1]\t\t\t\t\t\t)\n self.assertTrue(0 in out_sa['''attention_mask'''][1]\t\t\t\t\t\t)\n\n # p\n # test single pair max_length padding\n self.assertEqual(out_p['''input_ids'''].shape[-1]\t\t\t\t\t\t\t, 60\t\t\t\t\t\t)\n self.assertTrue(pad_token_id in out_p['''input_ids''']\t\t\t\t\t\t)\n self.assertTrue(0 in out_p['''attention_mask''']\t\t\t\t\t\t)\n\n # p2\n # test automatic padding pair\n self.assertEqual(out_pa['''input_ids'''].shape[-1]\t\t\t\t\t\t\t, 52\t\t\t\t\t\t)\n # long slice pair doesn't have padding\n self.assertFalse(pad_token_id in out_pa['''input_ids'''][0]\t\t\t\t\t\t)\n self.assertFalse(0 in out_pa['''attention_mask'''][0]\t\t\t\t\t\t)\n # short slice pair does have padding\n self.assertTrue(pad_token_id in out_pa['''input_ids'''][1]\t\t\t\t\t\t)\n self.assertTrue(0 in out_pa['''attention_mask'''][1]\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\t\"$$$\"\n lowercase :\t\t\t\tOptional[int] \t\t\t\t=\t\t\t\t\t\tGPTaTokenizer.from_pretrained(self.tmpdirname\t\t\t\t\t\t\t, bos_token=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_bos_token=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\t\"This is a simple input\"\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\t[\"This is a simple input 1\", \"This is a simple input 2\"]\n\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer.bos_token_id\n\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n self.assertEqual(out_s.input_ids[0]\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids\t\t\t\t\t\t)\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer.decode(out_s.input_ids\t\t\t\t\t\t)\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\ttokenizer.batch_decode(out_sa.input_ids\t\t\t\t\t\t)\n\n self.assertEqual(decode_s.split()[0]\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa\t\t\t\t\t\t)\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n pass\n\n\n\n\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\t[self.get_tokenizer(do_lower_case=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_bos_token=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)]\n for tokenizer in tokenizers:\n with self.subTest(f\"\"\"{tokenizer.__class__.__name__}\"\"\"\t\t\t\t\t\t):\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\t\"Encode this.\"\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\t\"This one too please.\"\n lowercase :\t\t\t\tint \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_special_tokens=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n encoded_sequence += tokenizer.encode(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_special_tokens=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\ttokenizer.encode_plus(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, add_special_tokens=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, return_special_tokens_mask=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, )\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\tencoded_sequence_dict[\"input_ids\"]\n lowercase :\t\t\t\tOptional[int] \t\t\t\t=\t\t\t\t\t\tencoded_sequence_dict[\"special_tokens_mask\"]\n self.assertEqual(len(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\t\t\t\t\t\t\t, len(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\t[\n (x if not special_tokens_mask[i] else None) for i, x in enumerate(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n ]\n lowercase :\t\t\t\tint \t\t\t\t=\t\t\t\t\t\t[x for x in filtered_sequence if x is not None]\n self.assertEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n\n\n\n\n\n\n@require_tokenizers\nclass \t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t( unittest.TestCase\t\t\t\t):\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n lowercase :\t\t\t\tList[Any] \t\t\t\t=\t\t\t\t\t\tAutoTokenizer.from_pretrained('''facebook/opt-350m'''\t\t\t\t\t\t\t, from_slow=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\t\"A photo of a cat\"\n\n lowercase :\t\t\t\tDict \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, )\n self.assertEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, [2, 250, 1345, 9, 10, 4758]\t\t\t\t\t\t)\n tokenizer.save_pretrained('''test_opt'''\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\tAutoTokenizer.from_pretrained('''./test_opt'''\t\t\t\t\t\t)\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, )\n self.assertEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, [2, 250, 1345, 9, 10, 4758]\t\t\t\t\t\t)\n\n\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\tAutoTokenizer.from_pretrained('''facebook/opt-350m'''\t\t\t\t\t\t\t, use_slow=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\t\"A photo of a cat\"\n\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, )\n # Same as above\n self.assertEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, [2, 250, 1345, 9, 10, 4758]\t\t\t\t\t\t)\n\n\n\n\n\n\n @unittest.skip('''This test is failing because of a bug in the fast tokenizer'''\t\t\t\t\t\t)\n def __lowerCamelCase (\t\t\t\t\t\t\tself\t\t\t\t\t\t):\n lowercase :\t\t\t\tOptional[int] \t\t\t\t=\t\t\t\t\t\tAutoTokenizer.from_pretrained('''facebook/opt-350m'''\t\t\t\t\t\t\t, from_slow=SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\t\"bos\"\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\ttokenizer.get_vocab()[\"bos\"]\n\n lowercase :\t\t\t\tOptional[int] \t\t\t\t=\t\t\t\t\t\t\"A photo of a cat\"\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, )\n # We changed the bos token\n self.assertEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, [31957, 250, 1345, 9, 10, 4758]\t\t\t\t\t\t)\n tokenizer.save_pretrained('''./tok'''\t\t\t\t\t\t)\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\tAutoTokenizer.from_pretrained('''./tok'''\t\t\t\t\t\t)\n self.assertTrue(tokenizer.is_fast\t\t\t\t\t\t)\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\ttokenizer.encode(\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, )\n self.assertEqual(SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, [31957, 250, 1345, 9, 10, 4758]\t\t\t\t\t\t)\n\n"},"code_codestyle":{"kind":"number","value":354,"string":"354"},"style_context":{"kind":"string","value":"\n\n\nfrom ...configuration_utils import PretrainedConfig\nfrom ...utils import logging\n\n\n__a\t\t\t\t\t\t\t= logging.get_logger(__name__)\n\n__a\t\t\t\t\t\t\t= {\n '''MIT/ast-finetuned-audioset-10-10-0.4593''': (\n '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json'''\n ),\n}\n\n\n\n\n\n\n\nclass \t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t( A__\t\t\t\t):\n A\t\t\t:\t\t\t\t\t\t\tUnion[str, Any] \t\t\t\t\t\t\t= 'audio-spectrogram-transformer'\n\n\n def __init__(\t\t\t\t\t\t\tself\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=768\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=12\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=12\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=3072\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=\"gelu\"\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=0.0\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=0.0\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=0.02\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=1E-12\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=16\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=True\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=10\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=10\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=1024\t\t\t\t\t\t\t, SCREAMING_SNAKE_CASE__=128\t\t\t\t\t\t\t, **SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t, ):\n super().__init__(**SCREAMING_SNAKE_CASE__\t\t\t\t\t\t)\n\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\thidden_size\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\tnum_hidden_layers\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\tnum_attention_heads\n lowercase :\t\t\t\tOptional[int] \t\t\t\t=\t\t\t\t\t\tintermediate_size\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\thidden_act\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\thidden_dropout_prob\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\tattention_probs_dropout_prob\n lowercase :\t\t\t\tOptional[Any] \t\t\t\t=\t\t\t\t\t\tinitializer_range\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\tlayer_norm_eps\n lowercase :\t\t\t\tAny \t\t\t\t=\t\t\t\t\t\tpatch_size\n lowercase :\t\t\t\tTuple \t\t\t\t=\t\t\t\t\t\tqkv_bias\n lowercase :\t\t\t\tstr \t\t\t\t=\t\t\t\t\t\tfrequency_stride\n lowercase :\t\t\t\tUnion[str, Any] \t\t\t\t=\t\t\t\t\t\ttime_stride\n lowercase :\t\t\t\tDict \t\t\t\t=\t\t\t\t\t\tmax_length\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\tnum_mel_bins\n\n"},"style_context_codestyle":{"kind":"number","value":173,"string":"173"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":256,"cells":{"code":{"kind":"string","value":"\n\n\n\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nimport torch\nfrom torch import nn\n\nfrom ..configuration_utils import ConfigMixin, register_to_config\nfrom ..utils import BaseOutput\nfrom .attention import BasicTransformerBlock\nfrom .modeling_utils import ModelMixin\n\n\n\n\n\n@dataclass\nclass \t\t\t\t\t__lowerCAmelCase ( lowerCamelCase__ ):\n\t\t\t\t__lowerCamelCase =\t\t\t\t42\n\n\n\n\n\nclass \t\t\t\t\t__lowerCAmelCase ( lowerCamelCase__ ,\t\t\t\t\t\tlowerCamelCase__ ):\n\n\n\n\n\t\t\t\t@register_to_config\n\t\t\t\tdef __init__(\t\t\t\t\t\t\tself\t\t\t\t\t\t,\t\t\t\t_snake_case = 16\t\t\t\t\t\t,\t\t\t\t_snake_case = 88\t\t\t\t\t\t,\t\t\t\t_snake_case = None\t\t\t\t\t\t,\t\t\t\t_snake_case = None\t\t\t\t\t\t,\t\t\t\t_snake_case = 1\t\t\t\t\t\t,\t\t\t\t_snake_case = 0.0\t\t\t\t\t\t,\t\t\t\t_snake_case = 32\t\t\t\t\t\t,\t\t\t\t_snake_case = None\t\t\t\t\t\t,\t\t\t\t_snake_case = False\t\t\t\t\t\t,\t\t\t\t_snake_case = None\t\t\t\t\t\t,\t\t\t\t_snake_case = \"geglu\"\t\t\t\t\t\t,\t\t\t\t_snake_case = True\t\t\t\t\t\t,\t\t\t\t_snake_case = True\t\t\t\t\t\t,\t\t\t\t):\n\n\n\n\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\t\t\t\t\t\t\t\t\tsuper().__init__()\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= num_attention_heads\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= attention_head_dim\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= num_attention_heads * attention_head_dim\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= in_channels\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= torch.nn.GroupNorm(num_groups=_snake_case\t\t\t\t\t\t,\t\t\t\tnum_channels=_snake_case\t\t\t\t\t\t,\t\t\t\teps=1e-6\t\t\t\t\t\t,\t\t\t\taffine=_snake_case\t\t)\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= nn.Linear(_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t)\n\n\t\t\t\t\t\t\t\t\t# 3. Define transformers blocks\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= nn.ModuleList(\n\t\t\t\t\t\t\t\t\t [\n\t\t\t\t\t\t\t\t\t BasicTransformerBlock(\n\t\t\t\t\t\t\t\t\t _snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\tdropout=_snake_case\t\t\t\t\t\t,\t\t\t\tcross_attention_dim=_snake_case\t\t\t\t\t\t,\t\t\t\tactivation_fn=_snake_case\t\t\t\t\t\t,\t\t\t\tattention_bias=_snake_case\t\t\t\t\t\t,\t\t\t\tdouble_self_attention=_snake_case\t\t\t\t\t\t,\t\t\t\tnorm_elementwise_affine=_snake_case\t\t\t\t\t\t,\t\t\t\t)\n\t\t\t\t\t\t\t\t\t for d in range(_snake_case\t\t)\n\t\t\t\t\t\t\t\t\t ]\t\t)\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= nn.Linear(_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t)\n\n\n\n\n\t\t\t\tdef \t\t\t\t\t\t\tsnake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case=None\t\t\t\t\t\t,\t\t\t\t_snake_case=None\t\t\t\t\t\t,\t\t\t\t_snake_case=None\t\t\t\t\t\t,\t\t\t\t_snake_case=1\t\t\t\t\t\t,\t\t\t\t_snake_case=None\t\t\t\t\t\t,\t\t\t\t_snake_case = True\t\t\t\t\t\t,\t\t\t\t):\n\n\n\n\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t,\t_lowerCAmelCase\t,\t_lowerCAmelCase\t,\t_lowerCAmelCase\t\t\t\t\t\t= hidden_states.shape\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= batch_frames // num_frames\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= hidden_states\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= hidden_states[None, :].reshape(_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t)\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= hidden_states.permute(0\t\t\t\t\t\t,\t\t\t\t2\t\t\t\t\t\t,\t\t\t\t1\t\t\t\t\t\t,\t\t\t\t3\t\t\t\t\t\t,\t\t\t\t4\t\t)\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= self.norm(_snake_case\t\t)\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= hidden_states.permute(0\t\t\t\t\t\t,\t\t\t\t3\t\t\t\t\t\t,\t\t\t\t4\t\t\t\t\t\t,\t\t\t\t2\t\t\t\t\t\t,\t\t\t\t1\t\t).reshape(batch_size * height * width\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t)\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= self.proj_in(_snake_case\t\t)\n\n\t\t\t\t\t\t\t\t\t# 2. Blocks\n\t\t\t\t\t\t\t\t\tfor block in self.transformer_blocks:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= block(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t _snake_case\t\t\t\t\t\t,\t\t\t\tencoder_hidden_states=_snake_case\t\t\t\t\t\t,\t\t\t\ttimestep=_snake_case\t\t\t\t\t\t,\t\t\t\tcross_attention_kwargs=_snake_case\t\t\t\t\t\t,\t\t\t\tclass_labels=_snake_case\t\t\t\t\t\t,\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t# 3. Output\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= self.proj_out(_snake_case\t\t)\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= (\n\t\t\t\t\t\t\t\t\t hidden_states[None, None, :]\n\t\t\t\t\t\t\t\t\t .reshape(_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t)\n\t\t\t\t\t\t\t\t\t .permute(0\t\t\t\t\t\t,\t\t\t\t3\t\t\t\t\t\t,\t\t\t\t4\t\t\t\t\t\t,\t\t\t\t1\t\t\t\t\t\t,\t\t\t\t2\t\t)\n\t\t\t\t\t\t\t\t\t .contiguous()\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= hidden_states.reshape(_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t\t\t\t\t,\t\t\t\t_snake_case\t\t)\n\n\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= hidden_states + residual\n\n\t\t\t\t\t\t\t\t\tif not return_dict:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn (output,)\n\n\t\t\t\t\t\t\t\t\treturn TransformerTemporalModelOutput(sample=_snake_case\t\t)\n\n\n\n"},"code_codestyle":{"kind":"number","value":82,"string":"82"},"style_context":{"kind":"string","value":"\n\n\n\nfrom math import isqrt, loga\n\n\ndef \t\t_UpperCAmelCase\t\t\t\t( snake_case\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= [True] * max_number\n\t\t\t\t\tfor i in range(2\t,\t\t\t\t\t\tisqrt(max_number - 1\t\t\t) + 1\t\t\t):\n\t\t\t\t\t\t\t\t\t\tif is_prime[i]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor j in range(i**2\t,\t\t\t\t\t\tsnake_case\t,\t\t\t\t\t\tsnake_case\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= False\n\n\t\t\t\t\treturn [i for i in range(2\t,\t\t\t\t\t\tsnake_case\t\t\t) if is_prime[i]]\n\n\ndef \t\t_UpperCAmelCase\t\t\t\t( snake_case = 80_08_00\t,\t\t\t\t\t\tsnake_case = 80_08_00\t\t\t):\n\n\n\n\n\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= degree * loga(snake_case\t\t\t)\n\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= int(snake_case\t\t\t)\n\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= calculate_prime_numbers(snake_case\t\t\t)\n\n\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= 0\n\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= 0\n\t\t\t\t\t_lowerCAmelCase\t\t\t\t\t\t= len(snake_case\t\t\t) - 1\n\t\t\t\t\twhile left < right:\n\t\t\t\t\t\t\t\t\t\twhile (\n\t\t\t\t\t\t\t\t\t\t prime_numbers[right] * loga(prime_numbers[left]\t\t\t)\n\t\t\t\t\t\t\t\t\t\t + prime_numbers[left] * loga(prime_numbers[right]\t\t\t)\n\t\t\t\t\t\t\t\t\t\t > upper_bound\n\t\t\t\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tright -= 1\n\t\t\t\t\t\t\t\t\t\thybrid_integers_count += right - left\n\t\t\t\t\t\t\t\t\t\tleft += 1\n\n\t\t\t\t\treturn hybrid_integers_count\n\n\nif __name__ == \"__main__\":\n\tprint(f\"{solution() = }\")\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":82,"string":"82"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":257,"cells":{"code":{"kind":"string","value":"\r\r\r\r\r\rimport unittest\r\rimport numpy as np\r\rfrom transformers import is_flax_available\rfrom transformers.testing_utils import require_flax\r\rfrom ..test_modeling_flax_common import ids_tensor\r\r\rif is_flax_available():\r\t\t\timport jax\r\t\t\timport jax.numpy as jnp\r\r\t\t\tfrom transformers.generation import (\r\t\t\t FlaxForcedBOSTokenLogitsProcessor,\r\t\t\t FlaxForcedEOSTokenLogitsProcessor,\r\t\t\t FlaxLogitsProcessorList,\r\t\t\t FlaxMinLengthLogitsProcessor,\r\t\t\t FlaxTemperatureLogitsWarper,\r\t\t\t FlaxTopKLogitsWarper,\r\t\t\t FlaxTopPLogitsWarper,\r\t\t\t)\r\r@require_flax\rclass __A ( unittest.TestCase ):\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jnp.ones((batch_size, length)\t\t\t\t\t\t\t) / length\r\t\t\t\t\t\t\t\treturn scores\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=None\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=20\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(batch_size=2\t\t\t\t,\tlength=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# tweak scores to not be uniform anymore\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=scores.at[1, 5].set((1 / length) + 0.1\t\t\t\t\t\t\t) # peak, 1st batch\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=scores.at[1, 10].set((1 / length) - 0.4\t\t\t\t\t\t\t) # valley, 1st batch\r\r\t\t\t\t\t\t\t\t# compute softmax\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jax.nn.softmax(UpperCAmelCase_\t\t\t\t,\taxis=-1\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTemperatureLogitsWarper(temperature=0.5\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTemperatureLogitsWarper(temperature=1.3\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jax.nn.softmax(temp_dist_warper_sharper(UpperCAmelCase_\t\t\t\t,\tscores.copy()\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\t\t\t\t,\taxis=-1\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jax.nn.softmax(temp_dist_warper_smoother(UpperCAmelCase_\t\t\t\t,\tscores.copy()\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\t\t\t\t,\taxis=-1\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# uniform distribution stays uniform\r\t\t\t\t\t\t\t\tself.assertTrue(jnp.allclose(probs[0, :]\t\t\t\t,\twarped_prob_sharp[0, :]\t\t\t\t,\tatol=1E-3\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertTrue(jnp.allclose(probs[0, :]\t\t\t\t,\twarped_prob_smooth[0, :]\t\t\t\t,\tatol=1E-3\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# sharp peaks get higher, valleys get lower\r\t\t\t\t\t\t\t\tself.assertLess(probs[1, :].max()\t\t\t\t,\twarped_prob_sharp[1, :].max()\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertGreater(probs[1, :].min()\t\t\t\t,\twarped_prob_sharp[1, :].min()\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# smooth peaks get lower, valleys get higher\r\t\t\t\t\t\t\t\tself.assertGreater(probs[1, :].max()\t\t\t\t,\twarped_prob_smooth[1, :].max()\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertLess(probs[1, :].min()\t\t\t\t,\twarped_prob_smooth[1, :].min()\t\t\t\t\t\t\t)\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=None\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=10\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=2\r\r\t\t\t\t\t\t\t\t# create ramp distribution\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=np.broadcast_to(np.arange(UpperCAmelCase_\t\t\t\t\t\t\t)[None, :]\t\t\t\t,\t(batch_size, vocab_size)\t\t\t\t\t\t\t).copy()\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=ramp_logits[1:, : vocab_size // 2] + vocab_size\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopKLogitsWarper(3\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=top_k_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# check that correct tokens are filtered\r\t\t\t\t\t\t\t\tself.assertListEqual(jnp.isinf(scores[0]\t\t\t\t\t\t\t).tolist()\t\t\t\t,\t7 * [True] + 3 * [False]\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertListEqual(jnp.isinf(scores[1]\t\t\t\t\t\t\t).tolist()\t\t\t\t,\t2 * [True] + 3 * [False] + 5 * [True]\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# check special case\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=5\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopKLogitsWarper(top_k=1\t\t\t\t,\tfilter_value=0.0\t\t\t\t,\tmin_tokens_to_keep=3\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=np.broadcast_to(np.arange(UpperCAmelCase_\t\t\t\t\t\t\t)[None, :]\t\t\t\t,\t(batch_size, length)\t\t\t\t\t\t\t).copy()\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=top_k_warp_safety_check(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified\r\t\t\t\t\t\t\t\tself.assertListEqual((scores == 0.0).sum(axis=-1\t\t\t\t\t\t\t).tolist()\t\t\t\t,\t[2, 2]\t\t\t\t\t\t\t)\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=None\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=10\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=2\r\r\t\t\t\t\t\t\t\t# create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.1_5, 0.3, 0.3, 0.2_5]]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopPLogitsWarper(0.8\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=np.exp(top_p_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# dist should be filtered to keep min num values so that sum is >= top_p\r\t\t\t\t\t\t\t\t# exp (-inf) => 0\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.2_5]]\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertTrue(np.allclose(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tatol=1E-3\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# check edge cases with negative and extreme logits\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=np.broadcast_to(np.arange(UpperCAmelCase_\t\t\t\t\t\t\t)[None, :]\t\t\t\t,\t(batch_size, vocab_size)\t\t\t\t\t\t\t).copy() - (\r\t\t\t\t\t\t\t\t vocab_size // 2\r\t\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# make ramp_logits more extreme\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=ramp_logits[1] * 100.0\r\r\t\t\t\t\t\t\t\t# make sure at least 2 tokens are kept\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopPLogitsWarper(0.9\t\t\t\t,\tmin_tokens_to_keep=2\t\t\t\t,\tfilter_value=0.0\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=top_p_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2.\r\t\t\t\t\t\t\t\tself.assertListEqual((filtered_dist != 0.0).sum(axis=-1\t\t\t\t\t\t\t).tolist()\t\t\t\t,\t[3, 2]\t\t\t\t\t\t\t)\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=20\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=4\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=0\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxMinLengthLogitsProcessor(min_length=10\t\t\t\t,\teos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# check that min length is applied at length 5\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=ids_tensor((batch_size, 20)\t\t\t\t,\tvocab_size=20\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=5\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=min_dist_processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertListEqual(scores_before_min_length[:, eos_token_id].tolist()\t\t\t\t,\t4 * [-float(\"\"\"inf\"\"\"\t\t\t\t\t\t\t)]\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# check that min length is not applied anymore at length 15\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=15\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=min_dist_processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertFalse(jnp.isinf(UpperCAmelCase_\t\t\t\t\t\t\t).any()\t\t\t\t\t\t\t)\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=20\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=4\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=0\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# check that all scores are -inf except the bos_token_id score\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=ids_tensor((batch_size, 1)\t\t\t\t,\tvocab_size=20\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=1\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=logits_processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :]\t\t\t\t\t\t\t).all()\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertListEqual(scores[:, bos_token_id].tolist()\t\t\t\t,\t4 * [0]\t\t\t\t\t\t\t) # score for bos_token_id shold be zero\r\r\t\t\t\t\t\t\t\t# check that bos_token_id is not forced if current length is greater than 1\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=3\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=logits_processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertFalse(jnp.isinf(UpperCAmelCase_\t\t\t\t\t\t\t).any()\t\t\t\t\t\t\t)\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=20\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=4\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=0\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=5\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase_\t\t\t\t,\teos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# check that all scores are -inf except the eos_token_id when max_length is reached\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=ids_tensor((batch_size, 4)\t\t\t\t,\tvocab_size=20\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=4\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=logits_processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :]\t\t\t\t\t\t\t).all()\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertListEqual(scores[:, eos_token_id].tolist()\t\t\t\t,\t4 * [0]\t\t\t\t\t\t\t) # score for eos_token_id should be zero\r\r\t\t\t\t\t\t\t\t# check that eos_token_id is not forced if max_length is not reached\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=3\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=logits_processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tself.assertFalse(jnp.isinf(UpperCAmelCase_\t\t\t\t\t\t\t).any()\t\t\t\t\t\t\t)\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=4\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=10\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=15\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=2\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=1\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=15\r\r\t\t\t\t\t\t\t\t# dummy input_ids and scores\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=ids_tensor((batch_size, sequence_length)\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=input_ids.copy()\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=scores.copy()\r\r\t\t\t\t\t\t\t\t# instantiate all dist processors\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTemperatureLogitsWarper(temperature=0.5\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopKLogitsWarper(3\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopPLogitsWarper(0.8\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# instantiate all logits processors\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxMinLengthLogitsProcessor(min_length=10\t\t\t\t,\teos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase_\t\t\t\t,\teos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=10\r\r\t\t\t\t\t\t\t\t# no processor list\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=temp_dist_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=top_k_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=top_p_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=min_dist_proc(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=bos_dist_proc(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=eos_dist_proc(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# with processor list\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxLogitsProcessorList(\r\t\t\t\t\t\t\t\t [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# scores should be equal\r\t\t\t\t\t\t\t\tself.assertTrue(jnp.allclose(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tatol=1E-3\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# input_ids should never be changed\r\t\t\t\t\t\t\t\tself.assertListEqual(input_ids.tolist()\t\t\t\t,\tinput_ids_comp.tolist()\t\t\t\t\t\t\t)\r\r\r\t\t\t\tdef _snake_case (\t\t\t\t\t\tself\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=4\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=10\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=15\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=2\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=1\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=15\r\r\t\t\t\t\t\t\t\t# dummy input_ids and scores\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=ids_tensor((batch_size, sequence_length)\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=input_ids.copy()\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=self._get_uniform_logits(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=scores.copy()\r\r\t\t\t\t\t\t\t\t# instantiate all dist processors\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTemperatureLogitsWarper(temperature=0.5\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopKLogitsWarper(3\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxTopPLogitsWarper(0.8\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# instantiate all logits processors\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxMinLengthLogitsProcessor(min_length=10\t\t\t\t,\teos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxForcedBOSTokenLogitsProcessor(bos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxForcedEOSTokenLogitsProcessor(max_length=UpperCAmelCase_\t\t\t\t,\teos_token_id=UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=10\r\r\t\t\t\t\t\t\t\t# no processor list\r\t\t\t\t\t\t\t\tdef run_no_processor_list(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=temp_dist_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=top_k_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=top_p_warp(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=min_dist_proc(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=bos_dist_proc(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=eos_dist_proc(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\treturn scores\r\r\t\t\t\t\t\t\t\t# with processor list\r\t\t\t\t\t\t\t\tdef run_processor_list(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=FlaxLogitsProcessorList(\r\t\t\t\t\t\t\t\t\t\t\t\t [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc]\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=processor(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tcur_len=UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\treturn scores\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jax.jit(UpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jax.jit(UpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jitted_run_no_processor_list(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\tlowerCamelCase\t\t\t=jitted_run_processor_list(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# scores should be equal\r\t\t\t\t\t\t\t\tself.assertTrue(jnp.allclose(UpperCAmelCase_\t\t\t\t,\tUpperCAmelCase_\t\t\t\t,\tatol=1E-3\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# input_ids should never be changed\r\t\t\t\t\t\t\t\tself.assertListEqual(input_ids.tolist()\t\t\t\t,\tinput_ids_comp.tolist()\t\t\t\t\t\t\t)\r\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":350,"string":"350"},"style_context":{"kind":"string","value":"\r\r\r\r\r\rfrom math import cos, sin, sqrt, tau\r\rfrom audio_filters.iir_filter import IIRFilter\r\r\r\r\r\rdef _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2\t\t\t)\t\t\t) ->\t\t\t\t\tIIRFilter:\r\t\t\t\tlowerCamelCase\t\t\t=tau * frequency / samplerate\r\t\t\t\tlowerCamelCase\t\t\t=sin(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=cos(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=_sin / (2 * q_factor)\r\r\t\t\t\tlowerCamelCase\t\t\t=(1 - _cos) / 2\r\t\t\t\tlowerCamelCase\t\t\t=1 - _cos\r\r\t\t\t\tlowerCamelCase\t\t\t=1 + alpha\r\t\t\t\tlowerCamelCase\t\t\t=-2 * _cos\r\t\t\t\tlowerCamelCase\t\t\t=1 - alpha\r\r\t\t\t\tlowerCamelCase\t\t\t=IIRFilter(2\t\t\t)\r\t\t\t\tfilt.set_coefficients([aa, aa, aa] , [ba, ba, ba]\t\t\t)\r\t\t\t\treturn filt\r\r\r\r\r\rdef _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2\t\t\t)\t\t\t) ->\t\t\t\t\tIIRFilter:\r\t\t\t\tlowerCamelCase\t\t\t=tau * frequency / samplerate\r\t\t\t\tlowerCamelCase\t\t\t=sin(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=cos(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=_sin / (2 * q_factor)\r\r\t\t\t\tlowerCamelCase\t\t\t=(1 + _cos) / 2\r\t\t\t\tlowerCamelCase\t\t\t=-1 - _cos\r\r\t\t\t\tlowerCamelCase\t\t\t=1 + alpha\r\t\t\t\tlowerCamelCase\t\t\t=-2 * _cos\r\t\t\t\tlowerCamelCase\t\t\t=1 - alpha\r\r\t\t\t\tlowerCamelCase\t\t\t=IIRFilter(2\t\t\t)\r\t\t\t\tfilt.set_coefficients([aa, aa, aa] , [ba, ba, ba]\t\t\t)\r\t\t\t\treturn filt\r\r\r\r\r\rdef _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2\t\t\t)\t\t\t) ->\t\t\t\t\tIIRFilter:\r\t\t\t\tlowerCamelCase\t\t\t=tau * frequency / samplerate\r\t\t\t\tlowerCamelCase\t\t\t=sin(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=cos(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=_sin / (2 * q_factor)\r\r\t\t\t\tlowerCamelCase\t\t\t=_sin / 2\r\t\t\t\tlowerCamelCase\t\t\t=0\r\t\t\t\tlowerCamelCase\t\t\t=-ba\r\r\t\t\t\tlowerCamelCase\t\t\t=1 + alpha\r\t\t\t\tlowerCamelCase\t\t\t=-2 * _cos\r\t\t\t\tlowerCamelCase\t\t\t=1 - alpha\r\r\t\t\t\tlowerCamelCase\t\t\t=IIRFilter(2\t\t\t)\r\t\t\t\tfilt.set_coefficients([aa, aa, aa] , [ba, ba, ba]\t\t\t)\r\t\t\t\treturn filt\r\r\r\r\r\rdef _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2\t\t\t)\t\t\t) ->\t\t\t\t\tIIRFilter:\r\t\t\t\tlowerCamelCase\t\t\t=tau * frequency / samplerate\r\t\t\t\tlowerCamelCase\t\t\t=sin(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=cos(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=_sin / (2 * q_factor)\r\r\t\t\t\tlowerCamelCase\t\t\t=1 - alpha\r\t\t\t\tlowerCamelCase\t\t\t=-2 * _cos\r\t\t\t\tlowerCamelCase\t\t\t=1 + alpha\r\r\t\t\t\tlowerCamelCase\t\t\t=IIRFilter(2\t\t\t)\r\t\t\t\tfilt.set_coefficients([ba, ba, ba] , [ba, ba, ba]\t\t\t)\r\t\t\t\treturn filt\r\r\r\r\r\rdef _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2\t\t\t) , ) ->\t\t\t\t\tIIRFilter:\r\t\t\t\tlowerCamelCase\t\t\t=tau * frequency / samplerate\r\t\t\t\tlowerCamelCase\t\t\t=sin(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=cos(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=_sin / (2 * q_factor)\r\t\t\t\tlowerCamelCase\t\t\t=10 ** (gain_db / 40)\r\r\t\t\t\tlowerCamelCase\t\t\t=1 + alpha * big_a\r\t\t\t\tlowerCamelCase\t\t\t=-2 * _cos\r\t\t\t\tlowerCamelCase\t\t\t=1 - alpha * big_a\r\t\t\t\tlowerCamelCase\t\t\t=1 + alpha / big_a\r\t\t\t\tlowerCamelCase\t\t\t=-2 * _cos\r\t\t\t\tlowerCamelCase\t\t\t=1 - alpha / big_a\r\r\t\t\t\tlowerCamelCase\t\t\t=IIRFilter(2\t\t\t)\r\t\t\t\tfilt.set_coefficients([aa, aa, aa] , [ba, ba, ba]\t\t\t)\r\t\t\t\treturn filt\r\r\r\r\r\rdef _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2\t\t\t) , ) ->\t\t\t\t\tIIRFilter:\r\t\t\t\tlowerCamelCase\t\t\t=tau * frequency / samplerate\r\t\t\t\tlowerCamelCase\t\t\t=sin(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=cos(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=_sin / (2 * q_factor)\r\t\t\t\tlowerCamelCase\t\t\t=10 ** (gain_db / 40)\r\t\t\t\tlowerCamelCase\t\t\t=(big_a + 1) - (big_a - 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=(big_a + 1) + (big_a - 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=(big_a - 1) - (big_a + 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=(big_a - 1) + (big_a + 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=2 * sqrt(_UpperCAmelCase\t\t\t) * alpha\r\r\t\t\t\tlowerCamelCase\t\t\t=big_a * (pmc + aaa)\r\t\t\t\tlowerCamelCase\t\t\t=2 * big_a * mpc\r\t\t\t\tlowerCamelCase\t\t\t=big_a * (pmc - aaa)\r\t\t\t\tlowerCamelCase\t\t\t=ppmc + aaa\r\t\t\t\tlowerCamelCase\t\t\t=-2 * pmpc\r\t\t\t\tlowerCamelCase\t\t\t=ppmc - aaa\r\r\t\t\t\tlowerCamelCase\t\t\t=IIRFilter(2\t\t\t)\r\t\t\t\tfilt.set_coefficients([aa, aa, aa] , [ba, ba, ba]\t\t\t)\r\t\t\t\treturn filt\r\r\r\r\r\rdef _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2\t\t\t) , ) ->\t\t\t\t\tIIRFilter:\r\t\t\t\tlowerCamelCase\t\t\t=tau * frequency / samplerate\r\t\t\t\tlowerCamelCase\t\t\t=sin(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=cos(_UpperCAmelCase\t\t\t)\r\t\t\t\tlowerCamelCase\t\t\t=_sin / (2 * q_factor)\r\t\t\t\tlowerCamelCase\t\t\t=10 ** (gain_db / 40)\r\t\t\t\tlowerCamelCase\t\t\t=(big_a + 1) - (big_a - 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=(big_a + 1) + (big_a - 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=(big_a - 1) - (big_a + 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=(big_a - 1) + (big_a + 1) * _cos\r\t\t\t\tlowerCamelCase\t\t\t=2 * sqrt(_UpperCAmelCase\t\t\t) * alpha\r\r\t\t\t\tlowerCamelCase\t\t\t=big_a * (ppmc + aaa)\r\t\t\t\tlowerCamelCase\t\t\t=-2 * big_a * pmpc\r\t\t\t\tlowerCamelCase\t\t\t=big_a * (ppmc - aaa)\r\t\t\t\tlowerCamelCase\t\t\t=pmc + aaa\r\t\t\t\tlowerCamelCase\t\t\t=2 * mpc\r\t\t\t\tlowerCamelCase\t\t\t=pmc - aaa\r\r\t\t\t\tlowerCamelCase\t\t\t=IIRFilter(2\t\t\t)\r\t\t\t\tfilt.set_coefficients([aa, aa, aa] , [ba, ba, ba]\t\t\t)\r\t\t\t\treturn filt\r\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":262,"string":"262"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":258,"cells":{"code":{"kind":"string","value":"import argparse\r\n\r\nfrom transformers import (\r\n TapasConfig,\r\n TapasForMaskedLM,\r\n TapasForQuestionAnswering,\r\n TapasForSequenceClassification,\r\n TapasModel,\r\n TapasTokenizer,\r\n load_tf_weights_in_tapas,\r\n)\r\nfrom transformers.utils import logging\r\n\r\n\r\nlogging.set_verbosity_info()\r\n\r\n\r\n\r\ndef \t__SCREAMING_SNAKE_CASE (\t\t\t\t\t__UpperCamelCase : Dict , __UpperCamelCase : Dict , __UpperCamelCase : Optional[int] , __UpperCamelCase : Dict , __UpperCamelCase : List[str]\t)\t\t\t\t\t\t\t->\t\t\t\t\tOptional[int]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasConfig.from_json_file(__UpperCamelCase\t)\r\n # set absolute/relative position embeddings parameter\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= reset_position_index_per_cell\r\n\r\n # set remaining parameters of TapasConfig as well as the model based on the task\r\n if task == \"SQA\":\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasForQuestionAnswering(config=__UpperCamelCase\t)\r\n elif task == \"WTQ\":\r\n # run_task_main.py hparams\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 4\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= True\r\n # hparam_utils.py hparams\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 0.66_4694\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 0.20_7951\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 0.12_1194\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= True\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= True\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= False\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 0.035_2513\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasForQuestionAnswering(config=__UpperCamelCase\t)\r\n elif task == \"WIKISQL_SUPERVISED\":\r\n # run_task_main.py hparams\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 4\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= False\r\n # hparam_utils.py hparams\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 36.4519\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 0.90_3421\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 222.088\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= True\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= True\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= True\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= 0.76_3141\r\n\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasForQuestionAnswering(config=__UpperCamelCase\t)\r\n elif task == \"TABFACT\":\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasForSequenceClassification(config=__UpperCamelCase\t)\r\n elif task == \"MLM\":\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasForMaskedLM(config=__UpperCamelCase\t)\r\n elif task == \"INTERMEDIATE_PRETRAINING\":\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasModel(config=__UpperCamelCase\t)\r\n else:\r\n raise ValueError(f\"\"\"Task {task} not supported.\"\"\"\t)\r\n\r\n print(f\"\"\"Building PyTorch model from configuration: {config}\"\"\"\t)\r\n # Load weights from tf checkpoint\r\n load_tf_weights_in_tapas(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase\t)\r\n\r\n # Save pytorch-model (weights and configuration)\r\n print(f\"\"\"Save PyTorch model to {pytorch_dump_path}\"\"\"\t)\r\n model.save_pretrained(__UpperCamelCase\t)\r\n\r\n # Save tokenizer files\r\n print(f\"\"\"Save tokenizer files to {pytorch_dump_path}\"\"\"\t)\r\n SCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t= TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + \"\"\"vocab.txt\"\"\" , model_max_length=5_12\t)\r\n tokenizer.save_pretrained(__UpperCamelCase\t)\r\n\r\n print(\"\"\"Used relative position embeddings:\"\"\" , model.config.reset_position_index_per_cell\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n __lowerCamelCase\t\t\t: Tuple\t\t\t\t\t\t\t =\t\targparse.ArgumentParser()\r\n # Required parameters\r\n parser.add_argument(\r\n '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.'''\r\n )\r\n parser.add_argument(\r\n '''--reset_position_index_per_cell''',\r\n default=False,\r\n action='''store_true''',\r\n help='''Whether to use relative position embeddings or not. Defaults to True.''',\r\n )\r\n parser.add_argument(\r\n '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''\r\n )\r\n parser.add_argument(\r\n '''--tapas_config_file''',\r\n default=None,\r\n type=str,\r\n required=True,\r\n help=(\r\n '''The config json file corresponding to the pre-trained TAPAS model. \\n'''\r\n '''This specifies the model architecture.'''\r\n ),\r\n )\r\n parser.add_argument(\r\n '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''\r\n )\r\n __lowerCamelCase\t\t\t: Dict\t\t\t\t\t\t\t =\t\tparser.parse_args()\r\n convert_tf_checkpoint_to_pytorch(\r\n args.task,\r\n args.reset_position_index_per_cell,\r\n args.tf_checkpoint_path,\r\n args.tapas_config_file,\r\n args.pytorch_dump_path,\r\n )\r\n"},"code_codestyle":{"kind":"number","value":219,"string":"219"},"style_context":{"kind":"string","value":"import warnings\r\n\r\nfrom ..trainer import Trainer\r\nfrom ..utils import logging\r\n\r\n\r\n__lowerCamelCase\t\t\t: List[Any]\t\t\t\t\t\t\t =\t\tlogging.get_logger(__name__)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass __snake_case\t\t\t\t(\t\t\t\t\t\tlowerCamelCase_\t\t):\r\n\r\n\r\n\r\n\r\n def __init__( self\t\t\t:\t\t\t\tTuple ,\t_lowercase\t\t\t:\t\t\t\tOptional[int]=None ,\t**_lowercase\t\t\t:\t\t\t\tList[Any] ):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n warnings.warn(\r\n \"\"\"`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` \"\"\"\r\n \"\"\"instead.\"\"\" ,\t_lowercase ,\t)\r\n super().__init__(args=_lowercase ,\t**_lowercase )\r\n"},"style_context_codestyle":{"kind":"number","value":219,"string":"219"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":259,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\nimport inspect\r\nimport logging\r\nimport os\r\nimport random\r\nimport shutil\r\nimport tempfile\r\nimport unittest\r\n\r\nimport pytest\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.utils.data import DataLoader, TensorDataset\r\n\r\nfrom accelerate import Accelerator\r\nfrom accelerate.test_utils import execute_subprocess_async, require_cuda\r\nfrom accelerate.utils import ProjectConfiguration, set_seed\r\n\r\n\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=logging.getLogger(__name__)\r\n\r\n\r\n\r\n\r\n\r\ndef \ta_ (\t\t\t\t\t\t\t_lowercase=2\t,\t\t\t\t\t\t_lowercase=3\t,\t\t\t\t\t\t_lowercase=16\t,\t\t\t\t\t\t_lowercase = 10\t,\t\t\t\t\t\t_lowercase = 2 ):\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef get_dataset(_lowercase ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = torch.randn(batch_size * n_batches\t,\t\t\t\t\t\t1 )\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn TensorDataset(A__\t,\t\t\t\t\t\ta * x + b + 0.1 * torch.randn(batch_size * n_batches\t,\t\t\t\t\t\t1 ) )\r\n\r\n\t\t\t\t\t\t_UpperCamelCase : List[str] = get_dataset(A__ )\r\n\t\t\t\t\t\t_UpperCamelCase : int = get_dataset(A__ )\r\n\t\t\t\t\t\t_UpperCamelCase : List[str] = DataLoader(A__\t,\t\t\t\t\t\tshuffle=A__\t,\t\t\t\t\t\tbatch_size=A__\t,\t\t\t\t\t\tnum_workers=4 )\r\n\t\t\t\t\t\t_UpperCamelCase : Dict = DataLoader(A__\t,\t\t\t\t\t\tshuffle=A__\t,\t\t\t\t\t\tbatch_size=A__\t,\t\t\t\t\t\tnum_workers=4 )\r\n\t\t\t\t\t\treturn (train_dataloader, valid_dataloader)\r\n\r\n\r\n\r\n\r\n\r\ndef \ta_ (\t\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase=None ):\r\n\t\t\t\t\t\t_UpperCamelCase : str = []\r\n\t\t\t\t\t\tfor epoch in range(A__ ):\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Train quickly\r\n\t\t\t\t\t\t\t\t\t\t\t\tmodel.train()\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor batch in dataloader:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : str = batch\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = model(A__ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : str = torch.nn.functional.mse_loss(A__\t,\t\t\t\t\t\tA__ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.backward(A__ )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toptimizer.step()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toptimizer.zero_grad()\r\n\t\t\t\t\t\t\t\t\t\t\t\trands.append(random.random() ) # Introduce some randomness\r\n\t\t\t\t\t\t\t\t\t\t\t\tif scheduler is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tscheduler.step()\r\n\t\t\t\t\t\treturn rands\r\n\r\n\r\n\r\n\r\nclass \t\t\t_a\t\t\t\t\t\t(\t\t\t\tnn.Module ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef __init__(\t\t\tself\t\t: Dict\t\t\t\t\t\t\t) ->\t\t\t\tTuple:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\tsuper().__init__()\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = nn.Parameter(torch.randn(1\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = nn.Parameter(torch.randn(1\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: List[Any],\t\t\tlowerCAmelCase__\t\t: Optional[Any]\t\t\t\t\t\t\t) ->\t\t\t\tOptional[int]:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\treturn x * self.a + self.b\r\n\r\n\r\n\r\n\r\nclass \t\t\t_a\t\t\t\t\t\t(\t\t\t\tunittest.TestCase ):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: str\t\t\t\t\t\t\t) ->\t\t\t\tOptional[int]:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_seed(4_2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[int] = torch.optim.Adam(params=model.parameters(),\t\t\tlr=1e-3\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = dummy_dataloaders()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : str = ProjectConfiguration(total_limit=1,\t\t\tproject_dir=UpperCamelCase_,\t\t\tautomatic_checkpoint_naming=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Train baseline\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : str = Accelerator(project_config=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : Tuple = accelerator.prepare(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save initial\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save second state\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(len(os.listdir(accelerator.project_dir\t\t\t\t\t\t\t)\t\t\t\t\t\t\t),\t\t\t1\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: Dict\t\t\t\t\t\t\t) ->\t\t\t\tTuple:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_seed(4_2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[Any] = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = torch.optim.Adam(params=model.parameters(),\t\t\tlr=1e-3\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : str = dummy_dataloaders()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Train baseline\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Union[str, Any] = Accelerator()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = accelerator.prepare(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save initial\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Union[str, Any] = os.path.join(UpperCamelCase_,\t\t\t'''initial'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : Union[str, Any] = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = optimizer.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = train(3,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : List[str] = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = optimizer.state_dict()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Train partially\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_seed(4_2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[int] = torch.optim.Adam(params=model.parameters(),\t\t\tlr=1e-3\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[str] = dummy_dataloaders()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Tuple = Accelerator()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : int = accelerator.prepare(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.load_state(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : Tuple = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = optimizer.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[Any] = train(2,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save everything\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = os.path.join(UpperCamelCase_,\t\t\t'''checkpoint'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Load everything back in and make sure all states work\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.load_state(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttest_rands += train(1,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : List[str] = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : str = optimizer.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: int\t\t\t\t\t\t\t) ->\t\t\t\tstr:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_seed(4_2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = torch.optim.Adam(params=model.parameters(),\t\t\tlr=1e-3\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[str] = dummy_dataloaders()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[Any] = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Train baseline\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = Accelerator(project_dir=UpperCamelCase_,\t\t\tproject_config=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = accelerator.prepare(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save initial\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : List[Any] = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Union[str, Any] = optimizer.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = train(3,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : Any = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[int] = optimizer.state_dict()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Train partially\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_seed(4_2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = torch.optim.Adam(params=model.parameters(),\t\t\tlr=1e-3\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : Dict = dummy_dataloaders()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = ProjectConfiguration(iteration=1,\t\t\tautomatic_checkpoint_naming=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Any = Accelerator(project_dir=UpperCamelCase_,\t\t\tproject_config=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : Optional[Any] = accelerator.prepare(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.load_state(os.path.join(UpperCamelCase_,\t\t\t'''checkpoints''',\t\t\t'''checkpoint_0'''\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : Optional[int] = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = optimizer.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Tuple = train(2,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save everything\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Load everything back in and make sure all states work\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.load_state(os.path.join(UpperCamelCase_,\t\t\t'''checkpoints''',\t\t\t'''checkpoint_1'''\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttest_rands += train(1,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t((_UpperCamelCase) ,\t\t\t\t\t\t\t(_UpperCamelCase)) : Optional[int] = model.a.item(), model.b.item()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = optimizer.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: List[str]\t\t\t\t\t\t\t) ->\t\t\t\tTuple:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = torch.tensor([1, 2, 3]\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = torch.tensor([2, 3, 4]\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = torch.optim.Adam(net.parameters()\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : str = Accelerator()\r\n\t\t\t\t\t\t\t\t\t\twith self.assertRaises(UpperCamelCase_\t\t\t\t\t\t\t) as ve:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.register_for_checkpointing(UpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = str(ve.exception\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tself.assertTrue('''Item at index 0''' in message\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tself.assertTrue('''Item at index 1''' in message\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tself.assertFalse('''Item at index 2''' in message\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\tself.assertFalse('''Item at index 3''' in message\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: int\t\t\t\t\t\t\t) ->\t\t\t\tList[str]:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_seed(4_2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : str = torch.optim.Adam(params=model.parameters(),\t\t\tlr=1e-3\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = torch.optim.lr_scheduler.StepLR(UpperCamelCase_,\t\t\tstep_size=1,\t\t\tgamma=0.99\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : Any = dummy_dataloaders()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Union[str, Any] = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Train baseline\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = Accelerator(project_dir=UpperCamelCase_,\t\t\tproject_config=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : Dict = accelerator.prepare(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save initial\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = scheduler.state_dict()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttrain(3,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertNotEqual(UpperCamelCase_,\t\t\tscheduler.state_dict()\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Load everything back in and make sure all states work\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.load_state(os.path.join(UpperCamelCase_,\t\t\t'''checkpoints''',\t\t\t'''checkpoint_0'''\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCamelCase_,\t\t\tscheduler.state_dict()\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: List[Any]\t\t\t\t\t\t\t) ->\t\t\t\tAny:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmpdir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_seed(4_2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Tuple = DummyModel()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Any = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_,\t\t\ttotal_limit=2\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Train baseline\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Any = Accelerator(project_dir=UpperCamelCase_,\t\t\tproject_config=UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Tuple = accelerator.prepare(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save 3 states:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor _ in range(1_1\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.save_state()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(not os.path.exists(os.path.join(UpperCamelCase_,\t\t\t'''checkpoints''',\t\t\t'''checkpoint_0'''\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(os.path.exists(os.path.join(UpperCamelCase_,\t\t\t'''checkpoints''',\t\t\t'''checkpoint_9'''\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(os.path.exists(os.path.join(UpperCamelCase_,\t\t\t'''checkpoints''',\t\t\t'''checkpoint_10'''\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t@require_cuda\r\n\t\t\t\tdef snake_case (\t\t\tself\t\t: Any\t\t\t\t\t\t\t) ->\t\t\t\tOptional[Any]:\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : int = ['''torchrun''', f\"\"\"--nproc_per_node={torch.cuda.device_count()}\"\"\", inspect.getfile(self.__class__\t\t\t\t\t\t\t)]\r\n\t\t\t\t\t\t\t\t\t\texecute_subprocess_async(UpperCamelCase_,\t\t\tenv=os.environ.copy()\t\t\t\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"/tmp/accelerate/state_checkpointing\"\"\"\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=DummyModel()\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=torch.optim.Adam(params=model.parameters(), lr=1e-3)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=dummy_dataloaders()\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=ProjectConfiguration(automatic_checkpoint_naming=True)\r\n\t\t\t\t\t\t# Train baseline\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=Accelerator(project_dir=savedir, project_config=project_config, mixed_precision=\"\"\"no\"\"\")\r\n\t\t\t\t\t\tif accelerator.process_index == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif os.path.exists(savedir):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshutil.rmtree(savedir)\r\n\t\t\t\t\t\t\t\t\t\t\t\tos.makedirs(savedir)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=accelerator.prepare(\r\n\t\t\t\t\t\t model, optimizer, train_dataloader, valid_dataloader, scheduler\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=accelerator.prepare(model, optimizer)\r\n\t\t\t\t\t\ttrain(3, model, train_dataloader, optimizer, accelerator, scheduler)\r\n\t\t\t\t\t\t# Check that the intial optimizer is loaded on the GPU\r\n\t\t\t\t\t\tfor group in optimizer.param_groups:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=group[\"\"\"params\"\"\"][0].device\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tassert param_device.type == accelerator.device.type\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=model.cpu()\r\n\t\t\t\t\t\taccelerator.wait_for_everyone()\r\n\t\t\t\t\t\taccelerator.save_state()\r\n\t\t\t\t\t\taccelerator.wait_for_everyone()\r\n\r\n\t\t\t\t\t\t# Check CPU state\r\n\t\t\t\t\t\taccelerator.load_state(os.path.join(savedir, \"\"\"checkpoints\"\"\", \"\"\"checkpoint_0\"\"\"), map_location=\"\"\"cpu\"\"\")\r\n\t\t\t\t\t\tfor group in optimizer.param_groups:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=group[\"\"\"params\"\"\"][0].device\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tassert (\r\n\t\t\t\t\t\t param_device.type == torch.device(\"\"\"cpu\"\"\").type\r\n\t\t\t\t\t\t), F\"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}\"\r\n\r\n\t\t\t\t\t\t# Check device state\r\n\t\t\t\t\t\tmodel.to(accelerator.device)\r\n\t\t\t\t\t\taccelerator.load_state(os.path.join(savedir, \"\"\"checkpoints\"\"\", \"\"\"checkpoint_0\"\"\"), map_location=\"\"\"on_device\"\"\")\r\n\t\t\t\t\t\tfor group in optimizer.param_groups:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=group[\"\"\"params\"\"\"][0].device\r\n\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\tassert (\r\n\t\t\t\t\t\t param_device.type == accelerator.device.type\r\n\t\t\t\t\t\t), F\"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}\"\r\n\r\n\t\t\t\t\t\t# Check error\r\n\t\t\t\t\t\twith pytest.raises(TypeError, match=\"\"\"Unsupported optimizer map location passed\"\"\"):\r\n\t\t\t\t\t\t\t\t\t\t\t\taccelerator.load_state(os.path.join(savedir, \"\"\"checkpoints\"\"\", \"\"\"checkpoint_0\"\"\"), map_location=\"\"\"invalid\"\"\")\r\n\t\t\t\t\t\taccelerator.wait_for_everyone()\r\n\t\t\t\t\t\tif accelerator.process_index == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\tshutil.rmtree(savedir)\r\n\t\t\t\t\t\taccelerator.wait_for_everyone()\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":357,"string":"357"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\nimport datasets\r\nimport faiss\r\nimport numpy as np\r\nimport streamlit as st\r\nimport torch\r\nfrom elasticsearch import Elasticsearch\r\nfrom elia_utils import (\r\n embed_questions_for_retrieval,\r\n make_qa_sas_model,\r\n qa_sas_generate,\r\n query_es_index,\r\n query_qa_dense_index,\r\n)\r\n\r\nimport transformers\r\nfrom transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer\r\n\r\n\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"bart\"\"\"\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=True\r\n\r\n\r\n\r\n\r\n\r\n@st.cache(allow_output_mutation=_lowercase )\r\ndef \ta_ (\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\tif LOAD_DENSE_INDEX:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[Any] = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Union[str, Any] = qar_model.eval()\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : str = (None, None)\r\n\t\t\t\t\t\tif MODEL_TYPE == \"bart\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' )\r\n\t\t\t\t\t\t\t\t\t\t\t\tsas_model.load_state_dict(save_dict['''model'''] )\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Dict = sas_model.eval()\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = make_qa_sas_model(\r\n\t\t\t\t\t\t\t\t\t\t\t\t model_name='''t5-small'''\t,\t\t\t\t\t\tfrom_file='''seq2seq_models/eli5_t5_model_1024_4.pth'''\t,\t\t\t\t\t\tdevice='''cuda:0''' )\r\n\t\t\t\t\t\treturn (qar_tokenizer, qar_model, sas_tokenizer, sas_model)\r\n\r\n\r\n\r\n\r\n\r\n@st.cache(allow_output_mutation=_lowercase )\r\ndef \ta_ (\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\tif LOAD_DENSE_INDEX:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = faiss.StandardGpuResources()\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[str] = datasets.load_dataset(path='''wiki_snippets'''\t,\t\t\t\t\t\tname='''wiki40b_en_100_0''' )['''train''']\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Tuple = np.memmap(\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat'''\t,\t\t\t\t\t\tdtype='''float32'''\t,\t\t\t\t\t\tmode='''r'''\t,\t\t\t\t\t\tshape=(wikiaab_passages.num_rows, 128)\t,\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Optional[int] = faiss.IndexFlatIP(128 )\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : Tuple = faiss.index_cpu_to_gpu(_lowercase\t,\t\t\t\t\t\t1\t,\t\t\t\t\t\t_lowercase )\r\n\t\t\t\t\t\t\t\t\t\t\t\twikiaab_gpu_index_flat.add(_lowercase ) # TODO fix for larger GPU\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : Tuple = (None, None)\r\n\t\t\t\t\t\t_UpperCamelCase : List[Any] = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] )\r\n\t\t\t\t\t\treturn (wikiaab_passages, wikiaab_gpu_index_flat, es_client)\r\n\r\n\r\n\r\n\r\n\r\n@st.cache(allow_output_mutation=_lowercase )\r\ndef \ta_ (\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t_UpperCamelCase : Optional[Any] = datasets.load_dataset('''eli5'''\t,\t\t\t\t\t\tname='''LFQA_reddit''' )\r\n\t\t\t\t\t\t_UpperCamelCase : Any = elia['''train_eli5''']\r\n\t\t\t\t\t\t_UpperCamelCase : Union[str, Any] = np.memmap(\r\n\t\t\t\t\t\t '''eli5_questions_reps.dat'''\t,\t\t\t\t\t\tdtype='''float32'''\t,\t\t\t\t\t\tmode='''r'''\t,\t\t\t\t\t\tshape=(elia_train.num_rows, 128) )\r\n\t\t\t\t\t\t_UpperCamelCase : str = faiss.IndexFlatIP(128 )\r\n\t\t\t\t\t\teli5_train_q_index.add(_lowercase )\r\n\t\t\t\t\t\treturn (elia_train, eli5_train_q_index)\r\n\r\n\r\nUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=load_indexes()\r\nUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=load_models()\r\nUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=load_train_data()\r\n\r\n\r\n\r\n\r\n\r\ndef \ta_ (\t\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase=10 ):\r\n\t\t\t\t\t\t_UpperCamelCase : Any = embed_questions_for_retrieval([question]\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase )\r\n\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = eli5_train_q_index.search(_lowercase\t,\t\t\t\t\t\t_lowercase )\r\n\t\t\t\t\t\t_UpperCamelCase : Tuple = [elia_train[int(_lowercase )] for i in I[0]]\r\n\t\t\t\t\t\treturn nn_examples\r\n\r\n\r\n\r\n\r\n\r\ndef \ta_ (\t\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase=\"wiki40b\"\t,\t\t\t\t\t\t_lowercase=\"dense\"\t,\t\t\t\t\t\t_lowercase=10 ):\r\n\t\t\t\t\t\tif source == \"none\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[str] = ('''
'''.join(['''''' for _ in range(11 )] ).strip(), [])\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif method == \"dense\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : Dict = query_qa_dense_index(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase )\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase ,\t\t\t\t\t\t\t_UpperCamelCase : List[str] = query_es_index(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t _lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\tindex_name='''english_wiki40b_snippets_100w'''\t,\t\t\t\t\t\tn_results=_lowercase\t,\t\t\t\t\t\t)\r\n\t\t\t\t\t\t_UpperCamelCase : Any = [\r\n\t\t\t\t\t\t (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst\r\n\t\t\t\t\t\t]\r\n\t\t\t\t\t\t_UpperCamelCase : List[Any] = '''question: {} context: {}'''.format(_lowercase\t,\t\t\t\t\t\t_lowercase )\r\n\t\t\t\t\t\treturn question_doc, support_list\r\n\r\n\r\n\r\n\r\n\r\n@st.cache(\r\n hash_funcs={\r\n torch.Tensor: (lambda _lowercase : None),\r\n transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowercase : None),\r\n } )\r\ndef \ta_ (\t\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase=64\t,\t\t\t\t\t\t_lowercase=256\t,\t\t\t\t\t\t_lowercase=False\t,\t\t\t\t\t\t_lowercase=2\t,\t\t\t\t\t\t_lowercase=0.95\t,\t\t\t\t\t\t_lowercase=0.8 ):\r\n\t\t\t\t\t\twith torch.no_grad():\r\n\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase : List[Any] = qa_sas_generate(\r\n\t\t\t\t\t\t\t\t\t\t\t\t _lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\t_lowercase\t,\t\t\t\t\t\tnum_answers=1\t,\t\t\t\t\t\tnum_beams=_lowercase\t,\t\t\t\t\t\tmin_len=_lowercase\t,\t\t\t\t\t\tmax_len=_lowercase\t,\t\t\t\t\t\tdo_sample=_lowercase\t,\t\t\t\t\t\ttemp=_lowercase\t,\t\t\t\t\t\ttop_p=_lowercase\t,\t\t\t\t\t\ttop_k=_lowercase\t,\t\t\t\t\t\tmax_input_length=1024\t,\t\t\t\t\t\tdevice='''cuda:0'''\t,\t\t\t\t\t\t)[0]\r\n\t\t\t\t\t\treturn (answer, support_list)\r\n\r\n\r\nst.title(\"\"\"Long Form Question Answering with ELI5\"\"\")\r\n\r\n# Start sidebar\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"\"\"\"\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"\n\n
\n \n \n \n \n %s\n \n \n\n\"\"\" % (\r\n header_html,\r\n)\r\nst.sidebar.markdown(\r\n header_full,\r\n unsafe_allow_html=True,\r\n)\r\n\r\n# Long Form QA with ELI5 and Wikipedia\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n\"\"\"\r\nst.sidebar.markdown(description, unsafe_allow_html=True)\r\n\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=[\r\n \"\"\"Answer the question\"\"\",\r\n \"\"\"View the retrieved document only\"\"\",\r\n \"\"\"View the most similar ELI5 question and answer\"\"\",\r\n \"\"\"Show me everything, please!\"\"\",\r\n]\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.checkbox(\"\"\"Demo options\"\"\")\r\nif demo_options:\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.selectbox(\r\n\t\t\t\t\t\t \"\"\"\"\"\",\r\n\t\t\t\t\t\t action_list,\r\n\t\t\t\t\t\t index=3,\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=action_list.index(action_st)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.selectbox(\r\n\t\t\t\t\t\t \"\"\"\"\"\",\r\n\t\t\t\t\t\t [\"\"\"Show full text of passages\"\"\", \"\"\"Show passage section titles\"\"\"],\r\n\t\t\t\t\t\t index=0,\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=show_type == \"\"\"Show full text of passages\"\"\"\r\nelse:\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=3\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=True\r\n\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.checkbox(\"\"\"Retrieval options\"\"\")\r\nif retrieval_options:\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n \"\"\"\r\n\t\t\t\t\t\tst.sidebar.markdown(retriever_info)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.selectbox(\"\"\"Which Wikipedia format should the model use?\"\"\", [\"\"\"wiki40b\"\"\", \"\"\"none\"\"\"])\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.selectbox(\"\"\"Which Wikipedia indexer should the model use?\"\"\", [\"\"\"dense\"\"\", \"\"\"sparse\"\"\", \"\"\"mixed\"\"\"])\r\nelse:\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"wiki40b\"\"\"\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"dense\"\"\"\r\n\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"beam\"\"\"\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=2\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=64\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=256\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=None\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=None\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.checkbox(\"\"\"Generation options\"\"\")\r\nif generate_options:\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n \"\"\"\r\n\t\t\t\t\t\tst.sidebar.markdown(generate_info)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.selectbox(\"\"\"Would you like to use beam search or sample an answer?\"\"\", [\"\"\"beam\"\"\", \"\"\"sampled\"\"\"])\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.slider(\r\n\t\t\t\t\t\t \"\"\"Minimum generation length\"\"\", min_value=8, max_value=256, value=64, step=8, format=None, key=None\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.slider(\r\n\t\t\t\t\t\t \"\"\"Maximum generation length\"\"\", min_value=64, max_value=512, value=256, step=16, format=None, key=None\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tif sampled == \"beam\":\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.slider(\"\"\"Beam size\"\"\", min_value=1, max_value=8, value=2, step=None, format=None, key=None)\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.slider(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"Nucleus sampling p\"\"\", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.sidebar.slider(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"Temperature\"\"\", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=None\r\n\r\n# start main text\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=[\r\n \"\"\"\"\"\",\r\n \"\"\"How do people make chocolate?\"\"\",\r\n \"\"\"Why do we get a fever when we are sick?\"\"\",\r\n \"\"\"How can different animals perceive different colors?\"\"\",\r\n \"\"\"What is natural language processing?\"\"\",\r\n \"\"\"What's the best way to treat a sunburn?\"\"\",\r\n \"\"\"What exactly are vitamins ?\"\"\",\r\n \"\"\"How does nuclear energy provide electricity?\"\"\",\r\n \"\"\"What's the difference between viruses and bacteria?\"\"\",\r\n \"\"\"Why are flutes classified as woodwinds when most of them are made out of metal ?\"\"\",\r\n \"\"\"Why do people like drinking coffee even though it tastes so bad?\"\"\",\r\n \"\"\"What happens when wine ages? How does it make the wine taste better?\"\"\",\r\n \"\"\"If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?\"\"\",\r\n \"\"\"How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?\"\"\",\r\n \"\"\"How does New Zealand have so many large bird predators?\"\"\",\r\n]\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.selectbox(\r\n \"\"\"What would you like to ask? ---- select to enter a new query\"\"\",\r\n questions_list,\r\n index=1,\r\n)\r\nif question_s == \"\":\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=st.text_input(\"\"\"Enter your question here:\"\"\", \"\"\"\"\"\")\r\nelse:\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=question_s\r\n\r\nif st.button(\"\"\"Show me!\"\"\"):\r\n\t\t\t\t\t\tif action in [0, 1, 3]:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif index_type == \"mixed\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=make_support(question, source=wiki_source, method=\"\"\"dense\"\"\", n_results=10)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=make_support(question, source=wiki_source, method=\"\"\"sparse\"\"\", n_results=10)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=[]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor res_d, res_s in zip(support_list_dense, support_list_sparse):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif tuple(res_d) not in support_list:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsupport_list += [tuple(res_d)]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif tuple(res_s) not in support_list:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsupport_list += [tuple(res_s)]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=support_list[:10]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"
\"\"\" + \"\"\"
\"\"\".join([res[-1] for res in support_list])\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=make_support(question, source=wiki_source, method=index_type, n_results=10)\r\n\t\t\t\t\t\tif action in [0, 3]:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t, UpperCamelCase_\t\t\t\t\t\t\t\t\t=answer_question(\r\n\t\t\t\t\t\t\t\t\t\t\t\t question_doc,\r\n\t\t\t\t\t\t\t\t\t\t\t\t sas_model,\r\n\t\t\t\t\t\t\t\t\t\t\t\t sas_tokenizer,\r\n\t\t\t\t\t\t\t\t\t\t\t\t min_len=min_len,\r\n\t\t\t\t\t\t\t\t\t\t\t\t max_len=int(max_len),\r\n\t\t\t\t\t\t\t\t\t\t\t\t sampling=(sampled == \"\"\"sampled\"\"\"),\r\n\t\t\t\t\t\t\t\t\t\t\t\t n_beams=n_beams,\r\n\t\t\t\t\t\t\t\t\t\t\t\t top_p=top_p,\r\n\t\t\t\t\t\t\t\t\t\t\t\t temp=temp,\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tst.markdown(\"\"\"### The model generated answer is:\"\"\")\r\n\t\t\t\t\t\t\t\t\t\t\t\tst.write(answer)\r\n\t\t\t\t\t\tif action in [0, 1, 3] and wiki_source != \"none\":\r\n\t\t\t\t\t\t\t\t\t\t\t\tst.markdown(\"\"\"--- \\n ### The model is drawing information from the following Wikipedia passages:\"\"\")\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor i, res in enumerate(support_list):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"https://en.wikipedia.org/wiki/{}\"\"\".format(res[0].replace(\"\"\" \"\"\", \"\"\"_\"\"\"))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=res[1].strip()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif sec_titles == \"\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"[{}]({})\"\"\".format(res[0], wiki_url)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=sec_titles.split(\"\"\" & \"\"\")\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\" & \"\"\".join(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t [\"\"\"[{}]({}#{})\"\"\".format(sec.strip(), wiki_url, sec.strip().replace(\"\"\" \"\"\", \"\"\"_\"\"\")) for sec in sec_list]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tst.markdown(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"{0:02d} - **Article**: {1:<18} _Section_: {2}\"\"\".format(i + 1, res[0], sections),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t unsafe_allow_html=True,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif show_passages:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tst.write(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"> \"\"\" + res[-1] + \"\"\"\"\"\", unsafe_allow_html=True\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\tif action in [2, 3]:\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=find_nearest_training(question)\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=nn_train_list[0]\r\n\t\t\t\t\t\t\t\t\t\t\t\tst.markdown(\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"--- \\n ### The most similar question in the ELI5 training set was: \\n\\n {}\"\"\".format(train_exple[\"\"\"title\"\"\"])\r\n\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t\t\t\t\t=[\r\n\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"{}. {}\"\"\".format(i + 1, \"\"\" \\n\"\"\".join([line.strip() for line in ans.split(\"\"\"\\n\"\"\") if line.strip() != \"\"\"\"\"\"]))\r\n\t\t\t\t\t\t\t\t\t\t\t\t for i, (ans, sc) in enumerate(zip(train_exple[\"\"\"answers\"\"\"][\"\"\"text\"\"\"], train_exple[\"\"\"answers\"\"\"][\"\"\"score\"\"\"]))\r\n\t\t\t\t\t\t\t\t\t\t\t\t if i == 0 or sc > 2\r\n\t\t\t\t\t\t\t\t\t\t\t\t]\r\n\t\t\t\t\t\t\t\t\t\t\t\tst.markdown(\"\"\"##### Its answers were: \\n\\n {}\"\"\".format(\"\"\"\\n\"\"\".join(answers_st)))\r\n\r\n\r\nUpperCamelCase_\t\t\t\t\t\t\t\t\t=\"\"\"\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\nst.sidebar.markdown(disclaimer, unsafe_allow_html=True)\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":128,"string":"128"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":260,"cells":{"code":{"kind":"string","value":"\r'''simple docstring'''\r\r\r\r\r\r\r\rimport argparse\r\rfrom transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta\rfrom transformers.utils import logging\r\r\rlogging.set_verbosity_info()\r\r\r\r\r\r\r\rdef \t\t\t\tSCREAMING_SNAKE_CASE__\t( __A\t\t\t,\t\t\t\t__A\t\t\t,\t\t\t\t__A\t) ->\tstr:\r\t# Initialise PyTorch model\r\t_snake_case \t\t\t\t\t\t=\t\tTaConfig.from_json_file(UpperCamelCase__\t)\r\tprint(F'Building PyTorch model from configuration: {config}'\t)\r\t_snake_case \t\t\t\t\t\t=\t\tTaForConditionalGeneration(UpperCamelCase__\t)\r\r\t# Load weights from tf checkpoint\r\tload_tf_weights_in_ta(UpperCamelCase__\t\t\t,\t\t\t\tUpperCamelCase__\t\t\t,\t\t\t\tUpperCamelCase__\t)\r\r\t# Save pytorch-model\r\tprint(F'Save PyTorch model to {pytorch_dump_path}'\t)\r\tmodel.save_pretrained(UpperCamelCase__\t)\r\r\rif __name__ == \"__main__\":\r\t\t\t\t\tlowercase :\t\t\t\t\t\t\tAny =\t\t\t\t\targparse.ArgumentParser()\r\t\t\t\t\t# Required parameters\r\t\t\t\t\tparser.add_argument(\r\t\t\t\t\t \"--tf_checkpoint_path\", default=None, type=str, required=True, help=\"Path to the TensorFlow checkpoint path.\"\r\t\t\t\t\t)\r\t\t\t\t\tparser.add_argument(\r\t\t\t\t\t \"--config_file\",\r\t\t\t\t\t default=None,\r\t\t\t\t\t type=str,\r\t\t\t\t\t required=True,\r\t\t\t\t\t help=(\r\t\t\t\t\t \"The config json file corresponding to the pre-trained T5 model. \\nThis specifies the model architecture.\"\r\t\t\t\t\t ),\r\t\t\t\t\t)\r\t\t\t\t\tparser.add_argument(\r\t\t\t\t\t \"--pytorch_dump_path\", default=None, type=str, required=True, help=\"Path to the output PyTorch model.\"\r\t\t\t\t\t)\r\t\t\t\t\tlowercase :\t\t\t\t\t\t\tstr =\t\t\t\t\tparser.parse_args()\r\t\t\t\t\tconvert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)\r\r"},"code_codestyle":{"kind":"number","value":42,"string":"42"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\n\r\nfrom collections import namedtuple\r\n\r\nimport requests\r\nfrom lxml import html # type: ignore\r\n\r\n__A\t\t=namedtuple('covid_data', 'cases deaths recovered')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t_UpperCamelCase\t\t\t\t\t(\t\t\t\t\t\tUpperCamelCase__ = \"https://www.worldometers.info/coronavirus/\" ):\r\n\t\t\tUpperCAmelCase__ : Union[str, Any] = \"\"\"//div[@class = \\\"maincounter-number\\\"]/span/text()\"\"\"\r\n\t\t\treturn covid_data(*html.fromstring(requests.get(UpperCamelCase__ ).content ).xpath(UpperCamelCase__ ) )\r\n\r\n\r\n__A\t\t='Total COVID-19 cases in the world: {}\\nTotal deaths due to COVID-19 in the world: {}\\nTotal COVID-19 patients recovered in the world: {}'\r\n\r\n\r\nprint(fmt.format(*covid_stats()))"},"style_context_codestyle":{"kind":"number","value":163,"string":"163"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":261,"cells":{"code":{"kind":"string","value":"\r\r\"\"\"simple docstring\"\"\"\r\r\rimport timeit\r\rimport numpy as np\r\rimport datasets\rfrom datasets.arrow_writer import ArrowWriter\rfrom datasets.features.features import _ArrayXD\r\r\r\r\rdef \t_lowercase ( __lowerCAmelCase\t\t\t\t\t\t\t) ->\t\t\tstr:\r def wrapper(*__lowerCAmelCase\t\t\t\t\t, **__lowerCAmelCase\t\t\t\t\t\t\t):\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\ttimeit.default_timer()\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\tfunc(*__lowerCAmelCase\t\t\t\t\t, **__lowerCAmelCase\t\t\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\ttimeit.default_timer() - starttime\r return delta\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tfunc.__name__\r\r return wrapper\r\r\r\r\rdef \t_lowercase ( __lowerCAmelCase\t\t\t\t\t, __lowerCAmelCase=100\t\t\t\t\t, __lowerCAmelCase=None\t\t\t\t\t\t\t) ->\t\t\tint:\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\t[]\r SCREAMING_SNAKE_CASE__\t\t\t\t: Dict \t\t\t\t\t\t=\t\tseq_shapes or {}\r for i in range(__lowerCAmelCase\t\t\t\t\t\t\t):\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[Any] \t\t\t\t\t\t=\t\t{}\r for col_id, (k, v) in enumerate(features.items()\t\t\t\t\t\t\t):\r if isinstance(__lowerCAmelCase\t\t\t\t\t, _ArrayXD\t\t\t\t\t\t\t):\r SCREAMING_SNAKE_CASE__\t\t\t\t: Dict \t\t\t\t\t\t=\t\tnp.random.rand(*v.shape\t\t\t\t\t\t\t).astype(v.dtype\t\t\t\t\t\t\t)\r elif isinstance(__lowerCAmelCase\t\t\t\t\t, datasets.Value\t\t\t\t\t\t\t):\r if v.dtype == \"string\":\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\t\"\"\"The small grey turtle was surprisingly fast when challenged.\"\"\"\r else:\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tnp.random.randint(10\t\t\t\t\t, size=1\t\t\t\t\t\t\t).astype(v.dtype\t\t\t\t\t\t\t).item()\r elif isinstance(__lowerCAmelCase\t\t\t\t\t, datasets.Sequence\t\t\t\t\t\t\t):\r while isinstance(__lowerCAmelCase\t\t\t\t\t, datasets.Sequence\t\t\t\t\t\t\t):\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[Any] \t\t\t\t\t\t=\t\tv.feature\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tseq_shapes[k]\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tnp.random.rand(*__lowerCAmelCase\t\t\t\t\t\t\t).astype(v.dtype\t\t\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\tdata\r\r dummy_data.append((i, example)\t\t\t\t\t\t\t)\r\r return dummy_data\r\r\r\r\rdef \t_lowercase ( __lowerCAmelCase\t\t\t\t\t, __lowerCAmelCase\t\t\t\t\t, __lowerCAmelCase=100\t\t\t\t\t, __lowerCAmelCase=None\t\t\t\t\t\t\t) ->\t\t\tstr:\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\tgenerate_examples(__lowerCAmelCase\t\t\t\t\t, num_examples=__lowerCAmelCase\t\t\t\t\t, seq_shapes=__lowerCAmelCase\t\t\t\t\t\t\t)\r\r with ArrowWriter(features=__lowerCAmelCase\t\t\t\t\t, path=__lowerCAmelCase\t\t\t\t\t\t\t) as writer:\r for key, record in dummy_data:\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tfeatures.encode_example(__lowerCAmelCase\t\t\t\t\t\t\t)\r writer.write(__lowerCAmelCase\t\t\t\t\t\t\t)\r\r SCREAMING_SNAKE_CASE__\t\t\t\t\t\t,\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\twriter.finalize()\r\r if not num_final_examples == num_examples:\r raise ValueError(\r F'''Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.'''\t\t\t\t\t\t\t)\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tdatasets.Dataset.from_file(filename=__lowerCAmelCase\t\t\t\t\t, info=datasets.DatasetInfo(features=__lowerCAmelCase\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r return dataset\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":56,"string":"56"},"style_context":{"kind":"string","value":"\r\r\"\"\"simple docstring\"\"\"\r\r\rimport unittest\r\rfrom transformers import DebertaConfig, is_torch_available\rfrom transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device\r\rfrom ...test_configuration_common import ConfigTester\rfrom ...test_modeling_common import ModelTesterMixin, ids_tensor\rfrom ...test_pipeline_mixin import PipelineTesterMixin\r\r\rif is_torch_available():\r import torch\r\r from transformers import (\r DebertaForMaskedLM,\r DebertaForQuestionAnswering,\r DebertaForSequenceClassification,\r DebertaForTokenClassification,\r DebertaModel,\r )\r from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST\r\rclass __a\t\t\t\t\t\t\t(UpperCamelCase_):\r\r\r\r\r\r\r '''simple docstring'''\r\r def __init__( self\t\t, _a\t\t, _a=13\t\t, _a=7\t\t, _a=True\t\t, _a=True\t\t, _a=True\t\t, _a=True\t\t, _a=99\t\t, _a=32\t\t, _a=5\t\t, _a=4\t\t, _a=37\t\t, _a=\"gelu\"\t\t, _a=0.1\t\t, _a=0.1\t\t, _a=512\t\t, _a=16\t\t, _a=2\t\t, _a=0.02\t\t, _a=False\t\t, _a=True\t\t, _a=\"None\"\t\t, _a=3\t\t, _a=4\t\t, _a=None\t\t, )\t\t\t\t\t-> List[Any]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tparent\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tbatch_size\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tseq_length\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tis_training\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\tuse_input_mask\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tuse_token_type_ids\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\tuse_labels\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tvocab_size\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\thidden_size\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tnum_hidden_layers\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tnum_attention_heads\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tintermediate_size\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\thidden_act\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\thidden_dropout_prob\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\tattention_probs_dropout_prob\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\tmax_position_embeddings\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\ttype_vocab_size\r SCREAMING_SNAKE_CASE__\t\t\t\t: Dict \t\t\t\t\t\t=\t\ttype_sequence_label_size\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tinitializer_range\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tnum_labels\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tnum_choices\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\trelative_attention\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tposition_biased_input\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tpos_att_type\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tscope\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Any:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\tids_tensor([self.batch_size, self.seq_length]\t\t, self.vocab_size\t\t\t\t\t)\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tNone\r if self.use_input_mask:\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\tids_tensor([self.batch_size, self.seq_length]\t\t, vocab_size=2\t\t\t\t\t)\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tNone\r if self.use_token_type_ids:\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\tids_tensor([self.batch_size, self.seq_length]\t\t, self.type_vocab_size\t\t\t\t\t)\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[Any] \t\t\t\t\t\t=\t\tNone\r SCREAMING_SNAKE_CASE__\t\t\t\t: int \t\t\t\t\t\t=\t\tNone\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\tNone\r if self.use_labels:\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tids_tensor([self.batch_size]\t\t, self.type_sequence_label_size\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[Any] \t\t\t\t\t\t=\t\tids_tensor([self.batch_size, self.seq_length]\t\t, self.num_labels\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\tids_tensor([self.batch_size]\t\t, self.num_choices\t\t\t\t\t)\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tself.get_config()\r\r return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Tuple:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r return DebertaConfig(\r vocab_size=self.vocab_size\t\t, hidden_size=self.hidden_size\t\t, num_hidden_layers=self.num_hidden_layers\t\t, num_attention_heads=self.num_attention_heads\t\t, intermediate_size=self.intermediate_size\t\t, hidden_act=self.hidden_act\t\t, hidden_dropout_prob=self.hidden_dropout_prob\t\t, attention_probs_dropout_prob=self.attention_probs_dropout_prob\t\t, max_position_embeddings=self.max_position_embeddings\t\t, type_vocab_size=self.type_vocab_size\t\t, initializer_range=self.initializer_range\t\t, relative_attention=self.relative_attention\t\t, position_biased_input=self.position_biased_input\t\t, pos_att_type=self.pos_att_type\t\t, )\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Any:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tself.get_config()\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\t300\r return config\r\r def _a ( self\t\t, _a\t\t\t\t\t)\t\t\t\t\t-> List[str]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r self.parent.assertListEqual(list(result.loss.size()\t\t\t\t\t)\t\t, []\t\t\t\t\t)\r\r def _a ( self\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t\t\t\t)\t\t\t\t\t-> Dict:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Dict \t\t\t\t\t\t=\t\tDebertaModel(config=_a\t\t\t\t\t)\r model.to(_a\t\t\t\t\t)\r model.eval()\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\tmodel(_a\t\t, attention_mask=_a\t\t, token_type_ids=_a\t\t\t\t\t)[0]\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tmodel(_a\t\t, token_type_ids=_a\t\t\t\t\t)[0]\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tmodel(_a\t\t\t\t\t)[0]\r\r self.parent.assertListEqual(list(sequence_output.size()\t\t\t\t\t)\t\t, [self.batch_size, self.seq_length, self.hidden_size]\t\t\t\t\t)\r\r def _a ( self\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t\t\t\t)\t\t\t\t\t-> Tuple:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[Any] \t\t\t\t\t\t=\t\tDebertaForMaskedLM(config=_a\t\t\t\t\t)\r model.to(_a\t\t\t\t\t)\r model.eval()\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tmodel(_a\t\t, attention_mask=_a\t\t, token_type_ids=_a\t\t, labels=_a\t\t\t\t\t)\r\r self.parent.assertEqual(result.logits.shape\t\t, (self.batch_size, self.seq_length, self.vocab_size)\t\t\t\t\t)\r\r def _a ( self\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t\t\t\t)\t\t\t\t\t-> Dict:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\tself.num_labels\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\tDebertaForSequenceClassification(_a\t\t\t\t\t)\r model.to(_a\t\t\t\t\t)\r model.eval()\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\tmodel(_a\t\t, attention_mask=_a\t\t, token_type_ids=_a\t\t, labels=_a\t\t\t\t\t)\r self.parent.assertListEqual(list(result.logits.size()\t\t\t\t\t)\t\t, [self.batch_size, self.num_labels]\t\t\t\t\t)\r self.check_loss_output(_a\t\t\t\t\t)\r\r def _a ( self\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t\t\t\t)\t\t\t\t\t-> List[Any]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\tself.num_labels\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[Any] \t\t\t\t\t\t=\t\tDebertaForTokenClassification(config=_a\t\t\t\t\t)\r model.to(_a\t\t\t\t\t)\r model.eval()\r SCREAMING_SNAKE_CASE__\t\t\t\t: int \t\t\t\t\t\t=\t\tmodel(_a\t\t, attention_mask=_a\t\t, token_type_ids=_a\t\t, labels=_a\t\t\t\t\t)\r self.parent.assertEqual(result.logits.shape\t\t, (self.batch_size, self.seq_length, self.num_labels)\t\t\t\t\t)\r\r def _a ( self\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t, _a\t\t\t\t\t)\t\t\t\t\t-> Union[str, Any]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[Any] \t\t\t\t\t\t=\t\tDebertaForQuestionAnswering(config=_a\t\t\t\t\t)\r model.to(_a\t\t\t\t\t)\r model.eval()\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tmodel(\r _a\t\t, attention_mask=_a\t\t, token_type_ids=_a\t\t, start_positions=_a\t\t, end_positions=_a\t\t, )\r self.parent.assertEqual(result.start_logits.shape\t\t, (self.batch_size, self.seq_length)\t\t\t\t\t)\r self.parent.assertEqual(result.end_logits.shape\t\t, (self.batch_size, self.seq_length)\t\t\t\t\t)\r\r\r\r\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Dict:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tself.prepare_config_and_inputs()\r (\r (\r SCREAMING_SNAKE_CASE__\r )\t\t\t\t\t\t,\t\t\t\t\t\t(\r SCREAMING_SNAKE_CASE__\r )\t\t\t\t\t\t,\t\t\t\t\t\t(\r SCREAMING_SNAKE_CASE__\r )\t\t\t\t\t\t,\t\t\t\t\t\t(\r SCREAMING_SNAKE_CASE__\r )\t\t\t\t\t\t,\t\t\t\t\t\t(\r SCREAMING_SNAKE_CASE__\r )\t\t\t\t\t\t,\t\t\t\t\t\t(\r SCREAMING_SNAKE_CASE__\r )\t\t\t\t\t\t,\t\t\t\t\t\t(\r SCREAMING_SNAKE_CASE__\r )\t\t\t\t\t\t,\t\t\t\t\t\t\r )\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tconfig_and_inputs\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\t{\"\"\"input_ids\"\"\": input_ids, \"\"\"token_type_ids\"\"\": token_type_ids, \"\"\"attention_mask\"\"\": input_mask}\r return config, inputs_dict\r\r\r\r\r\r@require_torch\rclass __a\t\t\t\t\t\t\t(UpperCamelCase_\t\t\t\t,\t\tUpperCamelCase_\t\t\t\t,\t\tunittest.TestCase):\r\r\r\r\r\r\r '''simple docstring'''\r _SCREAMING_SNAKE_CASE :List[str] =\t(\r (\r DebertaModel,\r DebertaForMaskedLM,\r DebertaForSequenceClassification,\r DebertaForTokenClassification,\r DebertaForQuestionAnswering,\r )\r if is_torch_available()\r else ()\r )\r _SCREAMING_SNAKE_CASE :str =\t(\r {\r \"\"\"feature-extraction\"\"\": DebertaModel,\r \"\"\"fill-mask\"\"\": DebertaForMaskedLM,\r \"\"\"question-answering\"\"\": DebertaForQuestionAnswering,\r \"\"\"text-classification\"\"\": DebertaForSequenceClassification,\r \"\"\"token-classification\"\"\": DebertaForTokenClassification,\r \"\"\"zero-shot\"\"\": DebertaForSequenceClassification,\r }\r if is_torch_available()\r else {}\r )\r\r _SCREAMING_SNAKE_CASE :Union[str, Any] =\tTrue\r _SCREAMING_SNAKE_CASE :str =\tFalse\r _SCREAMING_SNAKE_CASE :Dict =\tFalse\r _SCREAMING_SNAKE_CASE :Dict =\tFalse\r _SCREAMING_SNAKE_CASE :Union[str, Any] =\tFalse\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Optional[Any]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[Any] \t\t\t\t\t\t=\t\tDebertaModelTester(self\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tConfigTester(self\t\t, config_class=_a\t\t, hidden_size=37\t\t\t\t\t)\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Any:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r self.config_tester.run_common_tests()\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> int:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tself.model_tester.prepare_config_and_inputs()\r self.model_tester.create_and_check_deberta_model(*_a\t\t\t\t\t)\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Optional[Any]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\tself.model_tester.prepare_config_and_inputs()\r self.model_tester.create_and_check_deberta_for_sequence_classification(*_a\t\t\t\t\t)\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Tuple:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Any \t\t\t\t\t\t=\t\tself.model_tester.prepare_config_and_inputs()\r self.model_tester.create_and_check_deberta_for_masked_lm(*_a\t\t\t\t\t)\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Dict:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: str \t\t\t\t\t\t=\t\tself.model_tester.prepare_config_and_inputs()\r self.model_tester.create_and_check_deberta_for_question_answering(*_a\t\t\t\t\t)\r\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Union[str, Any]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: int \t\t\t\t\t\t=\t\tself.model_tester.prepare_config_and_inputs()\r self.model_tester.create_and_check_deberta_for_token_classification(*_a\t\t\t\t\t)\r\r\r\r\r\r @slow\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Optional[int]:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:\r SCREAMING_SNAKE_CASE__\t\t\t\t: Dict \t\t\t\t\t\t=\t\tDebertaModel.from_pretrained(_a\t\t\t\t\t)\r self.assertIsNotNone(_a\t\t\t\t\t)\r\r\r\r\r\r@require_torch\r@require_sentencepiece\r@require_tokenizers\rclass __a\t\t\t\t\t\t\t(unittest.TestCase):\r\r\r\r\r\r\r '''simple docstring'''\r\r @unittest.skip(reason=\"\"\"Model not available yet\"\"\"\t\t\t\t\t)\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> Any:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r pass\r\r\r\r\r\r @slow\r def _a ( self\t\t\t\t\t)\t\t\t\t\t-> int:\r\r\r \"\"\"simple docstring\"\"\"\r\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: List[str] \t\t\t\t\t\t=\t\tDebertaModel.from_pretrained(\"\"\"microsoft/deberta-base\"\"\"\t\t\t\t\t)\r\r SCREAMING_SNAKE_CASE__\t\t\t\t: Tuple \t\t\t\t\t\t=\t\ttorch.tensor([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]]\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\ttorch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]\t\t\t\t\t)\r with torch.no_grad():\r SCREAMING_SNAKE_CASE__\t\t\t\t: Optional[int] \t\t\t\t\t\t=\t\tmodel(_a\t\t, attention_mask=_a\t\t\t\t\t)[0]\r # compare the actual values for a slice.\r SCREAMING_SNAKE_CASE__\t\t\t\t: Union[str, Any] \t\t\t\t\t\t=\t\ttorch.tensor(\r [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]]\t\t\t\t\t)\r self.assertTrue(torch.allclose(output[:, 1:4, 1:4]\t\t, _a\t\t, atol=1E-4\t\t\t\t\t)\t\t, f'''{output[:, 1:4, 1:4]}'''\t\t\t\t\t)\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":56,"string":"56"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":262,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\nimport os\r\nimport unicodedata\r\nfrom shutil import copyfile\r\nfrom typing import Any, Dict, List, Optional, Tuple\r\n\r\nimport sentencepiece as spm\r\n\r\nfrom ...tokenization_utils import AddedToken, PreTrainedTokenizer\r\nfrom ...utils import logging\r\n\r\n\r\n_lowerCamelCase :\tDict =\t\t\t\tlogging.get_logger(__name__)\r\n_lowerCamelCase :\tOptional[Any] =\t\t\t\t{\"\"\"vocab_file\"\"\": \"\"\"spiece.model\"\"\"}\r\n\r\n_lowerCamelCase :\tTuple =\t\t\t\t{\r\n \"\"\"vocab_file\"\"\": {\r\n \"\"\"albert-base-v1\"\"\": \"\"\"https://huggingface.co/albert-base-v1/resolve/main/spiece.model\"\"\",\r\n \"\"\"albert-large-v1\"\"\": \"\"\"https://huggingface.co/albert-large-v1/resolve/main/spiece.model\"\"\",\r\n \"\"\"albert-xlarge-v1\"\"\": \"\"\"https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model\"\"\",\r\n \"\"\"albert-xxlarge-v1\"\"\": \"\"\"https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model\"\"\",\r\n \"\"\"albert-base-v2\"\"\": \"\"\"https://huggingface.co/albert-base-v2/resolve/main/spiece.model\"\"\",\r\n \"\"\"albert-large-v2\"\"\": \"\"\"https://huggingface.co/albert-large-v2/resolve/main/spiece.model\"\"\",\r\n \"\"\"albert-xlarge-v2\"\"\": \"\"\"https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model\"\"\",\r\n \"\"\"albert-xxlarge-v2\"\"\": \"\"\"https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model\"\"\",\r\n }\r\n}\r\n\r\n_lowerCamelCase :\tint =\t\t\t\t{\r\n \"\"\"albert-base-v1\"\"\": 512,\r\n \"\"\"albert-large-v1\"\"\": 512,\r\n \"\"\"albert-xlarge-v1\"\"\": 512,\r\n \"\"\"albert-xxlarge-v1\"\"\": 512,\r\n \"\"\"albert-base-v2\"\"\": 512,\r\n \"\"\"albert-large-v2\"\"\": 512,\r\n \"\"\"albert-xlarge-v2\"\"\": 512,\r\n \"\"\"albert-xxlarge-v2\"\"\": 512,\r\n}\r\n\r\n_lowerCamelCase :\tList[Any] =\t\t\t\t\"\"\"▁\"\"\"\r\n\r\nclass \t\t\t\tlowercase\t\t\t\t\t(\t\t\tUpperCamelCase__):\r\n\t\t\t\t__lowerCAmelCase\t\t\t:\t\t\tList[Any] \t\t\t\t= VOCAB_FILES_NAMES\r\n\t\t\t\t__lowerCAmelCase\t\t\t:\t\t\tint \t\t\t\t= PRETRAINED_VOCAB_FILES_MAP\r\n\t\t\t\t__lowerCAmelCase\t\t\t:\t\t\tDict \t\t\t\t= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef __init__(\t\t\t\t\t\t\tself : Any\t\t\t\t\t, _lowerCamelCase : List[str]\t\t\t\t\t, _lowerCamelCase : List[Any]=True\t\t\t\t\t, _lowerCamelCase : int=True\t\t\t\t\t, _lowerCamelCase : List[Any]=False\t\t\t\t\t, _lowerCamelCase : Union[str, Any]=\"[CLS]\"\t\t\t\t\t, _lowerCamelCase : str=\"[SEP]\"\t\t\t\t\t, _lowerCamelCase : List[Any]=\"\"\t\t\t\t\t, _lowerCamelCase : Optional[Any]=\"[SEP]\"\t\t\t\t\t, _lowerCamelCase : List[str]=\"\"\t\t\t\t\t, _lowerCamelCase : Optional[Any]=\"[CLS]\"\t\t\t\t\t, _lowerCamelCase : List[Any]=\"[MASK]\"\t\t\t\t\t, _lowerCamelCase : Optional[int] = None\t\t\t\t\t, **_lowerCamelCase : Any\t\t\t\t\t, ):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : List[str]\t\t =\t\t\t\t\t\t(\r\n\t\t\t\t\t AddedToken(lowerCAmelCase__\t\t\t\t\t, lstrip=lowerCAmelCase__\t\t\t\t\t, rstrip=lowerCAmelCase__\t\t\t\t\t, normalized=lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\t if isinstance(lowerCAmelCase__\t\t\t\t\t, lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\t else mask_token\r\n\t\t\t\t\t)\r\n\r\n\t\t\t\t\tA_ : Dict\t\t =\t\t\t\t\t\t{} if sp_model_kwargs is None else sp_model_kwargs\r\n\r\n\t\t\t\t\tsuper().__init__(\r\n\t\t\t\t\t do_lower_case=lowerCAmelCase__\t\t\t\t\t, remove_space=lowerCAmelCase__\t\t\t\t\t, keep_accents=lowerCAmelCase__\t\t\t\t\t, bos_token=lowerCAmelCase__\t\t\t\t\t, eos_token=lowerCAmelCase__\t\t\t\t\t, unk_token=lowerCAmelCase__\t\t\t\t\t, sep_token=lowerCAmelCase__\t\t\t\t\t, pad_token=lowerCAmelCase__\t\t\t\t\t, cls_token=lowerCAmelCase__\t\t\t\t\t, mask_token=lowerCAmelCase__\t\t\t\t\t, sp_model_kwargs=self.sp_model_kwargs\t\t\t\t\t, **lowerCAmelCase__\t\t\t\t\t, )\r\n\r\n\t\t\t\t\tA_ : Tuple\t\t =\t\t\t\t\t\tdo_lower_case\r\n\t\t\t\t\tA_ : int\t\t =\t\t\t\t\t\tremove_space\r\n\t\t\t\t\tA_ : List[Any]\t\t =\t\t\t\t\t\tkeep_accents\r\n\t\t\t\t\tA_ : List[Any]\t\t =\t\t\t\t\t\tvocab_file\r\n\r\n\t\t\t\t\tA_ : List[str]\t\t =\t\t\t\t\t\tspm.SentencePieceProcessor(**self.sp_model_kwargs\t\t\t\t)\r\n\t\t\t\t\tself.sp_model.Load(lowerCAmelCase__\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t@property\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Optional[int]\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn len(self.sp_model\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Optional[int]\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : Tuple\t\t =\t\t\t\t\t\t{self.convert_ids_to_tokens(lowerCAmelCase__\t\t\t\t): i for i in range(self.vocab_size\t\t\t\t)}\r\n\t\t\t\t\tvocab.update(self.added_tokens_encoder\t\t\t\t)\r\n\t\t\t\t\treturn vocab\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef __getstate__(\t\t\t\t\t\t\tself : Any\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : Union[str, Any]\t\t =\t\t\t\t\t\tself.__dict__.copy()\r\n\t\t\t\t\tA_ : Optional[int]\t\t =\t\t\t\t\t\tNone\r\n\t\t\t\t\treturn state\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef __setstate__(\t\t\t\t\t\t\tself : Dict\t\t\t\t\t, _lowerCamelCase : Any\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : List[Any]\t\t =\t\t\t\t\t\td\r\n\r\n\t\t\t\t\t# for backward compatibility\r\n\t\t\t\t\tif not hasattr(self\t\t\t\t\t, '''sp_model_kwargs'''\t\t\t\t):\r\n\t\t\t\t\t\tA_ : Optional[int]\t\t =\t\t\t\t\t\t{}\r\n\r\n\t\t\t\t\tA_ : str\t\t =\t\t\t\t\t\tspm.SentencePieceProcessor(**self.sp_model_kwargs\t\t\t\t)\r\n\t\t\t\t\tself.sp_model.Load(self.vocab_file\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : List[Any]\t\t\t\t\t, _lowerCamelCase : List[str]\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tif self.remove_space:\r\n\t\t\t\t\t\tA_ : Dict\t\t =\t\t\t\t\t\t\" \".join(inputs.strip().split()\t\t\t\t)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tA_ : List[Any]\t\t =\t\t\t\t\t\tinputs\r\n\t\t\t\t\tA_ : str\t\t =\t\t\t\t\t\toutputs.replace('''``'''\t\t\t\t\t, '''\\\"'''\t\t\t\t).replace('''\\'\\''''\t\t\t\t\t, '''\\\"'''\t\t\t\t)\r\n\r\n\t\t\t\t\tif not self.keep_accents:\r\n\t\t\t\t\t\tA_ : List[Any]\t\t =\t\t\t\t\t\tunicodedata.normalize('''NFKD'''\t\t\t\t\t, lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\t\tA_ : Any\t\t =\t\t\t\t\t\t\"\".join([c for c in outputs if not unicodedata.combining(lowerCAmelCase__\t\t\t\t)]\t\t\t\t)\r\n\t\t\t\t\tif self.do_lower_case:\r\n\t\t\t\t\t\tA_ : int\t\t =\t\t\t\t\t\toutputs.lower()\r\n\r\n\t\t\t\t\treturn outputs\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Optional[int]\t\t\t\t\t, _lowerCamelCase : List[Any]\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : Optional[int]\t\t =\t\t\t\t\t\tself.preprocess_text(lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\tA_ : Optional[Any]\t\t =\t\t\t\t\t\tself.sp_model.encode(lowerCAmelCase__\t\t\t\t\t, out_type=lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\tA_ : Optional[int]\t\t =\t\t\t\t\t\t[]\r\n\t\t\t\t\tfor piece in pieces:\r\n\t\t\t\t\t\tif len(lowerCAmelCase__\t\t\t\t) > 1 and piece[-1] == str(''','''\t\t\t\t) and piece[-2].isdigit():\r\n\t\t\t\t\t\t\tA_ : Optional[int]\t\t =\t\t\t\t\t\tself.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCAmelCase__\t\t\t\t\t, ''''''\t\t\t\t)\t\t\t\t)\r\n\t\t\t\t\t\t\tif piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:\r\n\t\t\t\t\t\t\t\tif len(cur_pieces[0]\t\t\t\t) == 1:\r\n\t\t\t\t\t\t\t\t\tA_ : Optional[Any]\t\t =\t\t\t\t\t\tcur_pieces[1:]\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tA_ : List[str]\t\t =\t\t\t\t\t\tcur_pieces[0][1:]\r\n\t\t\t\t\t\t\tcur_pieces.append(piece[-1]\t\t\t\t)\r\n\t\t\t\t\t\t\tnew_pieces.extend(lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tnew_pieces.append(lowerCAmelCase__\t\t\t\t)\r\n\r\n\t\t\t\t\treturn new_pieces\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : str\t\t\t\t\t, _lowerCamelCase : Optional[int]\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn self.sp_model.PieceToId(lowerCAmelCase__\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Dict\t\t\t\t\t, _lowerCamelCase : Any\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn self.sp_model.IdToPiece(lowerCAmelCase__\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Tuple\t\t\t\t\t, _lowerCamelCase : Tuple\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : Dict\t\t =\t\t\t\t\t\t[]\r\n\t\t\t\t\tA_ : Tuple\t\t =\t\t\t\t\t\t\"\"\r\n\t\t\t\t\tA_ : Tuple\t\t =\t\t\t\t\t\tFalse\r\n\t\t\t\t\tfor token in tokens:\r\n\t\t\t\t\t\t# make sure that special tokens are not decoded using sentencepiece model\r\n\t\t\t\t\t\tif token in self.all_special_tokens:\r\n\t\t\t\t\t\t\tif not prev_is_special:\r\n\t\t\t\t\t\t\t\tout_string += \" \"\r\n\t\t\t\t\t\t\tout_string += self.sp_model.decode(lowerCAmelCase__\t\t\t\t) + token\r\n\t\t\t\t\t\t\tA_ : str\t\t =\t\t\t\t\t\tTrue\r\n\t\t\t\t\t\t\tA_ : Tuple\t\t =\t\t\t\t\t\t[]\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tcurrent_sub_tokens.append(lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\t\t\tA_ : List[Any]\t\t =\t\t\t\t\t\tFalse\r\n\t\t\t\t\tout_string += self.sp_model.decode(lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\treturn out_string.strip()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Tuple\t\t\t\t\t, _lowerCamelCase : Union[str, Any]\t\t\t\t\t, _lowerCamelCase : Optional[Any] = None\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : Union[str, Any]\t\t =\t\t\t\t\t\t[self.sep_token_id]\r\n\t\t\t\t\tA_ : List[Any]\t\t =\t\t\t\t\t\t[self.cls_token_id]\r\n\t\t\t\t\tif token_ids_a is None:\r\n\t\t\t\t\t\treturn cls + token_ids_a + sep\r\n\t\t\t\t\treturn cls + token_ids_a + sep + token_ids_a + sep\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Dict\t\t\t\t\t, _lowerCamelCase : Optional[Any]\t\t\t\t\t, _lowerCamelCase : Union[str, Any] = None\t\t\t\t\t, _lowerCamelCase : int = False\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tif already_has_special_tokens:\r\n\t\t\t\t\t\treturn super().get_special_tokens_mask(\r\n\t\t\t\t\t\t token_ids_a=lowerCAmelCase__\t\t\t\t\t, token_ids_a=lowerCAmelCase__\t\t\t\t\t, already_has_special_tokens=lowerCAmelCase__\t\t\t\t)\r\n\r\n\t\t\t\t\tif token_ids_a is not None:\r\n\t\t\t\t\t\treturn [1] + ([0] * len(lowerCAmelCase__\t\t\t\t)) + [1] + ([0] * len(lowerCAmelCase__\t\t\t\t)) + [1]\r\n\t\t\t\t\treturn [1] + ([0] * len(lowerCAmelCase__\t\t\t\t)) + [1]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Optional[Any]\t\t\t\t\t, _lowerCamelCase : int\t\t\t\t\t, _lowerCamelCase : int = None\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tA_ : Tuple\t\t =\t\t\t\t\t\t[self.sep_token_id]\r\n\t\t\t\t\tA_ : Union[str, Any]\t\t =\t\t\t\t\t\t[self.cls_token_id]\r\n\r\n\t\t\t\t\tif token_ids_a is None:\r\n\t\t\t\t\t\treturn len(cls + token_ids_a + sep\t\t\t\t) * [0]\r\n\t\t\t\t\treturn len(cls + token_ids_a + sep\t\t\t\t) * [0] + len(token_ids_a + sep\t\t\t\t) * [1]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\tdef a_ (\t\t\t\t\t\t\tself : Optional[int]\t\t\t\t\t, _lowerCamelCase : List[Any]\t\t\t\t\t, _lowerCamelCase : int = None\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tif not os.path.isdir(lowerCAmelCase__\t\t\t\t):\r\n\t\t\t\t\t\tlogger.error(F\"\"\"Vocabulary path ({save_directory}) should be a directory\"\"\"\t\t\t\t)\r\n\t\t\t\t\t\treturn\r\n\t\t\t\t\tA_ : List[str]\t\t =\t\t\t\t\t\tos.path.join(\r\n\t\t\t\t\t lowerCAmelCase__\t\t\t\t\t, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']\t\t\t\t)\r\n\r\n\t\t\t\t\tif os.path.abspath(self.vocab_file\t\t\t\t) != os.path.abspath(lowerCAmelCase__\t\t\t\t) and os.path.isfile(self.vocab_file\t\t\t\t):\r\n\t\t\t\t\t\tcopyfile(self.vocab_file\t\t\t\t\t, lowerCAmelCase__\t\t\t\t)\r\n\t\t\t\t\telif not os.path.isfile(self.vocab_file\t\t\t\t):\r\n\t\t\t\t\t\twith open(lowerCAmelCase__\t\t\t\t\t, '''wb'''\t\t\t\t) as fi:\r\n\t\t\t\t\t\t\tA_ : List[str]\t\t =\t\t\t\t\t\tself.sp_model.serialized_model_proto()\r\n\t\t\t\t\t\t\tfi.write(lowerCAmelCase__\t\t\t\t)\r\n\r\n\t\t\t\t\treturn (out_vocab_file,)\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":167,"string":"167"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\nimport unittest\r\n\r\nimport numpy as np\r\n\r\nfrom transformers.testing_utils import require_torch, require_vision\r\nfrom transformers.utils import is_torch_available, is_vision_available\r\n\r\nfrom ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs\r\n\r\n\r\nif is_torch_available():\r\n import torch\r\n\r\nif is_vision_available():\r\n from PIL import Image\r\n\r\n from transformers import MobileNetVaImageProcessor\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass \t\t\t\t__lowerCAmelCase ( unittest.TestCase):\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __init__( self\t\t, lowerCAmelCase__\t\t, lowerCAmelCase__=7\t\t, lowerCAmelCase__=3\t\t, lowerCAmelCase__=1_8\t\t, lowerCAmelCase__=3_0\t\t, lowerCAmelCase__=4_0_0\t\t, lowerCAmelCase__=True\t\t, lowerCAmelCase__=None\t\t, lowerCAmelCase__=True\t\t, lowerCAmelCase__=None\t\t, ) ->\t\t\t\t\t\tOptional[int]:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n a__\t:\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t\t=size if size is not None else {\"shortest_edge\": 2_0}\r\n a__\t:\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t=crop_size if crop_size is not None else {\"height\": 1_8, \"width\": 1_8}\r\n a__\t:\t\t\t\t\tTuple\t\t\t\t\t\t\t\t\t\t=parent\r\n a__\t:\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t=batch_size\r\n a__\t:\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t\t=num_channels\r\n a__\t:\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t=image_size\r\n a__\t:\t\t\t\t\tDict\t\t\t\t\t\t\t\t\t\t=min_resolution\r\n a__\t:\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t=max_resolution\r\n a__\t:\t\t\t\t\tDict\t\t\t\t\t\t\t\t\t\t=do_resize\r\n a__\t:\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t=size\r\n a__\t:\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t\t=do_center_crop\r\n a__\t:\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t=crop_size\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tstr:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n return {\r\n \"do_resize\": self.do_resize,\r\n \"size\": self.size,\r\n \"do_center_crop\": self.do_center_crop,\r\n \"crop_size\": self.crop_size,\r\n }\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n@require_torch\r\n@require_vision\r\nclass \t\t\t\t__lowerCAmelCase ( UpperCamelCase__\t\t\t\t\t\t,\t\t\t\tunittest.TestCase):\r\n _lowercase\t\t\t\t:\t\t\t\t\tOptional[Any]\t\t\t\t\t\t=\t\t\tMobileNetVaImageProcessor if is_vision_available() else None\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tTuple:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n a__\t:\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t\t\t=MobileNetVaImageProcessingTester(self\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n @property\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tList[str]:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n return self.image_processor_tester.prepare_image_processor_dict()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tAny:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n a__\t:\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t=self.image_processing_class(**self.image_processor_dict\t\t\t\t\t\t\t)\r\n self.assertTrue(hasattr(lowerCAmelCase__\t\t, \"do_resize\"\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n self.assertTrue(hasattr(lowerCAmelCase__\t\t, \"size\"\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n self.assertTrue(hasattr(lowerCAmelCase__\t\t, \"do_center_crop\"\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n self.assertTrue(hasattr(lowerCAmelCase__\t\t, \"crop_size\"\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tstr:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n a__\t:\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t\t=self.image_processing_class.from_dict(self.image_processor_dict\t\t\t\t\t\t\t)\r\n self.assertEqual(image_processor.size\t\t, {\"shortest_edge\": 2_0}\t\t\t\t\t\t\t)\r\n self.assertEqual(image_processor.crop_size\t\t, {\"height\": 1_8, \"width\": 1_8}\t\t\t\t\t\t\t)\r\n\r\n a__\t:\t\t\t\t\tDict\t\t\t\t\t\t\t\t\t\t=self.image_processing_class.from_dict(self.image_processor_dict\t\t, size=4_2\t\t, crop_size=8_4\t\t\t\t\t\t\t)\r\n self.assertEqual(image_processor.size\t\t, {\"shortest_edge\": 4_2}\t\t\t\t\t\t\t)\r\n self.assertEqual(image_processor.crop_size\t\t, {\"height\": 8_4, \"width\": 8_4}\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tAny:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n pass\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tOptional[int]:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n a__\t:\t\t\t\t\tDict\t\t\t\t\t\t\t\t\t\t=self.image_processing_class(**self.image_processor_dict\t\t\t\t\t\t\t)\r\n # create random PIL images\r\n a__\t:\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t=prepare_image_inputs(self.image_processor_tester\t\t, equal_resolution=lowerCAmelCase__\t\t\t\t\t\t\t)\r\n for image in image_inputs:\r\n self.assertIsInstance(lowerCAmelCase__\t\t, Image.Image\t\t\t\t\t\t\t)\r\n\r\n # Test not batched input\r\n a__\t:\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t\t\t=image_processing(image_inputs[0]\t\t, return_tensors=\"pt\"\t\t\t\t\t\t\t).pixel_values\r\n self.assertEqual(\r\n encoded_images.shape\t\t, (\r\n 1,\r\n self.image_processor_tester.num_channels,\r\n self.image_processor_tester.crop_size[\"height\"],\r\n self.image_processor_tester.crop_size[\"width\"],\r\n )\t\t, )\r\n\r\n # Test batched\r\n a__\t:\t\t\t\t\tDict\t\t\t\t\t\t\t\t\t\t=image_processing(lowerCAmelCase__\t\t, return_tensors=\"pt\"\t\t\t\t\t\t\t).pixel_values\r\n self.assertEqual(\r\n encoded_images.shape\t\t, (\r\n self.image_processor_tester.batch_size,\r\n self.image_processor_tester.num_channels,\r\n self.image_processor_tester.crop_size[\"height\"],\r\n self.image_processor_tester.crop_size[\"width\"],\r\n )\t\t, )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tint:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n a__\t:\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t\t=self.image_processing_class(**self.image_processor_dict\t\t\t\t\t\t\t)\r\n # create random numpy tensors\r\n a__\t:\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t\t=prepare_image_inputs(self.image_processor_tester\t\t, equal_resolution=lowerCAmelCase__\t\t, numpify=lowerCAmelCase__\t\t\t\t\t\t\t)\r\n for image in image_inputs:\r\n self.assertIsInstance(lowerCAmelCase__\t\t, np.ndarray\t\t\t\t\t\t\t)\r\n\r\n # Test not batched input\r\n a__\t:\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t\t\t=image_processing(image_inputs[0]\t\t, return_tensors=\"pt\"\t\t\t\t\t\t\t).pixel_values\r\n self.assertEqual(\r\n encoded_images.shape\t\t, (\r\n 1,\r\n self.image_processor_tester.num_channels,\r\n self.image_processor_tester.crop_size[\"height\"],\r\n self.image_processor_tester.crop_size[\"width\"],\r\n )\t\t, )\r\n\r\n # Test batched\r\n a__\t:\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t=image_processing(lowerCAmelCase__\t\t, return_tensors=\"pt\"\t\t\t\t\t\t\t).pixel_values\r\n self.assertEqual(\r\n encoded_images.shape\t\t, (\r\n self.image_processor_tester.batch_size,\r\n self.image_processor_tester.num_channels,\r\n self.image_processor_tester.crop_size[\"height\"],\r\n self.image_processor_tester.crop_size[\"width\"],\r\n )\t\t, )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n def _lowercase ( self\t\t\t\t\t\t\t) ->\t\t\t\t\t\tOptional[int]:\r\n\r\n\r\n\r\n '''simple docstring'''\r\n\r\n\r\n\r\n\r\n a__\t:\t\t\t\t\tAny\t\t\t\t\t\t\t\t\t\t=self.image_processing_class(**self.image_processor_dict\t\t\t\t\t\t\t)\r\n # create random PyTorch tensors\r\n a__\t:\t\t\t\t\tint\t\t\t\t\t\t\t\t\t\t=prepare_image_inputs(self.image_processor_tester\t\t, equal_resolution=lowerCAmelCase__\t\t, torchify=lowerCAmelCase__\t\t\t\t\t\t\t)\r\n for image in image_inputs:\r\n self.assertIsInstance(lowerCAmelCase__\t\t, torch.Tensor\t\t\t\t\t\t\t)\r\n\r\n # Test not batched input\r\n a__\t:\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t=image_processing(image_inputs[0]\t\t, return_tensors=\"pt\"\t\t\t\t\t\t\t).pixel_values\r\n self.assertEqual(\r\n encoded_images.shape\t\t, (\r\n 1,\r\n self.image_processor_tester.num_channels,\r\n self.image_processor_tester.crop_size[\"height\"],\r\n self.image_processor_tester.crop_size[\"width\"],\r\n )\t\t, )\r\n\r\n # Test batched\r\n a__\t:\t\t\t\t\tstr\t\t\t\t\t\t\t\t\t\t=image_processing(lowerCAmelCase__\t\t, return_tensors=\"pt\"\t\t\t\t\t\t\t).pixel_values\r\n self.assertEqual(\r\n encoded_images.shape\t\t, (\r\n self.image_processor_tester.batch_size,\r\n self.image_processor_tester.num_channels,\r\n self.image_processor_tester.crop_size[\"height\"],\r\n self.image_processor_tester.crop_size[\"width\"],\r\n )\t\t, )\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":95,"string":"95"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":263,"cells":{"code":{"kind":"string","value":"\n\n\n\n\n\nimport itertools\nimport string\nfrom collections.abc import Generator, Iterable\n\n\n\n\n\n\n\ndef __lowerCamelCase (\t\t\t\t\t\t\t__a :List[str] ,\t\t\t\t\t__a :Optional[int] )\t\t-> List[Any]:\n\n\n\n\n\n\n\t\t\"\"\"simple docstring\"\"\"\n\n\t\tA__ \t\t\t\t= iter(A_ )\n\t\twhile True:\n\t\t\t\tA__ \t\t\t\t= tuple(itertools.islice(A_ ,\t\t\t\t\tA_ ) )\n\t\t\t\tif not chunk:\n\t\t\t\t\t\treturn\n\t\t\t\tyield chunk\n\n\n\n\n\n\n\ndef __lowerCamelCase (\t\t\t\t\t\t\t__a :Union[str, Any] )\t\t-> Optional[int]:\n\n\n\n\n\n\n\t\t\"\"\"simple docstring\"\"\"\n\n\t\tA__ \t\t\t\t= ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] )\n\t\tA__ \t\t\t\t= ''''''\n\n\t\tif len(A_ ) < 2:\n\t\t\t\treturn dirty\n\n\t\tfor i in range(len(A_ ) - 1 ):\n\t\t\t\tclean += dirty[i]\n\n\t\t\t\tif dirty[i] == dirty[i + 1]:\n\t\t\t\t\t\tclean += \"X\"\n\n\t\tclean += dirty[-1]\n\n\t\tif len(A_ ) & 1:\n\t\t\t\tclean += \"X\"\n\n\t\treturn clean\n\n\n\n\n\n\n\ndef __lowerCamelCase (\t\t\t\t\t\t\t__a :Optional[Any] )\t\t-> List[Any]:\n\n\n\n\n\n\n\t\t\"\"\"simple docstring\"\"\"\n\n\t\tA__ \t\t\t\t= '''ABCDEFGHIKLMNOPQRSTUVWXYZ'''\n\t\t# we're using a list instead of a '2d' array because it makes the math\n\t\t# for setting up the table and doing the actual encoding/decoding simpler\n\t\tA__ \t\t\t\t= []\n\n\t\t# copy key chars into the table if they are in `alphabet` ignoring duplicates\n\t\tfor char in key.upper():\n\t\t\t\tif char not in table and char in alphabet:\n\t\t\t\t\t\ttable.append(A_ )\n\n # fill the rest of the table in with the remaining alphabet chars\n\t\tfor char in alphabet:\n\t\t\t\tif char not in table:\n\t\t\t\t\t\ttable.append(A_ )\n\n\t\treturn table\n\n\n\n\n\n\n\ndef __lowerCamelCase (\t\t\t\t\t\t\t__a :int ,\t\t\t\t\t__a :Any )\t\t-> str:\n\n\n\n\n\n\n\t\t\"\"\"simple docstring\"\"\"\n\n\t\tA__ \t\t\t\t= generate_table(A_ )\n\t\tA__ \t\t\t\t= prepare_input(A_ )\n\t\tA__ \t\t\t\t= ''''''\n\n\t\t# https://en.wikipedia.org/wiki/Playfair_cipher#Description\n\t\tfor chara, chara in chunker(A_ ,\t\t\t\t\t2 ):\n\t\t\t\tA__ \t\t\t\t= divmod(table.index(A_ ) ,\t\t\t\t\t5 )\n\t\t\t\tA__ \t\t\t\t= divmod(table.index(A_ ) ,\t\t\t\t\t5 )\n\n\t\t\t\tif rowa == rowa:\n\t\t\t\t\t\tciphertext += table[rowa * 5 + (cola + 1) % 5]\n\t\t\t\t\t\tciphertext += table[rowa * 5 + (cola + 1) % 5]\n\t\t\t\telif cola == cola:\n\t\t\t\t\t\tciphertext += table[((rowa + 1) % 5) * 5 + cola]\n\t\t\t\t\t\tciphertext += table[((rowa + 1) % 5) * 5 + cola]\n\t\t\t\telse: # rectangle\n\t\t\t\t\t\tciphertext += table[rowa * 5 + cola]\n\t\t\t\t\t\tciphertext += table[rowa * 5 + cola]\n\n\t\treturn ciphertext\n\n\n\n\n\n\n\ndef __lowerCamelCase (\t\t\t\t\t\t\t__a :Dict ,\t\t\t\t\t__a :int )\t\t-> List[str]:\n\n\n\n\n\n\n\t\t\"\"\"simple docstring\"\"\"\n\n\t\tA__ \t\t\t\t= generate_table(A_ )\n\t\tA__ \t\t\t\t= ''''''\n\n\t\t# https://en.wikipedia.org/wiki/Playfair_cipher#Description\n\t\tfor chara, chara in chunker(A_ ,\t\t\t\t\t2 ):\n\t\t\t\tA__ \t\t\t\t= divmod(table.index(A_ ) ,\t\t\t\t\t5 )\n\t\t\t\tA__ \t\t\t\t= divmod(table.index(A_ ) ,\t\t\t\t\t5 )\n\n\t\t\t\tif rowa == rowa:\n\t\t\t\t\t\tplaintext += table[rowa * 5 + (cola - 1) % 5]\n\t\t\t\t\t\tplaintext += table[rowa * 5 + (cola - 1) % 5]\n\t\t\t\telif cola == cola:\n\t\t\t\t\t\tplaintext += table[((rowa - 1) % 5) * 5 + cola]\n\t\t\t\t\t\tplaintext += table[((rowa - 1) % 5) * 5 + cola]\n\t\t\t\telse: # rectangle\n\t\t\t\t\t\tplaintext += table[rowa * 5 + cola]\n\t\t\t\t\t\tplaintext += table[rowa * 5 + cola]\n\n\t\treturn plaintext\n\n\n\n"},"code_codestyle":{"kind":"number","value":358,"string":"358"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\nfrom __future__ import annotations\r\n\r\nimport unittest\r\n\r\nfrom transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available\r\nfrom transformers.testing_utils import require_tf, require_tokenizers, slow\r\nfrom transformers.utils import cached_property\r\n\r\nfrom ...test_configuration_common import ConfigTester\r\nfrom ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor\r\nfrom ...test_pipeline_mixin import PipelineTesterMixin\r\n\r\n\r\nif is_tf_available():\r\n\t\t\t\t\timport tensorflow as tf\r\n\r\n\t\t\t\t\tfrom transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel\r\n\r\n\r\n@require_tf\r\nclass A :\r\n\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\t\t__lowerCamelCase :\tOptional[Any] = BlenderbotSmallConfig\r\n\t\t\t__lowerCamelCase :\tOptional[Any] = {}\r\n\t\t\t__lowerCamelCase :\tList[Any] = '''gelu'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef __init__( self : Dict\t\t\t\t\t\t\t, __lowerCAmelCase : Tuple\t\t\t\t\t\t\t, __lowerCAmelCase : List[str]=13\t\t\t\t\t\t\t, __lowerCAmelCase : List[Any]=7\t\t\t\t\t\t\t, __lowerCAmelCase : List[str]=True\t\t\t\t\t\t\t, __lowerCAmelCase : List[Any]=False\t\t\t\t\t\t\t, __lowerCAmelCase : Union[str, Any]=99\t\t\t\t\t\t\t, __lowerCAmelCase : Union[str, Any]=32\t\t\t\t\t\t\t, __lowerCAmelCase : Any=2\t\t\t\t\t\t\t, __lowerCAmelCase : Optional[Any]=4\t\t\t\t\t\t\t, __lowerCAmelCase : Tuple=37\t\t\t\t\t\t\t, __lowerCAmelCase : List[Any]=0.1\t\t\t\t\t\t\t, __lowerCAmelCase : Optional[int]=0.1\t\t\t\t\t\t\t, __lowerCAmelCase : List[str]=20\t\t\t\t\t\t\t, __lowerCAmelCase : Union[str, Any]=2\t\t\t\t\t\t\t, __lowerCAmelCase : Dict=1\t\t\t\t\t\t\t, __lowerCAmelCase : int=0\t\t\t\t\t\t\t, ) -> Any:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= parent\r\n\t\t\t\t\tA__ \t\t\t\t= batch_size\r\n\t\t\t\t\tA__ \t\t\t\t= seq_length\r\n\t\t\t\t\tA__ \t\t\t\t= is_training\r\n\t\t\t\t\tA__ \t\t\t\t= use_labels\r\n\t\t\t\t\tA__ \t\t\t\t= vocab_size\r\n\t\t\t\t\tA__ \t\t\t\t= hidden_size\r\n\t\t\t\t\tA__ \t\t\t\t= num_hidden_layers\r\n\t\t\t\t\tA__ \t\t\t\t= num_attention_heads\r\n\t\t\t\t\tA__ \t\t\t\t= intermediate_size\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= hidden_dropout_prob\r\n\t\t\t\t\tA__ \t\t\t\t= attention_probs_dropout_prob\r\n\t\t\t\t\tA__ \t\t\t\t= max_position_embeddings\r\n\t\t\t\t\tA__ \t\t\t\t= eos_token_id\r\n\t\t\t\t\tA__ \t\t\t\t= pad_token_id\r\n\t\t\t\t\tA__ \t\t\t\t= bos_token_id\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef a_\t( self : Optional[Any] ) -> Tuple:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= ids_tensor([self.batch_size, self.seq_length - 1]\t\t\t\t\t\t\t, self.vocab_size )\r\n\t\t\t\t\tA__ \t\t\t\t= tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size )\t\t\t\t\t\t\t, 1 )\r\n\t\t\t\t\tA__ \t\t\t\t= tf.concat([input_ids, eos_tensor]\t\t\t\t\t\t\t, axis=1 )\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= ids_tensor([self.batch_size, self.seq_length]\t\t\t\t\t\t\t, self.vocab_size )\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= self.config_cls(\r\n\t\t\t\t\t vocab_size=self.vocab_size\t\t\t\t\t\t\t, d_model=self.hidden_size\t\t\t\t\t\t\t, encoder_layers=self.num_hidden_layers\t\t\t\t\t\t\t, decoder_layers=self.num_hidden_layers\t\t\t\t\t\t\t, encoder_attention_heads=self.num_attention_heads\t\t\t\t\t\t\t, decoder_attention_heads=self.num_attention_heads\t\t\t\t\t\t\t, encoder_ffn_dim=self.intermediate_size\t\t\t\t\t\t\t, decoder_ffn_dim=self.intermediate_size\t\t\t\t\t\t\t, dropout=self.hidden_dropout_prob\t\t\t\t\t\t\t, attention_dropout=self.attention_probs_dropout_prob\t\t\t\t\t\t\t, max_position_embeddings=self.max_position_embeddings\t\t\t\t\t\t\t, eos_token_ids=[2]\t\t\t\t\t\t\t, bos_token_id=self.bos_token_id\t\t\t\t\t\t\t, pad_token_id=self.pad_token_id\t\t\t\t\t\t\t, decoder_start_token_id=self.pad_token_id\t\t\t\t\t\t\t, **self.config_updates\t\t\t\t\t\t\t, )\r\n\t\t\t\t\tA__ \t\t\t\t= prepare_blenderbot_small_inputs_dict(__lowerCAmelCase\t\t\t\t\t\t\t, __lowerCAmelCase\t\t\t\t\t\t\t, __lowerCAmelCase )\r\n\t\t\t\t\treturn config, inputs_dict\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef a_\t( self : Union[str, Any]\t\t\t\t\t\t\t, __lowerCAmelCase : Any\t\t\t\t\t\t\t, __lowerCAmelCase : Union[str, Any] ) -> str:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= TFBlenderbotSmallModel(config=__lowerCAmelCase ).get_decoder()\r\n\t\t\t\t\tA__ \t\t\t\t= inputs_dict[\"\"\"input_ids\"\"\"]\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= input_ids[:1, :]\r\n\t\t\t\t\tA__ \t\t\t\t= inputs_dict[\"\"\"attention_mask\"\"\"][:1, :]\r\n\t\t\t\t\tA__ \t\t\t\t= inputs_dict[\"\"\"head_mask\"\"\"]\r\n\t\t\t\t\tA__ \t\t\t\t= 1\r\n\r\n\t\t\t\t\t# first forward pass\r\n\t\t\t\t\tA__ \t\t\t\t= model(__lowerCAmelCase\t\t\t\t\t\t\t, attention_mask=__lowerCAmelCase\t\t\t\t\t\t\t, head_mask=__lowerCAmelCase\t\t\t\t\t\t\t, use_cache=__lowerCAmelCase )\r\n\r\n\t\t\t\t\tA__\t\t\t\t, A__ \t\t\t\t= outputs.to_tuple()\r\n\r\n\t\t\t\t\t# create hypothetical next token and extent to next_input_ids\r\n\t\t\t\t\tA__ \t\t\t\t= ids_tensor((self.batch_size, 3)\t\t\t\t\t\t\t, config.vocab_size )\r\n\t\t\t\t\tA__ \t\t\t\t= tf.cast(ids_tensor((self.batch_size, 3)\t\t\t\t\t\t\t, 2 )\t\t\t\t\t\t\t, tf.inta )\r\n\r\n\t\t\t\t\t# append to next input_ids and\r\n\t\t\t\t\tA__ \t\t\t\t= tf.concat([input_ids, next_tokens]\t\t\t\t\t\t\t, axis=-1 )\r\n\t\t\t\t\tA__ \t\t\t\t= tf.concat([attention_mask, next_attn_mask]\t\t\t\t\t\t\t, axis=-1 )\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= model(__lowerCAmelCase\t\t\t\t\t\t\t, attention_mask=__lowerCAmelCase )[0]\r\n\t\t\t\t\tA__ \t\t\t\t= model(__lowerCAmelCase\t\t\t\t\t\t\t, attention_mask=__lowerCAmelCase\t\t\t\t\t\t\t, past_key_values=__lowerCAmelCase )[0]\r\n\r\n\t\t\t\t\tself.parent.assertEqual(next_tokens.shape[1]\t\t\t\t\t\t\t, output_from_past.shape[1] )\r\n\r\n\t\t\t\t\t# select random slice\r\n\t\t\t\t\tA__ \t\t\t\t= int(ids_tensor((1,)\t\t\t\t\t\t\t, output_from_past.shape[-1] ) )\r\n\t\t\t\t\tA__ \t\t\t\t= output_from_no_past[:, -3:, random_slice_idx]\r\n\t\t\t\t\tA__ \t\t\t\t= output_from_past[:, :, random_slice_idx]\r\n\r\n\t\t\t\t\t# test that outputs are equal for slice\r\n\t\t\t\t\ttf.debugging.assert_near(__lowerCAmelCase\t\t\t\t\t\t\t, __lowerCAmelCase\t\t\t\t\t\t\t, rtol=1e-3 )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef __lowerCamelCase (\t\t\t\t\t\t\t__a :Dict ,\t\t\t\t\t__a :Tuple ,\t\t\t\t\t__a :List[Any] ,\t\t\t\t\t__a :List[str]=None ,\t\t\t\t\t__a :List[Any]=None ,\t\t\t\t\t__a :Optional[Any]=None ,\t\t\t\t\t__a :List[str]=None ,\t\t\t\t\t__a :int=None ,\t\t\t\t\t)\t\t-> Optional[Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\tif attention_mask is None:\r\n\t\t\t\tA__ \t\t\t\t= tf.cast(tf.math.not_equal(__a ,\t\t\t\t\tconfig.pad_token_id ) ,\t\t\t\t\ttf.inta )\r\n\t\tif decoder_attention_mask is None:\r\n\t\t\t\tA__ \t\t\t\t= tf.concat(\r\n\t\t\t\t [\r\n\t\t\t\t tf.ones(decoder_input_ids[:, :1].shape ,\t\t\t\t\tdtype=tf.inta ),\r\n\t\t\t\t tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,\t\t\t\t\tconfig.pad_token_id ) ,\t\t\t\t\ttf.inta ),\r\n\t\t\t\t ] ,\t\t\t\t\taxis=-1 ,\t\t\t\t\t)\r\n\t\tif head_mask is None:\r\n\t\t\t\tA__ \t\t\t\t= tf.ones((config.encoder_layers, config.encoder_attention_heads) )\r\n\t\tif decoder_head_mask is None:\r\n\t\t\t\tA__ \t\t\t\t= tf.ones((config.decoder_layers, config.decoder_attention_heads) )\r\n\t\tif cross_attn_head_mask is None:\r\n\t\t\t\tA__ \t\t\t\t= tf.ones((config.decoder_layers, config.decoder_attention_heads) )\r\n\t\treturn {\r\n\t\t \"input_ids\": input_ids,\r\n\t\t \"decoder_input_ids\": decoder_input_ids,\r\n\t\t \"attention_mask\": attention_mask,\r\n\t\t \"decoder_attention_mask\": decoder_attention_mask,\r\n\t\t \"head_mask\": head_mask,\r\n\t\t \"decoder_head_mask\": decoder_head_mask,\r\n\t\t \"cross_attn_head_mask\": cross_attn_head_mask,\r\n\t\t}\r\n\r\n\r\n@require_tf\r\nclass A (SCREAMING_SNAKE_CASE ,\t\t\t\t\tSCREAMING_SNAKE_CASE ,\t\t\t\t\tunittest.TestCase ):\r\n\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\t\t__lowerCamelCase :\tTuple = (\r\n\t\t\t (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()\r\n\t\t\t)\r\n\t\t\t__lowerCamelCase :\tList[Any] = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()\r\n\t\t\t__lowerCamelCase :\tTuple = (\r\n\t\t\t {\r\n\t\t\t '''conversational''': TFBlenderbotSmallForConditionalGeneration,\r\n\t\t\t '''feature-extraction''': TFBlenderbotSmallModel,\r\n\t\t\t '''summarization''': TFBlenderbotSmallForConditionalGeneration,\r\n\t\t\t '''text2text-generation''': TFBlenderbotSmallForConditionalGeneration,\r\n\t\t\t '''translation''': TFBlenderbotSmallForConditionalGeneration,\r\n\t\t\t }\r\n\t\t\t if is_tf_available()\r\n\t\t\t else {}\r\n\t\t\t)\r\n\t\t\t__lowerCamelCase :\tDict = True\r\n\t\t\t__lowerCamelCase :\tOptional[Any] = False\r\n\t\t\t__lowerCamelCase :\tTuple = False\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef a_\t( self : Tuple ) -> Optional[int]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= TFBlenderbotSmallModelTester(self )\r\n\t\t\t\t\tA__ \t\t\t\t= ConfigTester(self\t\t\t\t\t\t\t, config_class=__lowerCAmelCase )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef a_\t( self : List[str] ) -> int:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tself.config_tester.run_common_tests()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\tdef a_\t( self : List[str] ) -> Any:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= self.model_tester.prepare_config_and_inputs_for_common()\r\n\t\t\t\t\tself.model_tester.check_decoder_model_past_large_inputs(*__lowerCAmelCase )\r\n\r\n\r\n@require_tokenizers\r\n@require_tf\r\nclass A (unittest.TestCase ):\r\n\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\t\t__lowerCamelCase :\tList[str] = [\r\n\t\t\t '''Social anxiety\\nWow, I am never shy. Do you have anxiety?\\nYes. I end up sweating and blushing and feel like '''\r\n\t\t\t ''' i\\'m going to throw up.\\nand why is that?'''\r\n\t\t\t]\r\n\t\t\t__lowerCamelCase :\tOptional[int] = '''facebook/blenderbot_small-90M'''\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t@cached_property\r\n\t\t\tdef a_\t( self : Optional[int] ) -> List[str]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\treturn BlenderbotSmallTokenizer.from_pretrained(\"\"\"facebook/blenderbot-90M\"\"\" )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t@cached_property\r\n\t\t\tdef a_\t( self : List[str] ) -> List[str]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )\r\n\t\t\t\t\treturn model\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t@slow\r\n\t\t\tdef a_\t( self : int ) -> Optional[Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tA__ \t\t\t\t= self.tokenizer(self.src_text\t\t\t\t\t\t\t, return_tensors=\"\"\"tf\"\"\" )\r\n\t\t\t\t\tA__ \t\t\t\t= self.model.generate(\r\n\t\t\t\t\t model_inputs.input_ids\t\t\t\t\t\t\t, attention_mask=model_inputs.attention_mask\t\t\t\t\t\t\t, num_beams=2\t\t\t\t\t\t\t, use_cache=__lowerCAmelCase\t\t\t\t\t\t\t, )\r\n\t\t\t\t\tA__ \t\t\t\t= self.tokenizer.batch_decode(generated_ids.numpy()\t\t\t\t\t\t\t, skip_special_tokens=__lowerCAmelCase )[0]\r\n\t\t\t\t\tassert generated_words in (\r\n\t\t\t\t\t \"i don't know. i just feel like i'm going to throw up. it's not fun.\",\r\n\t\t\t\t\t \"i'm not sure. i just feel like i've been feeling like i have to be in a certain place\",\r\n\t\t\t\t\t \"i'm not sure. i just feel like i've been in a bad situation.\",\r\n\t\t\t\t\t)\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":276,"string":"276"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":264,"cells":{"code":{"kind":"string","value":"import inspect\r\nimport os\r\nimport re\r\n\r\nfrom transformers.configuration_utils import PretrainedConfig\r\nfrom transformers.utils import direct_transformers_import\r\n\r\n\r\n# All paths are set with the intent you should run this script from the root of the repo with the command\r\n# python utils/check_config_docstrings.py\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\t\"\"\"src/transformers\"\"\"\r\n\r\n\r\n# This is to make sure the transformers module imported is the one in the repo.\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\tdirect_transformers_import(PATH_TO_TRANSFORMERS)\r\n\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\ttransformers.models.auto.configuration_auto.CONFIG_MAPPING\r\n\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\t{\r\n # used to compute the property `self.chunk_length`\r\n \"\"\"EncodecConfig\"\"\": [\"\"\"overlap\"\"\"],\r\n # used as `self.bert_model = BertModel(config, ...)`\r\n \"\"\"DPRConfig\"\"\": True,\r\n # not used in modeling files, but it's an important information\r\n \"\"\"FSMTConfig\"\"\": [\"\"\"langs\"\"\"],\r\n # used internally in the configuration class file\r\n \"\"\"GPTNeoConfig\"\"\": [\"\"\"attention_types\"\"\"],\r\n # used internally in the configuration class file\r\n \"\"\"EsmConfig\"\"\": [\"\"\"is_folding_model\"\"\"],\r\n # used during training (despite we don't have training script for these models yet)\r\n \"\"\"Mask2FormerConfig\"\"\": [\"\"\"ignore_value\"\"\"],\r\n # `ignore_value` used during training (despite we don't have training script for these models yet)\r\n # `norm` used in conversion script (despite not using in the modeling file)\r\n \"\"\"OneFormerConfig\"\"\": [\"\"\"ignore_value\"\"\", \"\"\"norm\"\"\"],\r\n # used during preprocessing and collation, see `collating_graphormer.py`\r\n \"\"\"GraphormerConfig\"\"\": [\"\"\"spatial_pos_max\"\"\"],\r\n # used internally in the configuration class file\r\n \"\"\"T5Config\"\"\": [\"\"\"feed_forward_proj\"\"\"],\r\n # used internally in the configuration class file\r\n # `tokenizer_class` get default value `T5Tokenizer` intentionally\r\n \"\"\"MT5Config\"\"\": [\"\"\"feed_forward_proj\"\"\", \"\"\"tokenizer_class\"\"\"],\r\n \"\"\"UMT5Config\"\"\": [\"\"\"feed_forward_proj\"\"\", \"\"\"tokenizer_class\"\"\"],\r\n # used internally in the configuration class file\r\n \"\"\"LongT5Config\"\"\": [\"\"\"feed_forward_proj\"\"\"],\r\n # used internally in the configuration class file\r\n \"\"\"SwitchTransformersConfig\"\"\": [\"\"\"feed_forward_proj\"\"\"],\r\n # having default values other than `1e-5` - we can't fix them without breaking\r\n \"\"\"BioGptConfig\"\"\": [\"\"\"layer_norm_eps\"\"\"],\r\n # having default values other than `1e-5` - we can't fix them without breaking\r\n \"\"\"GLPNConfig\"\"\": [\"\"\"layer_norm_eps\"\"\"],\r\n # having default values other than `1e-5` - we can't fix them without breaking\r\n \"\"\"SegformerConfig\"\"\": [\"\"\"layer_norm_eps\"\"\"],\r\n # having default values other than `1e-5` - we can't fix them without breaking\r\n \"\"\"CvtConfig\"\"\": [\"\"\"layer_norm_eps\"\"\"],\r\n # having default values other than `1e-5` - we can't fix them without breaking\r\n \"\"\"PerceiverConfig\"\"\": [\"\"\"layer_norm_eps\"\"\"],\r\n # used internally to calculate the feature size\r\n \"\"\"InformerConfig\"\"\": [\"\"\"num_static_real_features\"\"\", \"\"\"num_time_features\"\"\"],\r\n # used internally to calculate the feature size\r\n \"\"\"TimeSeriesTransformerConfig\"\"\": [\"\"\"num_static_real_features\"\"\", \"\"\"num_time_features\"\"\"],\r\n # used internally to calculate the feature size\r\n \"\"\"AutoformerConfig\"\"\": [\"\"\"num_static_real_features\"\"\", \"\"\"num_time_features\"\"\"],\r\n # used internally to calculate `mlp_dim`\r\n \"\"\"SamVisionConfig\"\"\": [\"\"\"mlp_ratio\"\"\"],\r\n # For (head) training, but so far not implemented\r\n \"\"\"ClapAudioConfig\"\"\": [\"\"\"num_classes\"\"\"],\r\n # Not used, but providing useful information to users\r\n \"\"\"SpeechT5HifiGanConfig\"\"\": [\"\"\"sampling_rate\"\"\"],\r\n}\r\n\r\n\r\n# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure\r\nSPECIAL_CASES_TO_ALLOW.update(\r\n {\r\n \"\"\"CLIPSegConfig\"\"\": True,\r\n \"\"\"DeformableDetrConfig\"\"\": True,\r\n \"\"\"DetaConfig\"\"\": True,\r\n \"\"\"DinatConfig\"\"\": True,\r\n \"\"\"DonutSwinConfig\"\"\": True,\r\n \"\"\"EfficientFormerConfig\"\"\": True,\r\n \"\"\"FSMTConfig\"\"\": True,\r\n \"\"\"JukeboxConfig\"\"\": True,\r\n \"\"\"LayoutLMv2Config\"\"\": True,\r\n \"\"\"MaskFormerSwinConfig\"\"\": True,\r\n \"\"\"MT5Config\"\"\": True,\r\n \"\"\"NatConfig\"\"\": True,\r\n \"\"\"OneFormerConfig\"\"\": True,\r\n \"\"\"PerceiverConfig\"\"\": True,\r\n \"\"\"RagConfig\"\"\": True,\r\n \"\"\"SpeechT5Config\"\"\": True,\r\n \"\"\"SwinConfig\"\"\": True,\r\n \"\"\"Swin2SRConfig\"\"\": True,\r\n \"\"\"Swinv2Config\"\"\": True,\r\n \"\"\"SwitchTransformersConfig\"\"\": True,\r\n \"\"\"TableTransformerConfig\"\"\": True,\r\n \"\"\"TapasConfig\"\"\": True,\r\n \"\"\"TransfoXLConfig\"\"\": True,\r\n \"\"\"UniSpeechConfig\"\"\": True,\r\n \"\"\"UniSpeechSatConfig\"\"\": True,\r\n \"\"\"WavLMConfig\"\"\": True,\r\n \"\"\"WhisperConfig\"\"\": True,\r\n # TODO: @Arthur (for `alignment_head` and `alignment_layer`)\r\n \"\"\"JukeboxPriorConfig\"\"\": True,\r\n # TODO: @Younes (for `is_decoder`)\r\n \"\"\"Pix2StructTextConfig\"\"\": True,\r\n }\r\n)\r\n\r\n\r\n\r\n\r\ndef \t\t\t\tUpperCamelCase\t\t\t\t\t\t( __lowercase\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t: Dict\t):\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\tA_\t\t:\t\t\t\tUnion[str, Any] = False\r\n\t\tfor attribute in attributes:\r\n\t\t\t\tfor modeling_source in source_strings:\r\n\t\t\t\t\t\t# check if we can find `config.xxx`, `getattr(config, \"xxx\", ...)` or `getattr(self.config, \"xxx\", ...)`\r\n\t\t\t\t\t\tif (\r\n\t\t\t\t\t\t f'''config.{attribute}''' in modeling_source\r\n\t\t\t\t\t\t or f'''getattr(config, \"{attribute}\"''' in modeling_source\r\n\t\t\t\t\t\t or f'''getattr(self.config, \"{attribute}\"''' in modeling_source\r\n\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tstr = True\r\n\t\t\t\t\t\t# Deal with multi-line cases\r\n\t\t\t\t\t\telif (\r\n\t\t\t\t\t\t re.search(\r\n\t\t\t\t\t\t rf'''getattr[ \\t\\v\\n\\r\\f]*\\([ \\t\\v\\n\\r\\f]*(self\\.)?config,[ \\t\\v\\n\\r\\f]*\"{attribute}\"'''\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t,)\r\n\t\t\t\t\t\t is not None\r\n\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tint = True\r\n\t\t\t\t\t\t# `SequenceSummary` is called with `SequenceSummary(config)`\r\n\t\t\t\t\t\telif attribute in [\r\n\t\t\t\t\t\t \"summary_type\",\r\n\t\t\t\t\t\t \"summary_use_proj\",\r\n\t\t\t\t\t\t \"summary_activation\",\r\n\t\t\t\t\t\t \"summary_last_dropout\",\r\n\t\t\t\t\t\t \"summary_proj_to_labels\",\r\n\t\t\t\t\t\t \"summary_first_dropout\",\r\n\t\t\t\t\t\t]:\r\n\t\t\t\t\t\t\t\tif \"SequenceSummary\" in modeling_source:\r\n\t\t\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tList[Any] = True\r\n\t\t\t\t\t\tif attribute_used:\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\tif attribute_used:\r\n\t\t\t\t\t\tbreak\r\n\r\n # common and important attributes, even if they do not always appear in the modeling files\r\n\t\tA_\t\t:\t\t\t\tList[Any] = [\r\n\t\t 'bos_index',\r\n\t\t 'eos_index',\r\n\t\t 'pad_index',\r\n\t\t 'unk_index',\r\n\t\t 'mask_index',\r\n\t\t 'image_size',\r\n\t\t 'use_cache',\r\n\t\t 'out_features',\r\n\t\t 'out_indices',\r\n\t\t]\r\n\t\tA_\t\t:\t\t\t\tList[str] = ['encoder_no_repeat_ngram_size']\r\n\r\n\t\t# Special cases to be allowed\r\n\t\tA_\t\t:\t\t\t\tAny = True\r\n\t\tif not attribute_used:\r\n\t\t\t\tA_\t\t:\t\t\t\tList[str] = False\r\n\t\t\t\tfor attribute in attributes:\r\n\t\t\t\t\t\t# Allow if the default value in the configuration class is different from the one in `PretrainedConfig`\r\n\t\t\t\t\t\tif attribute in [\"is_encoder_decoder\"] and default_value is True:\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tint = True\r\n\t\t\t\t\t\telif attribute in [\"tie_word_embeddings\"] and default_value is False:\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tOptional[int] = True\r\n\r\n\t\t\t\t\t\t# Allow cases without checking the default value in the configuration class\r\n\t\t\t\t\t\telif attribute in attributes_to_allow + attributes_used_in_generation:\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tint = True\r\n\t\t\t\t\t\telif attribute.endswith('_token_id'\t):\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tAny = True\r\n\r\n\t\t\t\t\t\t# configuration class specific cases\r\n\t\t\t\t\t\tif not case_allowed:\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tAny = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__\t\t\t\t\t\t,[]\t)\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tTuple = allowed_cases is True or attribute in allowed_cases\r\n\r\n\t\treturn attribute_used or case_allowed\r\n\r\n\r\n\r\n\r\ndef \t\t\t\tUpperCamelCase\t\t\t\t\t\t( __lowercase\t\t\t\t\t\t: List[Any]\t):\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\tA_\t\t:\t\t\t\tTuple = dict(inspect.signature(config_class.__init__\t).parameters\t)\r\n\t\tA_\t\t:\t\t\t\tint = [x for x in list(signature.keys()\t) if x not in ['self', 'kwargs']]\r\n\t\tA_\t\t:\t\t\t\tAny = [signature[param].default for param in parameter_names]\r\n\r\n\t\t# If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long\r\n\t\t# as one variant is used, the test should pass\r\n\t\tA_\t\t:\t\t\t\tTuple = {}\r\n\t\tif len(config_class.attribute_map\t) > 0:\r\n\t\t\t\tA_\t\t:\t\t\t\tDict = {v: k for k, v in config_class.attribute_map.items()}\r\n\r\n\t\t# Get the path to modeling source files\r\n\t\tA_\t\t:\t\t\t\tstr = inspect.getsourcefile(__lowercase\t)\r\n\t\tA_\t\t:\t\t\t\tList[str] = os.path.dirname(__lowercase\t)\r\n\t\t# Let's check against all frameworks: as long as one framework uses an attribute, we are good.\r\n\t\tA_\t\t:\t\t\t\tstr = [os.path.join(__lowercase\t\t\t\t\t\t,__lowercase\t) for fn in os.listdir(__lowercase\t) if fn.startswith('modeling_'\t)]\r\n\r\n\t\t# Get the source code strings\r\n\t\tA_\t\t:\t\t\t\tOptional[Any] = []\r\n\t\tfor path in modeling_paths:\r\n\t\t\t\tif os.path.isfile(__lowercase\t):\r\n\t\t\t\t\t\twith open(__lowercase\t) as fp:\r\n\t\t\t\t\t\t\t\tmodeling_sources.append(fp.read()\t)\r\n\r\n\t\tA_\t\t:\t\t\t\tDict = []\r\n\t\tfor config_param, default_value in zip(__lowercase\t\t\t\t\t\t,__lowercase\t):\r\n\t\t\t\t# `attributes` here is all the variant names for `config_param`\r\n\t\t\t\tA_\t\t:\t\t\t\tTuple = [config_param]\r\n\t\t\t\t# some configuration classes have non-empty `attribute_map`, and both names could be used in the\r\n\t\t\t\t# corresponding modeling files. As long as one of them appears, it is fine.\r\n\t\t\t\tif config_param in reversed_attribute_map:\r\n\t\t\t\t\t\tattributes.append(reversed_attribute_map[config_param]\t)\r\n\r\n\t\t\t\tif not check_attribute_being_used(__lowercase\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t,__lowercase\t):\r\n\t\t\t\t\t\tunused_attributes.append(attributes[0]\t)\r\n\r\n\t\treturn sorted(__lowercase\t)\r\n\r\n\r\n\r\n\r\ndef \t\t\t\tUpperCamelCase\t\t\t\t\t\t( ):\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\tA_\t\t:\t\t\t\tList[str] = {}\r\n\t\tfor _config_class in list(CONFIG_MAPPING.values()\t):\r\n\t\t\t\t# Skip deprecated models\r\n\t\t\t\tif \"models.deprecated\" in _config_class.__module__:\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\t# Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.)\r\n\t\t\t\tA_\t\t:\t\t\t\tstr = [\r\n\t\t\t\t cls\r\n\t\t\t\t for name, cls in inspect.getmembers(\r\n\t\t\t\t inspect.getmodule(_config_class\t)\t\t\t\t\t\t,lambda __lowercase\t: inspect.isclass(__lowercase\t)\r\n\t\t\t\t and issubclass(__lowercase\t\t\t\t\t\t,__lowercase\t)\r\n\t\t\t\t and inspect.getmodule(__lowercase\t) == inspect.getmodule(_config_class\t)\t\t\t\t\t\t,)\r\n\t\t\t\t]\r\n\t\t\t\tfor config_class in config_classes_in_module:\r\n\t\t\t\t\t\tA_\t\t:\t\t\t\tint = check_config_attributes_being_used(__lowercase\t)\r\n\t\t\t\t\t\tif len(__lowercase\t) > 0:\r\n\t\t\t\t\t\t\t\tA_\t\t:\t\t\t\tOptional[int] = unused_attributes\r\n\r\n\t\tif len(__lowercase\t) > 0:\r\n\t\t\t\tA_\t\t:\t\t\t\tUnion[str, Any] = 'The following configuration classes contain unused attributes in the corresponding modeling files:\\n'\r\n\t\t\t\tfor name, attributes in configs_with_unused_attributes.items():\r\n\t\t\t\t\t\terror += f'''{name}: {attributes}\\n'''\r\n\r\n\t\t\t\traise ValueError(__lowercase\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tcheck_config_attributes()\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":140,"string":"140"},"style_context":{"kind":"string","value":"import argparse\r\nfrom typing import Dict\r\n\r\nimport tensorflow as tf\r\nimport torch\r\nfrom tqdm import tqdm\r\n\r\nfrom transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration\r\n\r\n\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\t[\r\n # tf -> hf\r\n (\"\"\"/\"\"\", \"\"\".\"\"\"),\r\n (\"\"\"layer_\"\"\", \"\"\"layers.\"\"\"),\r\n (\"\"\"kernel\"\"\", \"\"\"weight\"\"\"),\r\n (\"\"\"beta\"\"\", \"\"\"bias\"\"\"),\r\n (\"\"\"gamma\"\"\", \"\"\"weight\"\"\"),\r\n (\"\"\"pegasus\"\"\", \"\"\"model\"\"\"),\r\n]\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\t[\r\n (\"\"\".output.dense\"\"\", \"\"\".fc2\"\"\"),\r\n (\"\"\"intermediate.LayerNorm\"\"\", \"\"\"final_layer_norm\"\"\"),\r\n (\"\"\"intermediate.dense\"\"\", \"\"\"fc1\"\"\"),\r\n]\r\n\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\t(\r\n INIT_COMMON\r\n + [\r\n (\"\"\"attention.self.LayerNorm\"\"\", \"\"\"self_attn_layer_norm\"\"\"),\r\n (\"\"\"attention.output.dense\"\"\", \"\"\"self_attn.out_proj\"\"\"),\r\n (\"\"\"attention.self\"\"\", \"\"\"self_attn\"\"\"),\r\n (\"\"\"attention.encdec.LayerNorm\"\"\", \"\"\"encoder_attn_layer_norm\"\"\"),\r\n (\"\"\"attention.encdec_output.dense\"\"\", \"\"\"encoder_attn.out_proj\"\"\"),\r\n (\"\"\"attention.encdec\"\"\", \"\"\"encoder_attn\"\"\"),\r\n (\"\"\"key\"\"\", \"\"\"k_proj\"\"\"),\r\n (\"\"\"value\"\"\", \"\"\"v_proj\"\"\"),\r\n (\"\"\"query\"\"\", \"\"\"q_proj\"\"\"),\r\n (\"\"\"decoder.LayerNorm\"\"\", \"\"\"decoder.layernorm_embedding\"\"\"),\r\n ]\r\n + END_COMMON\r\n)\r\n\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\t(\r\n INIT_COMMON\r\n + [\r\n (\"\"\"embeddings.word_embeddings\"\"\", \"\"\"shared.weight\"\"\"),\r\n (\"\"\"embeddings.position_embeddings\"\"\", \"\"\"embed_positions.weight\"\"\"),\r\n (\"\"\"attention.self.LayerNorm\"\"\", \"\"\"self_attn_layer_norm\"\"\"),\r\n (\"\"\"attention.output.dense\"\"\", \"\"\"self_attn.output\"\"\"),\r\n (\"\"\"attention.self\"\"\", \"\"\"self_attn.self\"\"\"),\r\n (\"\"\"encoder.LayerNorm\"\"\", \"\"\"encoder.layernorm_embedding\"\"\"),\r\n ]\r\n + END_COMMON\r\n)\r\n\r\n_UpperCAmelCase\t\t\t\t\t\t=\t\t[\r\n \"\"\"encdec/key/bias\"\"\",\r\n \"\"\"encdec/query/bias\"\"\",\r\n \"\"\"encdec/value/bias\"\"\",\r\n \"\"\"self/key/bias\"\"\",\r\n \"\"\"self/query/bias\"\"\",\r\n \"\"\"self/value/bias\"\"\",\r\n \"\"\"encdec_output/dense/bias\"\"\",\r\n \"\"\"attention/output/dense/bias\"\"\",\r\n]\r\n\r\n\r\n\r\n\r\ndef \t\t\t\tUpperCamelCase\t\t\t\t\t\t( __lowercase\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t: Tuple\t):\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\tfor tf_name, hf_name in patterns:\r\n\t\t\t\tA_\t\t:\t\t\t\tTuple = k.replace(__lowercase\t\t\t\t\t\t,__lowercase\t)\r\n\t\treturn k\r\n\r\n\r\n\r\n\r\ndef \t\t\t\tUpperCamelCase\t\t\t\t\t\t( __lowercase\t\t\t\t\t\t: dict\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t: dict\t):\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\tA_\t\t:\t\t\t\tint = BigBirdPegasusConfig(**__lowercase\t)\r\n\t\tA_\t\t:\t\t\t\tAny = BigBirdPegasusForConditionalGeneration(__lowercase\t)\r\n\t\tA_\t\t:\t\t\t\tUnion[str, Any] = torch_model.state_dict()\r\n\t\tA_\t\t:\t\t\t\tAny = {}\r\n\r\n\t\t# separating decoder weights\r\n\t\tA_\t\t:\t\t\t\tAny = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder'\t)}\r\n\t\tA_\t\t:\t\t\t\tstr = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder'\t)}\r\n\r\n\t\tfor k, v in tqdm(decoder_weights.items()\t\t\t\t\t\t,'tf -> hf conversion'\t):\r\n\t\t\t\tA_\t\t:\t\t\t\tOptional[int] = [k.endswith(__lowercase\t) for ending in KEYS_TO_IGNORE]\r\n\t\t\t\tif any(__lowercase\t):\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\tA_\t\t:\t\t\t\tOptional[Any] = DECODER_PATTERNS\r\n\t\t\t\tA_\t\t:\t\t\t\tTuple = rename_state_dict_key(__lowercase\t\t\t\t\t\t,__lowercase\t)\r\n\t\t\t\tif new_k not in state_dict:\r\n\t\t\t\t\t\traise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})'''\t)\r\n\t\t\t\tif any(True if i in k else False for i in ['dense', 'query', 'key', 'value']\t):\r\n\t\t\t\t\t\tA_\t\t:\t\t\t\tAny = v.T\r\n\t\t\t\tA_\t\t:\t\t\t\tAny = torch.from_numpy(__lowercase\t)\r\n\t\t\t\tassert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'''\r\n\r\n\t\tfor k, v in tqdm(remaining_weights.items()\t\t\t\t\t\t,'tf -> hf conversion'\t):\r\n\t\t\t\tA_\t\t:\t\t\t\tint = [k.endswith(__lowercase\t) for ending in KEYS_TO_IGNORE]\r\n\t\t\t\tif any(__lowercase\t):\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\tA_\t\t:\t\t\t\tAny = REMAINING_PATTERNS\r\n\t\t\t\tA_\t\t:\t\t\t\tList[str] = rename_state_dict_key(__lowercase\t\t\t\t\t\t,__lowercase\t)\r\n\t\t\t\tif new_k not in state_dict and k != \"pegasus/embeddings/position_embeddings\":\r\n\t\t\t\t\t\traise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})'''\t)\r\n\t\t\t\tif any(True if i in k else False for i in ['dense', 'query', 'key', 'value']\t):\r\n\t\t\t\t\t\tA_\t\t:\t\t\t\tint = v.T\r\n\t\t\t\tA_\t\t:\t\t\t\tDict = torch.from_numpy(__lowercase\t)\r\n\t\t\t\tif k != \"pegasus/embeddings/position_embeddings\":\r\n\t\t\t\t\t\tassert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'''\r\n\r\n\t\tA_\t\t:\t\t\t\tOptional[int] = mapping['model.embed_positions.weight']\r\n\t\tA_\t\t:\t\t\t\tTuple = mapping.pop('model.embed_positions.weight'\t)\r\n\t\tA_ ,\t\t\tA_\t\t:\t\t\t\tOptional[Any] = torch_model.load_state_dict(__lowercase\t\t\t\t\t\t,strict=__lowercase\t)\r\n\t\tA_\t\t:\t\t\t\tOptional[int] = [\r\n\t\t k\r\n\t\t for k in missing\r\n\t\t if k\r\n\t\t not in [\r\n\t\t 'final_logits_bias',\r\n\t\t 'model.encoder.embed_tokens.weight',\r\n\t\t 'model.decoder.embed_tokens.weight',\r\n\t\t 'lm_head.weight',\r\n\t\t ]\r\n\t\t]\r\n\t\tassert unexpected_missing == [], f'''no matches found for the following torch keys {unexpected_missing}'''\r\n\t\tassert extra == [], f'''no matches found for the following tf keys {extra}'''\r\n\t\treturn torch_model\r\n\r\n\r\n\r\n\r\ndef \t\t\t\tUpperCamelCase\t\t\t\t\t\t( __lowercase\t\t\t\t\t\t: Union[str, Any]\t):\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\tA_\t\t:\t\t\t\tstr = tf.train.list_variables(__lowercase\t)\r\n\t\tA_\t\t:\t\t\t\tUnion[str, Any] = {}\r\n\t\tA_\t\t:\t\t\t\tOptional[Any] = ['global_step']\r\n\t\tfor name, shape in tqdm(__lowercase\t\t\t\t\t\t,desc='converting tf checkpoint to dict'\t):\r\n\t\t\t\tA_\t\t:\t\t\t\tUnion[str, Any] = any(pat in name for pat in ignore_name\t)\r\n\t\t\t\tif skip_key:\r\n\t\t\t\t\t\tcontinue\r\n\t\t\t\tA_\t\t:\t\t\t\tTuple = tf.train.load_variable(__lowercase\t\t\t\t\t\t,__lowercase\t)\r\n\t\t\t\tA_\t\t:\t\t\t\tDict = array\r\n\t\treturn tf_weights\r\n\r\n\r\n\r\n\r\ndef \t\t\t\tUpperCamelCase\t\t\t\t\t\t( __lowercase\t\t\t\t\t\t: str\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t: str\t\t\t\t\t\t,__lowercase\t\t\t\t\t\t: dict\t):\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t\tA_\t\t:\t\t\t\tOptional[Any] = get_tf_weights_as_numpy(__lowercase\t)\r\n\t\tA_\t\t:\t\t\t\tDict = convert_bigbird_pegasus(__lowercase\t\t\t\t\t\t,__lowercase\t)\r\n\t\ttorch_model.save_pretrained(__lowercase\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t_UpperCAmelCase\t\t\t\t\t\t=\t\targparse.ArgumentParser()\r\n\tparser.add_argument(\"\"\"--tf_ckpt_path\"\"\", type=str, help=\"\"\"passed to tf.train.list_variables\"\"\")\r\n\tparser.add_argument(\"\"\"--save_dir\"\"\", default=None, type=str, help=\"\"\"Path to the output PyTorch model.\"\"\")\r\n\t_UpperCAmelCase\t\t\t\t\t\t=\t\tparser.parse_args()\r\n\t_UpperCAmelCase\t\t\t\t\t\t=\t\t{}\r\n\tconvert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":140,"string":"140"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":265,"cells":{"code":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\nimport copy\nimport os\nfrom typing import Union\n\nfrom ...configuration_utils import PretrainedConfig\nfrom ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES\nfrom ...utils import logging\nfrom ..auto import CONFIG_MAPPING\n\n\n__lowerCAmelCase\t\t\t\t\t\t = logging.get_logger(__name__)\n\n__lowerCAmelCase\t\t\t\t\t\t = {\n \"salesforce/blip2-opt-2.7b\": \"https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json\",\n}\n\nclass __magic_name__\t\t\t\t\t\t( SCREAMING_SNAKE_CASE__ ):\n lowerCAmelCase\t: Dict = 'blip_2_vision_model'\n\n\n\n\n\n\n\n def __init__(\t\t\t\t\t\t\tself :\tDict ,_UpperCAmelCase :\tint=1408 ,_UpperCAmelCase :\tAny=6144 ,_UpperCAmelCase :\tUnion[str, Any]=39 ,_UpperCAmelCase :\tUnion[str, Any]=16 ,_UpperCAmelCase :\tList[str]=224 ,_UpperCAmelCase :\tOptional[int]=14 ,_UpperCAmelCase :\tTuple=\"gelu\" ,_UpperCAmelCase :\tTuple=0.0_00_01 ,_UpperCAmelCase :\tDict=0.0 ,_UpperCAmelCase :\tUnion[str, Any]=1E-10 ,_UpperCAmelCase :\tint=True ,**_UpperCAmelCase :\tTuple ,):\n super().__init__(**a_\t\t)\n\n _a\t\t\t\t\t:\t\t\t\tUnion[str, Any]\t\t\t\t=\t\t\t\t\t\t\thidden_size\n _a\t\t\t\t\t:\t\t\t\tList[str]\t\t\t\t=\t\t\t\t\t\t\tintermediate_size\n _a\t\t\t\t\t:\t\t\t\tDict\t\t\t\t=\t\t\t\t\t\t\tnum_hidden_layers\n _a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\tnum_attention_heads\n _a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\tpatch_size\n _a\t\t\t\t\t:\t\t\t\tUnion[str, Any]\t\t\t\t=\t\t\t\t\t\t\timage_size\n _a\t\t\t\t\t:\t\t\t\tUnion[str, Any]\t\t\t\t=\t\t\t\t\t\t\tinitializer_range\n _a\t\t\t\t\t:\t\t\t\tUnion[str, Any]\t\t\t\t=\t\t\t\t\t\t\tattention_dropout\n _a\t\t\t\t\t:\t\t\t\tOptional[int]\t\t\t\t=\t\t\t\t\t\t\tlayer_norm_eps\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\thidden_act\n _a\t\t\t\t\t:\t\t\t\tList[str]\t\t\t\t=\t\t\t\t\t\t\tqkv_bias\n\n\n\n\n\n\n\n @classmethod\n def \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tcls :\tAny ,_UpperCAmelCase :\tUnion[str, os.PathLike] ,**_UpperCAmelCase :\tAny\t\t):\n cls._set_token_in_kwargs(a_\t\t)\n\n _a\t, _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\tcls.get_config_dict(a_ ,**a_\t\t)\n\n # get the vision config dict if we are loading from Blip2Config\n if config_dict.get('model_type'\t\t) == \"blip-2\":\n _a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\tconfig_dict['vision_config']\n\n if \"model_type\" in config_dict and hasattr(cls ,'model_type'\t\t) and config_dict[\"model_type\"] != cls.model_type:\n logger.warning(\n F\"\"\"You are using a model of type {config_dict['model_type']} to instantiate a model of type \"\"\"\n F\"\"\"{cls.model_type}. This is not supported for all configurations of models and can yield errors.\"\"\"\t\t)\n\n return cls.from_dict(a_ ,**a_\t\t)\n\nclass __magic_name__\t\t\t\t\t\t( SCREAMING_SNAKE_CASE__ ):\n lowerCAmelCase\t: Optional[int] = 'blip_2_qformer'\n\n\n\n\n\n\n\n def __init__(\t\t\t\t\t\t\tself :\tTuple ,_UpperCAmelCase :\tTuple=30522 ,_UpperCAmelCase :\tAny=768 ,_UpperCAmelCase :\tUnion[str, Any]=12 ,_UpperCAmelCase :\tOptional[int]=12 ,_UpperCAmelCase :\tUnion[str, Any]=3072 ,_UpperCAmelCase :\tList[Any]=\"gelu\" ,_UpperCAmelCase :\tDict=0.1 ,_UpperCAmelCase :\tDict=0.1 ,_UpperCAmelCase :\tList[Any]=512 ,_UpperCAmelCase :\tAny=0.02 ,_UpperCAmelCase :\tOptional[Any]=1E-12 ,_UpperCAmelCase :\tstr=0 ,_UpperCAmelCase :\tList[str]=\"absolute\" ,_UpperCAmelCase :\tList[str]=2 ,_UpperCAmelCase :\tList[Any]=1408 ,**_UpperCAmelCase :\tTuple ,):\n super().__init__(pad_token_id=a_ ,**a_\t\t)\n\n _a\t\t\t\t\t:\t\t\t\tint\t\t\t\t=\t\t\t\t\t\t\tvocab_size\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\thidden_size\n _a\t\t\t\t\t:\t\t\t\tstr\t\t\t\t=\t\t\t\t\t\t\tnum_hidden_layers\n _a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\tnum_attention_heads\n _a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\thidden_act\n _a\t\t\t\t\t:\t\t\t\tint\t\t\t\t=\t\t\t\t\t\t\tintermediate_size\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\thidden_dropout_prob\n _a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\tattention_probs_dropout_prob\n _a\t\t\t\t\t:\t\t\t\tOptional[int]\t\t\t\t=\t\t\t\t\t\t\tmax_position_embeddings\n _a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\tinitializer_range\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\tlayer_norm_eps\n _a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\tposition_embedding_type\n _a\t\t\t\t\t:\t\t\t\tOptional[int]\t\t\t\t=\t\t\t\t\t\t\tcross_attention_frequency\n _a\t\t\t\t\t:\t\t\t\tTuple\t\t\t\t=\t\t\t\t\t\t\tencoder_hidden_size\n\n\n\n\n\n\n\n @classmethod\n def \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tcls :\tOptional[int] ,_UpperCAmelCase :\tUnion[str, os.PathLike] ,**_UpperCAmelCase :\tList[str]\t\t):\n cls._set_token_in_kwargs(a_\t\t)\n\n _a\t, _a\t\t\t\t\t:\t\t\t\tDict\t\t\t\t=\t\t\t\t\t\t\tcls.get_config_dict(a_ ,**a_\t\t)\n\n # get the qformer config dict if we are loading from Blip2Config\n if config_dict.get('model_type'\t\t) == \"blip-2\":\n _a\t\t\t\t\t:\t\t\t\tint\t\t\t\t=\t\t\t\t\t\t\tconfig_dict['qformer_config']\n\n if \"model_type\" in config_dict and hasattr(cls ,'model_type'\t\t) and config_dict[\"model_type\"] != cls.model_type:\n logger.warning(\n F\"\"\"You are using a model of type {config_dict['model_type']} to instantiate a model of type \"\"\"\n F\"\"\"{cls.model_type}. This is not supported for all configurations of models and can yield errors.\"\"\"\t\t)\n\n return cls.from_dict(a_ ,**a_\t\t)\n\nclass __magic_name__\t\t\t\t\t\t( SCREAMING_SNAKE_CASE__ ):\n lowerCAmelCase\t: Optional[int] = 'blip-2'\n lowerCAmelCase\t: Dict = True\n\n\n\n\n\n\n\n def __init__(\t\t\t\t\t\t\tself :\tDict ,_UpperCAmelCase :\tList[Any]=None ,_UpperCAmelCase :\tOptional[Any]=None ,_UpperCAmelCase :\tDict=None ,_UpperCAmelCase :\tTuple=32 ,**_UpperCAmelCase :\tOptional[int]\t\t):\n super().__init__(**a_\t\t)\n\n if vision_config is None:\n _a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\t{}\n logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.'\t\t)\n\n if qformer_config is None:\n _a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\t{}\n logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.'\t\t)\n\n if text_config is None:\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\t{}\n logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).'\t\t)\n\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\tBlipaVisionConfig(**a_\t\t)\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\tBlipaQFormerConfig(**a_\t\t)\n _a\t\t\t\t\t:\t\t\t\tOptional[Any]\t\t\t\t=\t\t\t\t\t\t\ttext_config['model_type'] if 'model_type' in text_config else 'opt'\n _a\t\t\t\t\t:\t\t\t\tDict\t\t\t\t=\t\t\t\t\t\t\tCONFIG_MAPPING[text_model_type](**a_\t\t)\n\n _a\t\t\t\t\t:\t\t\t\tDict\t\t\t\t=\t\t\t\t\t\t\tself.text_config.tie_word_embeddings\n _a\t\t\t\t\t:\t\t\t\tUnion[str, Any]\t\t\t\t=\t\t\t\t\t\t\tself.text_config.is_encoder_decoder\n\n _a\t\t\t\t\t:\t\t\t\tstr\t\t\t\t=\t\t\t\t\t\t\tnum_query_tokens\n _a\t\t\t\t\t:\t\t\t\tint\t\t\t\t=\t\t\t\t\t\t\tself.vision_config.hidden_size\n _a\t\t\t\t\t:\t\t\t\tOptional[int]\t\t\t\t=\t\t\t\t\t\t\tself.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES\n _a\t\t\t\t\t:\t\t\t\tint\t\t\t\t=\t\t\t\t\t\t\t1.0\n _a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\t0.02\n\n\n\n\n\n\n\n @classmethod\n def \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tcls :\tint ,_UpperCAmelCase :\tBlipaVisionConfig ,_UpperCAmelCase :\tBlipaQFormerConfig ,_UpperCAmelCase :\tPretrainedConfig ,**_UpperCAmelCase :\tint ,):\n return cls(\n vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**a_ ,)\n\n\n\n\n\n\n\n def \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tself :\tTuple\t\t):\n _a\t\t\t\t\t:\t\t\t\tTuple\t\t\t\t=\t\t\t\t\t\t\tcopy.deepcopy(self.__dict__\t\t)\n _a\t\t\t\t\t:\t\t\t\tstr\t\t\t\t=\t\t\t\t\t\t\tself.vision_config.to_dict()\n _a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\tself.qformer_config.to_dict()\n _a\t\t\t\t\t:\t\t\t\tOptional[int]\t\t\t\t=\t\t\t\t\t\t\tself.text_config.to_dict()\n _a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\tself.__class__.model_type\n return output\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":359,"string":"359"},"style_context":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\nfrom binascii import hexlify\nfrom hashlib import shaaaa\nfrom os import urandom\n\n# RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for\n# Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526\n\n__lowerCAmelCase\t\t\t\t\t\t = {\n # 1536-bit\n 5: {\n '''prime''': int(\n '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1'''\n + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD'''\n + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245'''\n + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED'''\n + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D'''\n + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F'''\n + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D'''\n + '''670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF''',\n base=16,\n ),\n '''generator''': 2,\n },\n # 2048-bit\n 14: {\n '''prime''': int(\n '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1'''\n + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD'''\n + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245'''\n + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED'''\n + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D'''\n + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F'''\n + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D'''\n + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B'''\n + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9'''\n + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510'''\n + '''15728E5A8AACAA68FFFFFFFFFFFFFFFF''',\n base=16,\n ),\n '''generator''': 2,\n },\n # 3072-bit\n 15: {\n '''prime''': int(\n '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1'''\n + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD'''\n + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245'''\n + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED'''\n + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D'''\n + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F'''\n + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D'''\n + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B'''\n + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9'''\n + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510'''\n + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64'''\n + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7'''\n + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B'''\n + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C'''\n + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31'''\n + '''43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF''',\n base=16,\n ),\n '''generator''': 2,\n },\n # 4096-bit\n 16: {\n '''prime''': int(\n '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1'''\n + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD'''\n + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245'''\n + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED'''\n + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D'''\n + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F'''\n + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D'''\n + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B'''\n + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9'''\n + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510'''\n + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64'''\n + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7'''\n + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B'''\n + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C'''\n + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31'''\n + '''43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7'''\n + '''88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA'''\n + '''2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6'''\n + '''287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED'''\n + '''1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9'''\n + '''93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199'''\n + '''FFFFFFFFFFFFFFFF''',\n base=16,\n ),\n '''generator''': 2,\n },\n # 6144-bit\n 17: {\n '''prime''': int(\n '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08'''\n + '''8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B'''\n + '''302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9'''\n + '''A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6'''\n + '''49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8'''\n + '''FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D'''\n + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C'''\n + '''180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718'''\n + '''3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D'''\n + '''04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D'''\n + '''B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226'''\n + '''1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C'''\n + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC'''\n + '''E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26'''\n + '''99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB'''\n + '''04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2'''\n + '''233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127'''\n + '''D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492'''\n + '''36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406'''\n + '''AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918'''\n + '''DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151'''\n + '''2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03'''\n + '''F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F'''\n + '''BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA'''\n + '''CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B'''\n + '''B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632'''\n + '''387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E'''\n + '''6DCC4024FFFFFFFFFFFFFFFF''',\n base=16,\n ),\n '''generator''': 2,\n },\n # 8192-bit\n 18: {\n '''prime''': int(\n '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1'''\n + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD'''\n + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245'''\n + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED'''\n + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D'''\n + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F'''\n + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D'''\n + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B'''\n + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9'''\n + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510'''\n + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64'''\n + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7'''\n + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B'''\n + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C'''\n + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31'''\n + '''43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7'''\n + '''88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA'''\n + '''2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6'''\n + '''287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED'''\n + '''1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9'''\n + '''93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492'''\n + '''36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD'''\n + '''F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831'''\n + '''179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B'''\n + '''DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF'''\n + '''5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6'''\n + '''D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3'''\n + '''23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA'''\n + '''CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328'''\n + '''06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C'''\n + '''DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE'''\n + '''12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4'''\n + '''38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300'''\n + '''741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568'''\n + '''3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9'''\n + '''22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B'''\n + '''4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A'''\n + '''062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36'''\n + '''4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1'''\n + '''B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92'''\n + '''4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47'''\n + '''9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71'''\n + '''60C980DD98EDD3DFFFFFFFFFFFFFFFFF''',\n base=16,\n ),\n '''generator''': 2,\n },\n}\n\nclass __magic_name__\t\t\t\t\t\t:\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tdef __init__(\t\t\t\t\t\t\tself :\tUnion[str, Any] ,_UpperCAmelCase :\tint = 14\t\t):\n\t\t\t\t\t\t\t\t\tif group not in primes:\n\t\t\t\t\t\t\t\t\t\t\traise ValueError('Unsupported Group'\t\t)\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tstr\t\t\t\t=\t\t\t\t\t\t\tprimes[group]['prime']\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tOptional[int]\t\t\t\t=\t\t\t\t\t\t\tprimes[group]['generator']\n\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tTuple\t\t\t\t=\t\t\t\t\t\t\tint(hexlify(urandom(32\t\t)\t\t) ,base=16\t\t)\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tself :\tDict\t\t):\n\t\t\t\t\t\t\t\t\treturn hex(self.__private_key\t\t)[2:]\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tself :\tList[str]\t\t):\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tint\t\t\t\t=\t\t\t\t\t\t\tpow(self.generator ,self.__private_key ,self.prime\t\t)\n\t\t\t\t\t\t\t\t\treturn hex(_UpperCAmelCase\t\t)[2:]\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tself :\tint ,_UpperCAmelCase :\tint\t\t):\n\t\t\t\t\t\t\t\t\t# check if the other public key is valid based on NIST SP800-56\n\t\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t 2 <= key <= self.prime - 2\n\t\t\t\t\t\t\t\t\t and pow(_UpperCAmelCase ,(self.prime - 1) // 2 ,self.prime\t\t) == 1\n\t\t\t\t\t\t\t\t\t)\n\n\n\n\n\n\n\n\t\t\t\t\t\t\tdef \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\tself :\tTuple ,_UpperCAmelCase :\tstr\t\t):\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tList[Any]\t\t\t\t=\t\t\t\t\t\t\tint(_UpperCAmelCase ,base=16\t\t)\n\t\t\t\t\t\t\t\t\tif not self.is_valid_public_key(_UpperCAmelCase\t\t):\n\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid public key'\t\t)\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\tpow(_UpperCAmelCase ,self.__private_key ,self.prime\t\t)\n\t\t\t\t\t\t\t\t\treturn shaaaa(str(_UpperCAmelCase\t\t).encode()\t\t).hexdigest()\n\n\n\n\n\n\n\n\t\t\t\t\t\t\t@staticmethod\n\t\t\t\t\t\t\tdef \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\t_UpperCAmelCase :\tint ,_UpperCAmelCase :\tint\t\t):\n\t\t\t\t\t\t\t\t\t# check if the other public key is valid based on NIST SP800-56\n\t\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t 2 <= remote_public_key_str <= prime - 2\n\t\t\t\t\t\t\t\t\t and pow(_UpperCAmelCase ,(prime - 1) // 2 ,_UpperCAmelCase\t\t) == 1\n\t\t\t\t\t\t\t\t\t)\n\n\n\n\n\n\n\n\t\t\t\t\t\t\t@staticmethod\n\t\t\t\t\t\t\tdef \t\t\t\t\t\t\t__lowercase (\t\t\t\t\t\t\t_UpperCAmelCase :\tstr ,_UpperCAmelCase :\tstr ,_UpperCAmelCase :\tint = 14\t\t):\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tstr\t\t\t\t=\t\t\t\t\t\t\tint(_UpperCAmelCase ,base=16\t\t)\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tint\t\t\t\t=\t\t\t\t\t\t\tint(_UpperCAmelCase ,base=16\t\t)\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tAny\t\t\t\t=\t\t\t\t\t\t\tprimes[group]['prime']\n\t\t\t\t\t\t\t\t\tif not DiffieHellman.is_valid_public_key_static(_UpperCAmelCase ,_UpperCAmelCase\t\t):\n\t\t\t\t\t\t\t\t\t\t\traise ValueError('Invalid public key'\t\t)\n\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t:\t\t\t\tList[str]\t\t\t\t=\t\t\t\t\t\t\tpow(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase\t\t)\n\t\t\t\t\t\t\t\t\treturn shaaaa(str(_UpperCAmelCase\t\t).encode()\t\t).hexdigest()\n\n\nif __name__ == \"__main__\":\n\t\t\t\t\t\t\timport doctest\n\n\t\t\t\t\t\t\tdoctest.testmod()\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":107,"string":"107"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":266,"cells":{"code":{"kind":"string","value":"\r\r\r\r\r\r'''simple docstring'''\r\r\r\r\r\r\r\rimport warnings\rfrom typing import List, Optional, Union\r\rfrom ...processing_utils import ProcessorMixin\rfrom ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy\rfrom ...utils import TensorType\rclass \t\t\t\t__SCREAMING_SNAKE_CASE (lowerCamelCase_ ):\r\r\r\r\r\r\r\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\r\t\t\t\t__a =['image_processor', 'tokenizer']\r\t\t\t\t__a ='LayoutLMv3ImageProcessor'\r\t\t\t\t__a =('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast')\r\r\r\r\r\t\t\t\tdef __init__( self :\t\t\t\t\tTuple\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tint=None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tUnion[str, Any]=None\t\t\t\t\t,\t\t\t\t**__a :\t\t\t\t\tOptional[Any]\t\t\t\t\t):\r\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= None\r\t\t\t\t\t\t\t\tif \"feature_extractor\" in kwargs:\r\t\t\t\t\t\t\t\t\t\t\t\twarnings.warn(\r\t\t\t\t\t\t\t\t\t\t\t\t \"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`\"\r\t\t\t\t\t\t\t\t\t\t\t\t \" instead.\"\t\t\t\t\t,\t\t\t\t__a\t\t\t\t\t,\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= kwargs.pop(\"feature_extractor\"\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= image_processor if image_processor is not None else feature_extractor\r\t\t\t\t\t\t\t\tif image_processor is None:\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"You need to specify an `image_processor`.\"\t\t\t\t\t)\r\t\t\t\t\t\t\t\tif tokenizer is None:\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"You need to specify a `tokenizer`.\"\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tsuper().__init__(__a\t\t\t\t\t,\t\t\t\t__a\t\t\t\t\t)\r\r\r\r\r\t\t\t\tdef __call__( self :\t\t\t\t\tAny\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tList[str]\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tUnion[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tOptional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tUnion[List[List[int]], List[List[List[int]]]] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tOptional[Union[List[int], List[List[int]]]] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tbool = True\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tUnion[bool, str, PaddingStrategy] = False\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tUnion[bool, str, TruncationStrategy] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tOptional[int] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tint = 0\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tOptional[int] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tOptional[bool] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tOptional[bool] = None\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tbool = False\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tbool = False\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tbool = False\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tbool = False\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tbool = True\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tOptional[Union[str, TensorType]] = None\t\t\t\t\t,\t\t\t\t**__a :\t\t\t\t\tDict\t\t\t\t\t,\t\t\t\t):\r\t\t\t\t\t\t\t\t# verify input\r\t\t\t\t\t\t\t\tif self.image_processor.apply_ocr and (boxes is not None):\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\t\t\t\t\t\t\t\t\t\t\t\t \"You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.\"\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tif self.image_processor.apply_ocr and (word_labels is not None):\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\t\t\t\t\t\t\t\t\t\t\t\t \"You cannot provide word labels if you initialized the image processor with apply_ocr set to True.\"\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# first, apply the image processor\r\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= self.image_processor(images=__a\t\t\t\t\t,\t\t\t\treturn_tensors=__a\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# second, apply the tokenizer\r\t\t\t\t\t\t\t\tif text is not None and self.image_processor.apply_ocr and text_pair is None:\r\t\t\t\t\t\t\t\t\t\t\t\tif isinstance(__a\t\t\t\t\t,\t\t\t\t__a\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= [text] # add batch dimension (as the image processor always adds a batch dimension)\r\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= features[\"words\"]\r\r\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= self.tokenizer(\r\t\t\t\t\t\t\t\t text=text if text is not None else features[\"words\"]\t\t\t\t\t,\t\t\t\ttext_pair=text_pair if text_pair is not None else None\t\t\t\t\t,\t\t\t\tboxes=boxes if boxes is not None else features[\"boxes\"]\t\t\t\t\t,\t\t\t\tword_labels=__a\t\t\t\t\t,\t\t\t\tadd_special_tokens=__a\t\t\t\t\t,\t\t\t\tpadding=__a\t\t\t\t\t,\t\t\t\ttruncation=__a\t\t\t\t\t,\t\t\t\tmax_length=__a\t\t\t\t\t,\t\t\t\tstride=__a\t\t\t\t\t,\t\t\t\tpad_to_multiple_of=__a\t\t\t\t\t,\t\t\t\treturn_token_type_ids=__a\t\t\t\t\t,\t\t\t\treturn_attention_mask=__a\t\t\t\t\t,\t\t\t\treturn_overflowing_tokens=__a\t\t\t\t\t,\t\t\t\treturn_special_tokens_mask=__a\t\t\t\t\t,\t\t\t\treturn_offsets_mapping=__a\t\t\t\t\t,\t\t\t\treturn_length=__a\t\t\t\t\t,\t\t\t\tverbose=__a\t\t\t\t\t,\t\t\t\treturn_tensors=__a\t\t\t\t\t,\t\t\t\t**__a\t\t\t\t\t,\t\t\t\t)\r\r\t\t\t\t\t\t\t\t# add pixel values\r\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= features.pop(\"pixel_values\"\t\t\t\t\t)\r\t\t\t\t\t\t\t\tif return_overflowing_tokens is True:\r\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= self.get_overflowing_images(__a\t\t\t\t\t,\t\t\t\tencoded_inputs[\"overflow_to_sample_mapping\"]\t\t\t\t\t)\r\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= images\r\r\t\t\t\t\t\t\t\treturn encoded_inputs\r\r\r\r\r\t\t\t\tdef UpperCamelCase__ ( self :\t\t\t\t\tOptional[int]\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tstr\t\t\t\t\t,\t\t\t\t__a :\t\t\t\t\tList[Any]\t\t\t\t\t):\r\t\t\t\t\t\t\t\t# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image\r\t\t\t\t\t\t\t\t_a\t\t\t\t\t\t\t\t= []\r\t\t\t\t\t\t\t\tfor sample_idx in overflow_to_sample_mapping:\r\t\t\t\t\t\t\t\t\t\t\t\timages_with_overflow.append(images[sample_idx]\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\tif len(__a\t\t\t\t\t) != len(__a\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\t\t\t\t\t\t\t\t\t\t\t\t \"Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got\"\r\t\t\t\t\t\t\t\t\t\t\t\t f' {len(__a\t\t\t\t\t)} and {len(__a\t\t\t\t\t)}'\t\t\t\t\t)\r\r\t\t\t\t\t\t\t\treturn images_with_overflow\r\r\r\r\r\t\t\t\tdef UpperCamelCase__ ( self :\t\t\t\t\tint\t\t\t\t\t,\t\t\t\t*__a :\t\t\t\t\tstr\t\t\t\t\t,\t\t\t\t**__a :\t\t\t\t\tTuple\t\t\t\t\t):\r\t\t\t\t\t\t\t\treturn self.tokenizer.batch_decode(*__a\t\t\t\t\t,\t\t\t\t**__a\t\t\t\t\t)\r\r\r\r\r\t\t\t\tdef UpperCamelCase__ ( self :\t\t\t\t\tstr\t\t\t\t\t,\t\t\t\t*__a :\t\t\t\t\tList[Any]\t\t\t\t\t,\t\t\t\t**__a :\t\t\t\t\tList[str]\t\t\t\t\t):\r\t\t\t\t\t\t\t\treturn self.tokenizer.decode(*__a\t\t\t\t\t,\t\t\t\t**__a\t\t\t\t\t)\r\r\r\r\r\t\t\t\t@property\r\t\t\t\tdef UpperCamelCase__ ( self :\t\t\t\t\tTuple\t\t\t\t\t):\r\t\t\t\t\t\t\t\treturn [\"input_ids\", \"bbox\", \"attention_mask\", \"pixel_values\"]\r\r\r\r\r\t\t\t\t@property\r\t\t\t\tdef UpperCamelCase__ ( self :\t\t\t\t\tint\t\t\t\t\t):\r\t\t\t\t\t\t\t\twarnings.warn(\r\t\t\t\t\t\t\t\t \"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.\"\t\t\t\t\t,\t\t\t\t__a\t\t\t\t\t,\t\t\t\t)\r\t\t\t\t\t\t\t\treturn self.image_processor_class\r\r\r\r\r\t\t\t\t@property\r\t\t\t\tdef UpperCamelCase__ ( self :\t\t\t\t\tList[str]\t\t\t\t\t):\r\t\t\t\t\t\t\t\twarnings.warn(\r\t\t\t\t\t\t\t\t \"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.\"\t\t\t\t\t,\t\t\t\t__a\t\t\t\t\t,\t\t\t\t)\r\t\t\t\t\t\t\t\treturn self.image_processor\r"},"code_codestyle":{"kind":"number","value":63,"string":"63"},"style_context":{"kind":"string","value":"\rimport numpy as np\r\r\r\r\r\r\rdef a_\t\t( __lowercase :\tnp.array ) -> np.array:\r\t\t\treturn 1 / (1 + np.exp(-vector ))\r\r\rif __name__ == \"__main__\":\r\t\t\timport doctest\r\r\t\t\tdoctest.testmod()"},"style_context_codestyle":{"kind":"number","value":282,"string":"282"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":267,"cells":{"code":{"kind":"string","value":"\r\r\rfrom typing import TYPE_CHECKING\r\rfrom ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available\r\r\rSCREAMING_SNAKE_CASE__ \t=\t\t\t\t\t\t\t{\r \"\"\"configuration_ernie\"\"\": [\"\"\"ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP\"\"\", \"\"\"ErnieConfig\"\"\", \"\"\"ErnieOnnxConfig\"\"\"],\r}\r\rtry:\r\t\t\t\t\t\t\tif not is_torch_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\rexcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\tpass\relse:\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__ \t=\t\t\t\t\t\t\t[\r\t\t\t\t\t\t\t \"\"\"ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForCausalLM\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForMaskedLM\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForMultipleChoice\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForNextSentencePrediction\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForPreTraining\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForQuestionAnswering\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForSequenceClassification\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieForTokenClassification\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErnieModel\"\"\",\r\t\t\t\t\t\t\t \"\"\"ErniePreTrainedModel\"\"\",\r\t\t\t\t\t\t\t]\r\rif TYPE_CHECKING:\r\t\t\t\t\t\t\tfrom .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig\r\r\t\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not is_torch_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\t\t\t\t\t\t\texcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass\r\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom .modeling_ernie import (\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForCausalLM,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForMaskedLM,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForMultipleChoice,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForNextSentencePrediction,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForPreTraining,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForQuestionAnswering,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForSequenceClassification,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieForTokenClassification,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErnieModel,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t ErniePreTrainedModel,\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\relse:\r\t\t\t\t\t\t\timport sys\r\r\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__ \t=\t\t\t\t\t\t\t_LazyModule(__name__, globals()[\"\"\"__file__\"\"\"], _import_structure, module_spec=__spec__)\r\r"},"code_codestyle":{"kind":"number","value":297,"string":"297"},"style_context":{"kind":"string","value":"\r\r\rfrom scipy.stats import pearsonr\r\rimport datasets\r\r\rSCREAMING_SNAKE_CASE__ \t=\t\t\t\t\t\t\t\"\"\"\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n\"\"\"\r\r\rSCREAMING_SNAKE_CASE__ \t=\t\t\t\t\t\t\t\"\"\"\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric(\\\"pearsonr\\\")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results['pearsonr'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric(\\\"pearsonr\\\")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n ['p-value', 'pearsonr']\n >>> print(round(results['pearsonr'], 2))\n -0.74\n >>> print(round(results['p-value'], 2))\n 0.15\n\"\"\"\r\r\rSCREAMING_SNAKE_CASE__ \t=\t\t\t\t\t\t\t\"\"\"\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n\"\"\"\r\r\r\r\r\r\r\r@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )\rclass __lowerCamelCase ( datasets.Metric ):\r\r\r\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\t\t\t\t\t\t\tdef \t\t\t\t\t\t\tA__ ( self ) -> int:\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\treturn datasets.MetricInfo(\r\t\t\t\t\t\t\t\t description=_DESCRIPTION\t\t, citation=_CITATION\t\t, inputs_description=_KWARGS_DESCRIPTION\t\t, features=datasets.Features(\r\t\t\t\t\t\t\t\t {\r\t\t\t\t\t\t\t\t \"predictions\": datasets.Value(\"float\" ),\r\t\t\t\t\t\t\t\t \"references\": datasets.Value(\"float\" ),\r\t\t\t\t\t\t\t\t } )\t\t, reference_urls=[\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html\"]\t\t, )\r\r\r\r\r\t\t\t\t\t\t\tdef \t\t\t\t\t\t\tA__ ( self\t\t, UpperCAmelCase\t\t, UpperCAmelCase\t\t, UpperCAmelCase=False ) -> int:\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\tif return_pvalue:\r\t\t\t\t\t\t\t\t\tlowercase_\t\t\t\t\t=\t\t\t\tpearsonr(UpperCAmelCase\t\t, UpperCAmelCase )\r\t\t\t\t\t\t\t\t\treturn {\"pearsonr\": results[0], \"p-value\": results[1]}\r\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\treturn {\"pearsonr\": float(pearsonr(UpperCAmelCase\t\t, UpperCAmelCase )[0] )}\r\r"},"style_context_codestyle":{"kind":"number","value":297,"string":"297"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":268,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\nimport argparse\r\nimport os\r\nimport re\r\n\r\n\r\nlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\t'''src/transformers'''\r\n\r\n# Pattern that looks at the indentation in a line.\r\nlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\tre.compile(R\"\"\"^(\\s*)\\S\"\"\")\r\n# Pattern that matches `\"key\":\" and puts `key` in group 0.\r\nlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\tre.compile(R\"\"\"^\\s*\\\"([^\\\"]+)\\\":\"\"\")\r\n# Pattern that matches `_import_structure[\"key\"]` and puts `key` in group 0.\r\nlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\tre.compile(R\"\"\"^\\s*_import_structure\\[\\\"([^\\\"]+)\\\"\\]\"\"\")\r\n# Pattern that matches `\"key\",` and puts `key` in group 0.\r\nlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\tre.compile(R\"\"\"^\\s*\\\"([^\\\"]+)\\\",\\s*$\"\"\")\r\n# Pattern that matches any `[stuff]` and puts `stuff` in group 0.\r\nlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\tre.compile(R\"\"\"\\[([^\\]]+)\\]\"\"\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef _snake_case\t\t\t(\t\t\t\tlowercase__\t\t):\r\n\t\t\t\t_lowerCamelCase :\t\t\tTuple = _re_indent.search(a__\t\t)\r\n\t\t\t\treturn \"\" if search is None else search.groups()[0]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef _snake_case\t\t\t(\t\t\t\tlowercase__\t\t\t\t\t\t\t, lowercase__=\"\"\t\t\t\t\t\t\t, lowercase__=None\t\t\t\t\t\t\t, lowercase__=None\t\t):\r\n\t\t\t\t_lowerCamelCase :\t\t\tUnion[str, Any] = 0\r\n\t\t\t\t_lowerCamelCase :\t\t\tint = code.split('\\n'\t\t)\r\n\t\t\t\tif start_prompt is not None:\r\n\t\t\t\t\t\t\t\twhile not lines[index].startswith(a__\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\tindex += 1\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = ['''\\n'''.join(lines[:index]\t\t)]\r\n\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tList[Any] = []\r\n\r\n\t\t\t\t# We split into blocks until we get to the `end_prompt` (or the end of the block).\r\n\t\t\t\t_lowerCamelCase :\t\t\tOptional[Any] = [lines[index]]\r\n\t\t\t\tindex += 1\r\n\t\t\t\twhile index < len(a__\t\t) and (end_prompt is None or not lines[index].startswith(a__\t\t)):\r\n\t\t\t\t\t\t\t\tif len(lines[index]\t\t) > 0 and get_indent(lines[index]\t\t) == indent_level:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif len(a__\t\t) > 0 and get_indent(current_block[-1]\t\t).startswith(indent_level + ' '\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrent_block.append(lines[index]\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblocks.append('\\n'.join(a__\t\t)\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif index < len(a__\t\t) - 1:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tList[str] = [lines[index + 1]]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tindex += 1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tUnion[str, Any] = []\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tblocks.append('\\n'.join(a__\t\t)\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tUnion[str, Any] = [lines[index]]\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\tcurrent_block.append(lines[index]\t\t)\r\n\t\t\t\t\t\t\t\tindex += 1\r\n\r\n\t\t\t\t# Adds current block if it's nonempty.\r\n\t\t\t\tif len(a__\t\t) > 0:\r\n\t\t\t\t\t\t\t\tblocks.append('\\n'.join(a__\t\t)\t\t)\r\n\r\n\t\t\t\t# Add final block after end_prompt if provided.\r\n\t\t\t\tif end_prompt is not None and index < len(a__\t\t):\r\n\t\t\t\t\t\t\t\tblocks.append('\\n'.join(lines[index:]\t\t)\t\t)\r\n\r\n\t\t\t\treturn blocks\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef _snake_case\t\t\t(\t\t\t\tlowercase__\t\t):\r\n\r\n\r\n\r\n\t\t\t\tdef _inner(lowercase__\t\t):\r\n\t\t\t\t\t\t\t\treturn key(a__\t\t).lower().replace('_'\t\t\t\t\t\t\t, ''\t\t)\r\n\r\n\t\t\t\treturn _inner\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef _snake_case\t\t\t(\t\t\t\tlowercase__\t\t\t\t\t\t\t, lowercase__=None\t\t):\r\n\r\n\r\n\r\n\t\t\t\tdef noop(lowercase__\t\t):\r\n\t\t\t\t\t\t\t\treturn x\r\n\r\n\t\t\t\tif key is None:\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tList[Any] = noop\r\n\t\t\t\t# Constants are all uppercase, they go first.\r\n\t\t\t\t_lowerCamelCase :\t\t\tUnion[str, Any] = [obj for obj in objects if key(a__\t\t).isupper()]\r\n\t\t\t\t# Classes are not all uppercase but start with a capital, they go second.\r\n\t\t\t\t_lowerCamelCase :\t\t\tint = [obj for obj in objects if key(a__\t\t)[0].isupper() and not key(a__\t\t).isupper()]\r\n\t\t\t\t# Functions begin with a lowercase, they go last.\r\n\t\t\t\t_lowerCamelCase :\t\t\tDict = [obj for obj in objects if not key(a__\t\t)[0].isupper()]\r\n\r\n\t\t\t\t_lowerCamelCase :\t\t\tOptional[int] = ignore_underscore(a__\t\t)\r\n\t\t\t\treturn sorted(a__\t\t\t\t\t\t\t, key=a__\t\t) + sorted(a__\t\t\t\t\t\t\t, key=a__\t\t) + sorted(a__\t\t\t\t\t\t\t, key=a__\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef _snake_case\t\t\t(\t\t\t\tlowercase__\t\t):\r\n\r\n\r\n\r\n\t\t\t\tdef _replace(lowercase__\t\t):\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tList[Any] = match.groups()[0]\r\n\t\t\t\t\t\t\t\tif \",\" not in imports:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn f'''[{imports}]'''\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tOptional[int] = [part.strip().replace('\"'\t\t\t\t\t\t\t, ''\t\t) for part in imports.split(','\t\t)]\r\n\t\t\t\t\t\t\t\t# We will have a final empty element if the line finished with a comma.\r\n\t\t\t\t\t\t\t\tif len(keys[-1]\t\t) == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tList[Any] = keys[:-1]\r\n\t\t\t\t\t\t\t\treturn \"[\" + \", \".join([f'''\\\"{k}\\\"''' for k in sort_objects(a__\t\t)]\t\t) + \"]\"\r\n\r\n\t\t\t\t_lowerCamelCase :\t\t\tDict = import_statement.split('\\n'\t\t)\r\n\t\t\t\tif len(a__\t\t) > 3:\r\n\t\t\t\t\t\t\t\t# Here we have to sort internal imports that are on several lines (one per name):\r\n\t\t\t\t\t\t\t\t# key: [\r\n\t\t\t\t\t\t\t\t# \"object1\",\r\n\t\t\t\t\t\t\t\t# \"object2\",\r\n\t\t\t\t\t\t\t\t# ...\r\n\t\t\t\t\t\t\t\t# ]\r\n\r\n\t\t\t\t\t\t\t\t# We may have to ignore one or two lines on each side.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tDict = 2 if lines[1].strip() == '''[''' else 1\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tDict = [(i, _re_strip_line.search(a__\t\t).groups()[0]) for i, line in enumerate(lines[idx:-idx]\t\t)]\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tUnion[str, Any] = sort_objects(a__\t\t\t\t\t\t\t, key=lambda lowercase__\t\t: x[1]\t\t)\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tint = [lines[x[0] + idx] for x in sorted_indices]\r\n\t\t\t\t\t\t\t\treturn \"\\n\".join(lines[:idx] + sorted_lines + lines[-idx:]\t\t)\r\n\t\t\t\telif len(a__\t\t) == 3:\r\n\t\t\t\t\t\t\t\t# Here we have to sort internal imports that are on one separate line:\r\n\t\t\t\t\t\t\t\t# key: [\r\n\t\t\t\t\t\t\t\t# \"object1\", \"object2\", ...\r\n\t\t\t\t\t\t\t\t# ]\r\n\t\t\t\t\t\t\t\tif _re_bracket_content.search(lines[1]\t\t) is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = _re_bracket_content.sub(_replace\t\t\t\t\t\t\t, lines[1]\t\t)\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tAny = [part.strip().replace('\"'\t\t\t\t\t\t\t, ''\t\t) for part in lines[1].split(','\t\t)]\r\n\t\t\t\t\t\t\t\t\t\t\t\t# We will have a final empty element if the line finished with a comma.\r\n\t\t\t\t\t\t\t\t\t\t\t\tif len(keys[-1]\t\t) == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tDict = keys[:-1]\r\n\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tList[str] = get_indent(lines[1]\t\t) + ''', '''.join([f'''\\\"{k}\\\"''' for k in sort_objects(a__\t\t)]\t\t)\r\n\t\t\t\t\t\t\t\treturn \"\\n\".join(a__\t\t)\r\n\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t# Finally we have to deal with imports fitting on one line\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = _re_bracket_content.sub(_replace\t\t\t\t\t\t\t, a__\t\t)\r\n\t\t\t\t\t\t\t\treturn import_statement\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef _snake_case\t\t\t(\t\t\t\tlowercase__\t\t\t\t\t\t\t, lowercase__=True\t\t):\r\n\r\n\r\n\r\n\t\t\t\twith open(a__\t\t\t\t\t\t\t, encoding='utf-8'\t\t) as f:\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tList[Any] = f.read()\r\n\r\n\t\t\t\tif \"_import_structure\" not in code:\r\n\t\t\t\t\t\t\t\treturn\r\n\r\n\t\t\t\t# Blocks of indent level 0\r\n\t\t\t\t_lowerCamelCase :\t\t\tTuple = split_code_in_indented_blocks(\r\n\t\t\t\t a__\t\t\t\t\t\t\t, start_prompt='_import_structure = {'\t\t\t\t\t\t\t, end_prompt='if TYPE_CHECKING:'\t\t)\r\n\r\n\t\t\t\t# We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt).\r\n\t\t\t\tfor block_idx in range(1\t\t\t\t\t\t\t, len(a__\t\t) - 1\t\t):\r\n\t\t\t\t\t\t\t\t# Check if the block contains some `_import_structure`s thingy to sort.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = main_blocks[block_idx]\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = block.split('\\n'\t\t)\r\n\r\n\t\t\t\t\t\t\t\t# Get to the start of the imports.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = 0\r\n\t\t\t\t\t\t\t\twhile line_idx < len(a__\t\t) and \"_import_structure\" not in block_lines[line_idx]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Skip dummy import blocks\r\n\t\t\t\t\t\t\t\t\t\t\t\tif \"import dummy\" in block_lines[line_idx]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tTuple = len(a__\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tline_idx += 1\r\n\t\t\t\t\t\t\t\tif line_idx >= len(a__\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue\r\n\r\n\t\t\t\t\t\t\t\t# Ignore beginning and last line: they don't contain anything.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tOptional[Any] = '''\\n'''.join(block_lines[line_idx:-1]\t\t)\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tOptional[Any] = get_indent(block_lines[1]\t\t)\r\n\t\t\t\t\t\t\t\t# Slit the internal block into blocks of indent level 1.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tOptional[Any] = split_code_in_indented_blocks(a__\t\t\t\t\t\t\t, indent_level=a__\t\t)\r\n\t\t\t\t\t\t\t\t# We have two categories of import key: list or _import_structure[key].append/extend\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tOptional[Any] = _re_direct_key if '''_import_structure = {''' in block_lines[0] else _re_indirect_key\r\n\t\t\t\t\t\t\t\t# Grab the keys, but there is a trap: some lines are empty or just comments.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tDict = [(pattern.search(a__\t\t).groups()[0] if pattern.search(a__\t\t) is not None else None) for b in internal_blocks]\r\n\t\t\t\t\t\t\t\t# We only sort the lines with a key.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tAny = [(i, key) for i, key in enumerate(a__\t\t) if key is not None]\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tUnion[str, Any] = [x[0] for x in sorted(a__\t\t\t\t\t\t\t, key=lambda lowercase__\t\t: x[1]\t\t)]\r\n\r\n\t\t\t\t\t\t\t\t# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tOptional[Any] = 0\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = []\r\n\t\t\t\t\t\t\t\tfor i in range(len(a__\t\t)\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\tif keys[i] is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treorderded_blocks.append(internal_blocks[i]\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tint = sort_objects_in_import(internal_blocks[sorted_indices[count]]\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treorderded_blocks.append(a__\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcount += 1\r\n\r\n # And we put our main block back together with its first and last line.\r\n\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tUnion[str, Any] = '''\\n'''.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]]\t\t)\r\n\r\n\t\t\t\tif code != \"\\n\".join(a__\t\t):\r\n\t\t\t\t\t\t\t\tif check_only:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn True\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\tprint(f'''Overwriting {file}.'''\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\twith open(a__\t\t\t\t\t\t\t, 'w'\t\t\t\t\t\t\t, encoding='utf-8'\t\t) as f:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tf.write('\\n'.join(a__\t\t)\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef _snake_case\t\t\t(\t\t\t\tlowercase__=True\t\t):\r\n\t\t\t\t_lowerCamelCase :\t\t\tTuple = []\r\n\t\t\t\tfor root, _, files in os.walk(a__\t\t):\r\n\t\t\t\t\t\t\t\tif \"__init__.py\" in files:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = sort_imports(os.path.join(a__\t\t\t\t\t\t\t, '__init__.py'\t\t)\t\t\t\t\t\t\t, check_only=a__\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif result:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_lowerCamelCase :\t\t\tstr = [os.path.join(a__\t\t\t\t\t\t\t, '__init__.py'\t\t)]\r\n\t\t\t\tif len(a__\t\t) > 0:\r\n\t\t\t\t\t\t\t\traise ValueError(f'''Would overwrite {len(a__\t\t)} files, run `make style`.'''\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\tlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\targparse.ArgumentParser()\r\n\t\t\tparser.add_argument(\"\"\"--check_only\"\"\", action=\"\"\"store_true\"\"\", help=\"\"\"Whether to only check or fix style.\"\"\")\r\n\t\t\tlowercase__ \t\t\t\t\t\t=\t\t\t\t\t\tparser.parse_args()\r\n\r\n\t\t\tsort_imports_in_all_inits(check_only=args.check_only)"},"code_codestyle":{"kind":"number","value":96,"string":"96"},"style_context":{"kind":"string","value":"\nimport gc\nimport random\nimport unittest\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom transformers import XLMRobertaTokenizerFast\n\nfrom diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel\nfrom diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP\nfrom diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device\nfrom diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu\n\nfrom ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference\n\n\nenable_full_determinism()\n\n\n\n\n\n\nclass a_ ( a__\t\t\t\t\t\t\t, unittest.TestCase\t\t\t\t):\n\n\n\n \"\"\"simple docstring\"\"\"\n __SCREAMING_SNAKE_CASE : str\t\t= KandinskyImgaImgPipeline\n __SCREAMING_SNAKE_CASE : str\t\t= ['prompt', 'image_embeds', 'negative_image_embeds', 'image']\n __SCREAMING_SNAKE_CASE : int\t\t= [\n 'prompt',\n 'negative_prompt',\n 'image_embeds',\n 'negative_image_embeds',\n 'image',\n ]\n __SCREAMING_SNAKE_CASE : int\t\t= [\n 'generator',\n 'height',\n 'width',\n 'strength',\n 'guidance_scale',\n 'negative_prompt',\n 'num_inference_steps',\n 'return_dict',\n 'guidance_scale',\n 'num_images_per_prompt',\n 'output_type',\n 'return_dict',\n ]\n __SCREAMING_SNAKE_CASE : List[Any]\t\t= False\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->int:\n return 32\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->List[str]:\n return 32\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Optional[int]:\n return self.time_input_dim\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Tuple:\n return self.time_input_dim * 4\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Optional[int]:\n return 100\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Dict:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base'''\t\t\t\t\t)\n return tokenizer\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Tuple:\n torch.manual_seed(0\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t= MCLIPConfig(\n numDims=self.cross_attention_dim\t\t\t\t\t\t\t, transformerDimensions=self.text_embedder_hidden_size\t\t\t\t\t\t\t, hidden_size=self.text_embedder_hidden_size\t\t\t\t\t\t\t, intermediate_size=37\t\t\t\t\t\t\t, num_attention_heads=4\t\t\t\t\t\t\t, num_hidden_layers=5\t\t\t\t\t\t\t, vocab_size=1005\t\t\t\t\t\t\t, )\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t= MultilingualCLIP(_lowerCamelCase\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= text_encoder.eval()\n\n return text_encoder\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Union[str, Any]:\n torch.manual_seed(0\t\t\t\t\t)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= {\n '''in_channels''': 4,\n # Out channels is double in channels because predicts mean and variance\n '''out_channels''': 8,\n '''addition_embed_type''': '''text_image''',\n '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),\n '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),\n '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',\n '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),\n '''layers_per_block''': 1,\n '''encoder_hid_dim''': self.text_embedder_hidden_size,\n '''encoder_hid_dim_type''': '''text_image_proj''',\n '''cross_attention_dim''': self.cross_attention_dim,\n '''attention_head_dim''': 4,\n '''resnet_time_scale_shift''': '''scale_shift''',\n '''class_embed_type''': None,\n }\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tTuple\t\t\t\t\t\t\t\t= UNetaDConditionModel(**_lowerCamelCase\t\t\t\t\t)\n return model\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->List[str]:\n return {\n \"block_out_channels\": [32, 64],\n \"down_block_types\": [\"DownEncoderBlock2D\", \"AttnDownEncoderBlock2D\"],\n \"in_channels\": 3,\n \"latent_channels\": 4,\n \"layers_per_block\": 1,\n \"norm_num_groups\": 8,\n \"norm_type\": \"spatial\",\n \"num_vq_embeddings\": 12,\n \"out_channels\": 3,\n \"up_block_types\": [\n \"AttnUpDecoderBlock2D\",\n \"UpDecoderBlock2D\",\n ],\n \"vq_embed_dim\": 4,\n }\n\n\n\n\n\n\n @property\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Optional[Any]:\n torch.manual_seed(0\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t= VQModel(**self.dummy_movq_kwargs\t\t\t\t\t)\n return model\n\n\n\n\n\n\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Dict:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= self.dummy_text_encoder\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= self.dummy_tokenizer\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t= self.dummy_unet\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= self.dummy_movq\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t= {\n '''num_train_timesteps''': 1000,\n '''beta_schedule''': '''linear''',\n '''beta_start''': 0.0_0_0_8_5,\n '''beta_end''': 0.0_1_2,\n '''clip_sample''': False,\n '''set_alpha_to_one''': False,\n '''steps_offset''': 0,\n '''prediction_type''': '''epsilon''',\n '''thresholding''': False,\n }\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t= DDIMScheduler(**_lowerCamelCase\t\t\t\t\t)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t= {\n '''text_encoder''': text_encoder,\n '''tokenizer''': tokenizer,\n '''unet''': unet,\n '''scheduler''': scheduler,\n '''movq''': movq,\n }\n\n return components\n\n\n\n\n\n\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t\t\t, _lowerCamelCase=0\t\t\t\t\t) ->str:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t= floats_tensor((1, self.cross_attention_dim)\t\t\t\t\t\t\t, rng=random.Random(_lowerCamelCase\t\t\t\t\t)\t\t\t\t\t).to(_lowerCamelCase\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t= floats_tensor((1, self.cross_attention_dim)\t\t\t\t\t\t\t, rng=random.Random(seed + 1\t\t\t\t\t)\t\t\t\t\t).to(_lowerCamelCase\t\t\t\t\t)\n # create init_image\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= floats_tensor((1, 3, 64, 64)\t\t\t\t\t\t\t, rng=random.Random(_lowerCamelCase\t\t\t\t\t)\t\t\t\t\t).to(_lowerCamelCase\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t= image.cpu().permute(0\t\t\t\t\t\t\t, 2\t\t\t\t\t\t\t, 3\t\t\t\t\t\t\t, 1\t\t\t\t\t)[0]\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= Image.fromarray(np.uinta(_lowerCamelCase\t\t\t\t\t)\t\t\t\t\t).convert('''RGB'''\t\t\t\t\t).resize((256, 256)\t\t\t\t\t)\n\n if str(_lowerCamelCase\t\t\t\t\t).startswith('''mps'''\t\t\t\t\t):\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= torch.manual_seed(_lowerCamelCase\t\t\t\t\t)\n else:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= torch.Generator(device=_lowerCamelCase\t\t\t\t\t).manual_seed(_lowerCamelCase\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= {\n '''prompt''': '''horse''',\n '''image''': init_image,\n '''image_embeds''': image_embeds,\n '''negative_image_embeds''': negative_image_embeds,\n '''generator''': generator,\n '''height''': 64,\n '''width''': 64,\n '''num_inference_steps''': 10,\n '''guidance_scale''': 7.0,\n '''strength''': 0.2,\n '''output_type''': '''np''',\n }\n return inputs\n\n\n\n\n\n\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Dict:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= '''cpu'''\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t= self.get_dummy_components()\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t= self.pipeline_class(**_lowerCamelCase\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= pipe.to(_lowerCamelCase\t\t\t\t\t)\n\n pipe.set_progress_bar_config(disable=_lowerCamelCase\t\t\t\t\t)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= pipe(**self.get_dummy_inputs(_lowerCamelCase\t\t\t\t\t)\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t= output.images\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= pipe(\n **self.get_dummy_inputs(_lowerCamelCase\t\t\t\t\t)\t\t\t\t\t\t\t, return_dict=_lowerCamelCase\t\t\t\t\t\t\t, )[0]\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t= image[0, -3:, -3:, -1]\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[Any]\t\t\t\t\t\t\t\t= image_from_tuple[0, -3:, -3:, -1]\n\n assert image.shape == (1, 64, 64, 3)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t= np.array(\n [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3]\t\t\t\t\t)\n assert (\n np.abs(image_slice.flatten() - expected_slice\t\t\t\t\t).max() < 1e-2\n ), F\"\"\" expected_slice {expected_slice}, but got {image_slice.flatten()}\"\"\"\n assert (\n np.abs(image_from_tuple_slice.flatten() - expected_slice\t\t\t\t\t).max() < 1e-2\n ), F\"\"\" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}\"\"\"\n\n\n\n\n\n\n@slow\n@require_torch_gpu\nclass a_ ( unittest.TestCase\t\t\t\t):\n\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n\n\n\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->List[Any]:\n # clean up the VRAM after each test\n super().tearDown()\n gc.collect()\n torch.cuda.empty_cache()\n\n\n\n\n\n\n def __lowerCAmelCase\t\t\t(\t\t\t\t\t\tself\t\t\t\t\t) ->Optional[int]:\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t= load_numpy(\n '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''\n '''/kandinsky/kandinsky_img2img_frog.npy'''\t\t\t\t\t)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t= load_image(\n '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png'''\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= '''A red cartoon frog, 4k'''\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tAny\t\t\t\t\t\t\t\t= KandinskyPriorPipeline.from_pretrained(\n '''kandinsky-community/kandinsky-2-1-prior'''\t\t\t\t\t\t\t, torch_dtype=torch.floataa\t\t\t\t\t)\n pipe_prior.to(_lowerCamelCase\t\t\t\t\t)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t= KandinskyImgaImgPipeline.from_pretrained(\n '''kandinsky-community/kandinsky-2-1'''\t\t\t\t\t\t\t, torch_dtype=torch.floataa\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tstr\t\t\t\t\t\t\t\t= pipeline.to(_lowerCamelCase\t\t\t\t\t)\n\n pipeline.set_progress_bar_config(disable=_lowerCamelCase\t\t\t\t\t)\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t= torch.Generator(device='''cpu'''\t\t\t\t\t).manual_seed(0\t\t\t\t\t)\n SCREAMING_SNAKE_CASE\t,\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t= pipe_prior(\n _lowerCamelCase\t\t\t\t\t\t\t, generator=_lowerCamelCase\t\t\t\t\t\t\t, num_inference_steps=5\t\t\t\t\t\t\t, negative_prompt=''''''\t\t\t\t\t\t\t, ).to_tuple()\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t= pipeline(\n _lowerCamelCase\t\t\t\t\t\t\t, image=_lowerCamelCase\t\t\t\t\t\t\t, image_embeds=_lowerCamelCase\t\t\t\t\t\t\t, negative_image_embeds=_lowerCamelCase\t\t\t\t\t\t\t, generator=_lowerCamelCase\t\t\t\t\t\t\t, num_inference_steps=100\t\t\t\t\t\t\t, height=768\t\t\t\t\t\t\t, width=768\t\t\t\t\t\t\t, strength=0.2\t\t\t\t\t\t\t, output_type='''np'''\t\t\t\t\t\t\t, )\n\n SCREAMING_SNAKE_CASE\t\t\t\t\t\t\t:\t\t\t\t\t\t\tTuple\t\t\t\t\t\t\t\t= output.images[0]\n\n assert image.shape == (768, 768, 3)\n\n assert_mean_pixel_difference(_lowerCamelCase\t\t\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t)\n"},"style_context_codestyle":{"kind":"number","value":313,"string":"313"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":269,"cells":{"code":{"kind":"string","value":"\"\"\"simple docstring\"\"\"\r\n\r\nfrom __future__ import annotations\r\n\r\nimport os\r\nimport tempfile\r\nimport unittest\r\n\r\nimport numpy as np\r\nfrom huggingface_hub import hf_hub_download\r\n\r\nfrom transformers import is_tensorflow_text_available, is_tf_available\r\nfrom transformers.testing_utils import require_tensorflow_text, require_tf, slow\r\n\r\nfrom ..test_modeling_tf_common import floats_tensor\r\nfrom .test_framework_agnostic import GenerationIntegrationTestsMixin\r\n\r\n\r\nif is_tf_available():\r\n\t\t\t\timport tensorflow as tf\r\n\r\n\t\t\t\tfrom transformers import (\r\n\t\t\t\t AutoTokenizer,\r\n\t\t\t\t TFAutoModelForCausalLM,\r\n\t\t\t\t TFAutoModelForSeqaSeqLM,\r\n\t\t\t\t TFAutoModelForSpeechSeqaSeq,\r\n\t\t\t\t TFAutoModelForVisionaSeq,\r\n\t\t\t\t TFBartForConditionalGeneration,\r\n\t\t\t\t TFLogitsProcessorList,\r\n\t\t\t\t TFMinLengthLogitsProcessor,\r\n\t\t\t\t tf_top_k_top_p_filtering,\r\n\t\t\t\t)\r\n\r\nif is_tensorflow_text_available():\r\n\t\t\t\timport tensorflow_text as text\r\n\r\n\r\n\r\n\r\n\r\n\r\n@require_tf\r\nclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\tunittest.TestCase ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : Any\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tTuple:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.convert_to_tensor(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t [\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t [\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 8.2_22_09_91, # 3rd highest value; idx. 0\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -0.5_62_00_44,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 5.23_22_97_52,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 4.0_38_63_93,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -6.8_79_83_78,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -0.54_78_58_02,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -3.2_01_21_53,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 2.92_77_71_76,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 1.88_17_19_53,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 7.35_34_12_76, # 5th highest value; idx. 9\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 8.43_20_78_33, # 2nd highest value; idx. 10\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -9.85_71_18_36,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -5.96_20_92_36,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -1.13_03_91_61,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -7.1_11_52_94,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -0.8_36_96_33,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -5.3_18_64_08,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 7.06_42_74_07,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 0.81_36_93_44,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -0.82_02_38_17,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -5.9_17_97_96,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 0.58_81_34_43,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -6.99_77_84_38,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 4.71_55_11_89,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -0.18_77_16_37,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 7.44_02_07_59, # 4th highest value; idx. 25\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 9.38_45_09_87, # 1st highest value; idx. 26\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 2.12_66_29_41,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -9.32_56_20_38,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 2.35_65_25_22,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t ], # cummulative prob of 5 highest values <= 0.6\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t [\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 0.58_42_55_18,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 4.53_13_92_38,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -5.57_51_04_64,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -6.28_03_06_99,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -7.19_52_95_03,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -4.02_12_25_51,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 1.39_33_70_37,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -6.06_70_70_57,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 1.59_48_05_17,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -9.64_31_19,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 0.03_90_77_99,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 0.67_23_17_62,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -8.88_20_67_26,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 6.27_11_59_22, # 4th highest value; idx. 13\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 2.28_52_07_23,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 4.82_76_75_06,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 4.30_42_13_68,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 8.8_27_53_13, # 2nd highest value; idx. 17\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 5.44_02_99_58, # 5th highest value; idx. 18\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -4.4_73_57_94,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 7.38_57_95_36, # 3rd highest value; idx. 20\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -2.91_05_16_63,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 2.61_94_60_77,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -2.5_67_47_62,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -9.48_95_93_02,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -4.02_92_26_45,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -1.35_41_69_18,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 9.67_70_23_23, # 1st highest value; idx. 27\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t -5.89_47_85_53,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t 1.85_37_04_67,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t ], # cummulative prob of 5 highest values <= 0.6\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t ] ,\t\t\t\tdtype=tf.floataa ,\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.convert_to_tensor(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] ,\t\t\t\tdtype=tf.intaa ,\t\t\t\t) # expected non filtered idx as noted above\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.convert_to_tensor(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t [8.22_20_99, 7.3_53_41_26, 8.43_20_78, 7.4_40_20_75, 9.3_84_51, 6.27_11_59, 8.82_75_31, 5.4_40_29_95, 7.3_85_79_56, 9.67_70_23] ,\t\t\t\tdtype=tf.floataa ,\t\t\t\t) # expected non filtered values as noted above\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf_top_k_top_p_filtering(UpperCamelCase__ ,\t\t\t\ttop_k=10 ,\t\t\t\ttop_p=0.6 ,\t\t\t\tmin_tokens_to_keep=4\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=output[output != -float('''inf'''\t\t\t\t\t\t\t)]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.cast(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t tf.where(tf.not_equal(UpperCamelCase__ ,\t\t\t\ttf.constant(-float('''inf'''\t\t\t\t\t\t\t) ,\t\t\t\tdtype=tf.floataa\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t) ,\t\t\t\tdtype=tf.intaa ,\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\ttf.debugging.assert_near(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__ ,\t\t\t\trtol=1E-12\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\ttf.debugging.assert_equal(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n@require_tf\r\nclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\tunittest.TestCase\t\t\t,\t\t\t__a ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tif is_tf_available():\r\n\t\t\t\t\t\t\t\t\t\t\t\tlowercase__ = {\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''AutoModelForCausalLM''': TFAutoModelForCausalLM,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''AutoModelForSpeechSeq2Seq''': TFAutoModelForSpeechSeqaSeq,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''AutoModelForSeq2SeqLM''': TFAutoModelForSeqaSeqLM,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''AutoModelForVision2Seq''': TFAutoModelForVisionaSeq,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''LogitsProcessorList''': TFLogitsProcessorList,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''MinLengthLogitsProcessor''': TFMinLengthLogitsProcessor,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''create_tensor_fn''': tf.convert_to_tensor,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''floats_tensor''': floats_tensor,\r\n\t\t\t\t\t\t\t\t\t\t\t\t '''return_tensors''': '''tf''',\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@slow\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : Optional[int]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tint:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=2\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=2\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\ttf.Module ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef __init__(\t\t\t\t\t\t\tself : Optional[Any] ,\t\t\t\tUpperCamelCase__ : List[str]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tOptional[Any]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuper(UpperCamelCase__ ,\t\t\t\tself\t\t\t\t\t\t\t).__init__()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=model\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t@tf.function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t input_signature=(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t tf.TensorSpec((None, input_length) ,\t\t\t\ttf.intaa ,\t\t\t\tname='''input_ids'''\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t tf.TensorSpec((None, input_length) ,\t\t\t\ttf.intaa ,\t\t\t\tname='''attention_mask'''\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ) ,\t\t\t\tjit_compile=UpperCamelCase__ ,\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : Dict ,\t\t\t\tUpperCamelCase__ : str ,\t\t\t\tUpperCamelCase__ : Optional[Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tstr:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=self.model.generate(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t input_ids=UpperCamelCase__ ,\t\t\t\tattention_mask=UpperCamelCase__ ,\t\t\t\tmax_new_tokens=UpperCamelCase__ ,\t\t\t\treturn_dict_in_generate=UpperCamelCase__ ,\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn {\"sequences\": outputs[\"sequences\"]}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=[[2, 0], [102, 103]]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=[[1, 0], [1, 1]]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=DummyModel(model=UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttf.saved_model.save(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__ ,\t\t\t\tsignatures={'''serving_default''': dummy_model.serving}\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.saved_model.load(UpperCamelCase__\t\t\t\t\t\t\t).signatures['''serving_default''']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor batch_size in range(1 ,\t\t\t\tlen(UpperCamelCase__\t\t\t\t\t\t\t) + 1\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t={\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''input_ids''': tf.constant(dummy_input_ids[:batch_size]\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''attention_mask''': tf.constant(dummy_attention_masks[:batch_size]\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=serving_func(**UpperCamelCase__\t\t\t\t\t\t\t)['''sequences''']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=test_model.generate(**UpperCamelCase__ ,\t\t\t\tmax_new_tokens=UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttf.debugging.assert_equal(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@slow\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : List[Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tAny:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=2\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\ttf.Module ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef __init__(\t\t\t\t\t\t\tself : List[str] ,\t\t\t\tUpperCamelCase__ : Tuple\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tstr:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuper(UpperCamelCase__ ,\t\t\t\tself\t\t\t\t\t\t\t).__init__()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=model\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t@tf.function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t input_signature=(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t tf.TensorSpec((batch_size, None) ,\t\t\t\ttf.intaa ,\t\t\t\tname='''input_ids'''\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t tf.TensorSpec((batch_size, None) ,\t\t\t\ttf.intaa ,\t\t\t\tname='''attention_mask'''\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ) ,\t\t\t\tjit_compile=UpperCamelCase__ ,\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : List[str] ,\t\t\t\tUpperCamelCase__ : Optional[Any] ,\t\t\t\tUpperCamelCase__ : int\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tAny:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=self.model.generate(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t input_ids=UpperCamelCase__ ,\t\t\t\tattention_mask=UpperCamelCase__ ,\t\t\t\tmax_new_tokens=UpperCamelCase__ ,\t\t\t\treturn_dict_in_generate=UpperCamelCase__ ,\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn {\"sequences\": outputs[\"sequences\"]}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=[[2], [102, 103]]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=[[1], [1, 1]]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=DummyModel(model=UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttf.saved_model.save(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__ ,\t\t\t\tsignatures={'''serving_default''': dummy_model.serving}\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.saved_model.load(UpperCamelCase__\t\t\t\t\t\t\t).signatures['''serving_default''']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor input_row in range(len(UpperCamelCase__\t\t\t\t\t\t\t)\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t={\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''input_ids''': tf.constant([dummy_input_ids[input_row]]\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''attention_mask''': tf.constant([dummy_attention_masks[input_row]]\t\t\t\t\t\t\t),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=serving_func(**UpperCamelCase__\t\t\t\t\t\t\t)['''sequences''']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=test_model.generate(**UpperCamelCase__ ,\t\t\t\tmax_new_tokens=UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttf.debugging.assert_equal(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@slow\r\n\t\t\t\t\t\t@require_tensorflow_text\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : List[Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tDict:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twith tempfile.TemporaryDirectory() as tmp_dir:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# file needed to load the TF tokenizer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\thf_hub_download(repo_id='''google/flan-t5-small''' ,\t\t\t\tfilename='''spiece.model''' ,\t\t\t\tlocal_dir=UpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\ttf.keras.layers.Layer ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef __init__(\t\t\t\t\t\t\tself : Optional[Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tOptional[int]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=text.SentencepieceTokenizer(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t model=tf.io.gfile.GFile(os.path.join(UpperCamelCase__ ,\t\t\t\t'''spiece.model'''\t\t\t\t\t\t\t) ,\t\t\t\t'''rb'''\t\t\t\t\t\t\t).read()\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=TFAutoModelForSeqaSeqLM.from_pretrained('''hf-internal-testing/tiny-random-t5'''\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : str ,\t\t\t\tUpperCamelCase__ : Any ,\t\t\t\t*UpperCamelCase__ : Any ,\t\t\t\t**UpperCamelCase__ : Dict\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tint:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=self.tokenizer.tokenize(UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t, __UpperCamelCase\t\t\t\t\t\t\t=text.pad_model_inputs(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCamelCase__ ,\t\t\t\tmax_seq_length=64 ,\t\t\t\tpad_value=self.model.config.pad_token_id\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=self.model.generate(input_ids=UpperCamelCase__ ,\t\t\t\tattention_mask=UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn self.tokenizer.detokenize(UpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=CompleteSentenceTransformer()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.keras.layers.Input(shape=(1,) ,\t\t\t\tdtype=tf.string ,\t\t\t\tname='''inputs'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=complete_model(UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tf.keras.Model(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tkeras_model.save(UpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : List[Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tAny:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t={\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '''do_sample''': True,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '''num_beams''': 1,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '''top_p''': 0.7,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '''top_k''': 10,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t '''temperature''': 0.7,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=14\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t='''Hello, my dog is cute and'''\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=tokenizer(UpperCamelCase__ ,\t\t\t\treturn_tensors='''tf'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=TFAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-random-gpt2'''\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=638\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t# forces the generation to happen on CPU, to avoid GPU-related quirks\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twith tf.device(''':/CPU:0'''\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttf.random.set_seed(0\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=model.generate(**UpperCamelCase__ ,\t\t\t\teos_token_id=UpperCamelCase__ ,\t\t\t\t**UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(expectation == len(generated_tokens[0]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=[638, 198]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twith tf.device(''':/CPU:0'''\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttf.random.set_seed(0\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=model.generate(**UpperCamelCase__ ,\t\t\t\teos_token_id=UpperCamelCase__ ,\t\t\t\t**UpperCamelCase__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(expectation == len(generated_tokens[0]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : Union[str, Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tDict:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bart'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t='''Hugging Face is a technology company based in New York and Paris.'''\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=bart_tokenizer(UpperCamelCase__ ,\t\t\t\treturn_tensors='''tf'''\t\t\t\t\t\t\t).input_ids\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=TFBartForConditionalGeneration.from_pretrained('''hf-internal-testing/tiny-random-bart'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=bart_model.generate(UpperCamelCase__\t\t\t\t\t\t\t).numpy()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\t__a ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : Union[str, Any] ,\t\t\t\tUpperCamelCase__ : List[Any] ,\t\t\t\tUpperCamelCase__ : Tuple=None ,\t\t\t\t**UpperCamelCase__ : Optional[Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tList[Any]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn super().call(UpperCamelCase__ ,\t\t\t\t**UpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=FakeBart.from_pretrained('''hf-internal-testing/tiny-random-bart'''\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=bart_model.generate(UpperCamelCase__ ,\t\t\t\tfoo='''bar'''\t\t\t\t\t\t\t).numpy()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(np.array_equal(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\tbart_model.model.encoder.__class__ ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : Union[str, Any] ,\t\t\t\tUpperCamelCase__ : List[str] ,\t\t\t\t**UpperCamelCase__ : Union[str, Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tDict:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn super().call(UpperCamelCase__ ,\t\t\t\t**UpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=FakeEncoder(bart_model.config ,\t\t\t\tbart_model.model.shared\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=fake_encoder\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t# Normal generation still works (the output will be different because the encoder weights are different)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=bart_model.generate(UpperCamelCase__\t\t\t\t\t\t\t).numpy()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twith self.assertRaises(UpperCamelCase__\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input \"foo\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbart_model.generate(UpperCamelCase__ ,\t\t\t\tfoo='''bar'''\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":85,"string":"85"},"style_context":{"kind":"string","value":"\"\"\"simple docstring\"\"\"\r\n\r\nfrom collections import OrderedDict\r\nfrom typing import Mapping\r\n\r\nfrom ...configuration_utils import PretrainedConfig\r\nfrom ...onnx import OnnxConfig\r\n\r\n\r\n__lowercase\t\t\t\t =\t\t\t\t\t\t\t{\r\n '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/config.json''',\r\n '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/config.json''',\r\n '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/config.json''',\r\n '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json''',\r\n '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/config.json''',\r\n '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/config.json''',\r\n '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/config.json''',\r\n '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json''',\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\t__a ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tlowercase__ = '''albert'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef __init__(\t\t\t\t\t\t\tself : List[Any] ,\t\t\t\tUpperCamelCase__ : List[Any]=30000 ,\t\t\t\tUpperCamelCase__ : int=128 ,\t\t\t\tUpperCamelCase__ : str=4096 ,\t\t\t\tUpperCamelCase__ : Optional[Any]=12 ,\t\t\t\tUpperCamelCase__ : Dict=1 ,\t\t\t\tUpperCamelCase__ : Union[str, Any]=64 ,\t\t\t\tUpperCamelCase__ : Any=16384 ,\t\t\t\tUpperCamelCase__ : Any=1 ,\t\t\t\tUpperCamelCase__ : Optional[int]=\"gelu_new\" ,\t\t\t\tUpperCamelCase__ : int=0 ,\t\t\t\tUpperCamelCase__ : List[Any]=0 ,\t\t\t\tUpperCamelCase__ : Dict=512 ,\t\t\t\tUpperCamelCase__ : Optional[Any]=2 ,\t\t\t\tUpperCamelCase__ : str=0.02 ,\t\t\t\tUpperCamelCase__ : Tuple=1E-12 ,\t\t\t\tUpperCamelCase__ : Tuple=0.1 ,\t\t\t\tUpperCamelCase__ : Dict=\"absolute\" ,\t\t\t\tUpperCamelCase__ : List[Any]=0 ,\t\t\t\tUpperCamelCase__ : int=2 ,\t\t\t\tUpperCamelCase__ : Optional[Any]=3 ,\t\t\t\t**UpperCamelCase__ : List[str] ,\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tDict:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(pad_token_id=UpperCamelCase__ ,\t\t\t\tbos_token_id=UpperCamelCase__ ,\t\t\t\teos_token_id=UpperCamelCase__ ,\t\t\t\t**UpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=vocab_size\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=embedding_size\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=hidden_size\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=num_hidden_layers\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=num_hidden_groups\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=num_attention_heads\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=inner_group_num\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=hidden_act\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=intermediate_size\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=hidden_dropout_prob\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=attention_probs_dropout_prob\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=max_position_embeddings\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=type_vocab_size\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=initializer_range\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=layer_norm_eps\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=classifier_dropout_prob\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=position_embedding_type\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass \t\t\t\t\t\t_lowercase\t\t\t\t(\t\t__a ):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@property\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : Union[str, Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tMapping[str, Mapping[int, str]]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif self.task == \"multiple-choice\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t={0: '''batch''', 1: '''choice''', 2: '''sequence'''}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t={0: '''batch''', 1: '''sequence'''}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn OrderedDict(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t [\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t ('''input_ids''', dynamic_axis),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t ('''attention_mask''', dynamic_axis),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t ('''token_type_ids''', dynamic_axis),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t ]\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":85,"string":"85"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":270,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nimport argparse\r\n\r\nimport gdown\r\nimport numpy as np\r\nimport torch\r\nfrom huggingface_hub import hf_hub_download\r\n\r\nfrom transformers import (\r\n CLIPTokenizer,\r\n CLIPTokenizerFast,\r\n VideoMAEImageProcessor,\r\n XCLIPConfig,\r\n XCLIPModel,\r\n XCLIPProcessor,\r\n XCLIPTextConfig,\r\n XCLIPVisionConfig,\r\n)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t__lowerCamelCase\t\t\t\t( A__ ,\t\t\t\t\t\tA__ ) ->\tOptional[Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n UpperCamelCase\t\t\t\t\t= XCLIPTextConfig()\r\n\r\n # derive patch size from model name\r\n UpperCamelCase\t\t\t\t\t= model_name.find('patch' )\r\n UpperCamelCase\t\t\t\t\t= int(model_name[start_idx + len('patch' ) : start_idx + len('patch' ) + 2] )\r\n UpperCamelCase\t\t\t\t\t= XCLIPVisionConfig(patch_size=A__ ,\t\t\t\t\t\tnum_frames=A__ )\r\n\r\n if \"large\" in model_name:\r\n UpperCamelCase\t\t\t\t\t= 768\r\n UpperCamelCase\t\t\t\t\t= 3_072\r\n UpperCamelCase\t\t\t\t\t= 12\r\n\r\n UpperCamelCase\t\t\t\t\t= 1_024\r\n UpperCamelCase\t\t\t\t\t= 4_096\r\n UpperCamelCase\t\t\t\t\t= 16\r\n UpperCamelCase\t\t\t\t\t= 24\r\n UpperCamelCase\t\t\t\t\t= 768\r\n UpperCamelCase\t\t\t\t\t= 3_072\r\n\r\n if model_name == \"xclip-large-patch14-16-frames\":\r\n UpperCamelCase\t\t\t\t\t= 336\r\n\r\n UpperCamelCase\t\t\t\t\t= XCLIPConfig.from_text_vision_configs(A__ ,\t\t\t\t\t\tA__ )\r\n\r\n if \"large\" in model_name:\r\n UpperCamelCase\t\t\t\t\t= 768\r\n\r\n return config\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t__lowerCamelCase\t\t\t\t( A__ ) ->\tTuple:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n # text encoder\r\n if name == \"token_embedding.weight\":\r\n UpperCamelCase\t\t\t\t\t= name.replace('token_embedding.weight' ,\t\t\t\t\t\t'text_model.embeddings.token_embedding.weight' )\r\n if name == \"positional_embedding\":\r\n UpperCamelCase\t\t\t\t\t= name.replace('positional_embedding' ,\t\t\t\t\t\t'text_model.embeddings.position_embedding.weight' )\r\n if \"ln_1\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('ln_1' ,\t\t\t\t\t\t'layer_norm1' )\r\n if \"ln_2\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('ln_2' ,\t\t\t\t\t\t'layer_norm2' )\r\n if \"c_fc\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('c_fc' ,\t\t\t\t\t\t'fc1' )\r\n if \"c_proj\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('c_proj' ,\t\t\t\t\t\t'fc2' )\r\n if name.startswith('transformer.resblocks' ):\r\n UpperCamelCase\t\t\t\t\t= name.replace('transformer.resblocks' ,\t\t\t\t\t\t'text_model.encoder.layers' )\r\n if \"attn.out_proj\" in name and \"message\" not in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('attn.out_proj' ,\t\t\t\t\t\t'self_attn.out_proj' )\r\n if \"ln_final\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('ln_final' ,\t\t\t\t\t\t'text_model.final_layer_norm' )\r\n # visual encoder\r\n if name == \"visual.class_embedding\":\r\n UpperCamelCase\t\t\t\t\t= name.replace('visual.class_embedding' ,\t\t\t\t\t\t'vision_model.embeddings.class_embedding' )\r\n if name == \"visual.positional_embedding\":\r\n UpperCamelCase\t\t\t\t\t= name.replace('visual.positional_embedding' ,\t\t\t\t\t\t'vision_model.embeddings.position_embedding.weight' )\r\n if name.startswith('visual.transformer.resblocks' ):\r\n UpperCamelCase\t\t\t\t\t= name.replace('visual.transformer.resblocks' ,\t\t\t\t\t\t'vision_model.encoder.layers' )\r\n if \"visual.conv1\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('visual.conv1' ,\t\t\t\t\t\t'vision_model.embeddings.patch_embedding' )\r\n if \"visual.ln_pre\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('visual.ln_pre' ,\t\t\t\t\t\t'vision_model.pre_layernorm' )\r\n if \"visual.ln_post\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('visual.ln_post' ,\t\t\t\t\t\t'vision_model.post_layernorm' )\r\n if \"visual.proj\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('visual.proj' ,\t\t\t\t\t\t'visual_projection.weight' )\r\n if \"text_projection\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('text_projection' ,\t\t\t\t\t\t'text_projection.weight' )\r\n # things on top\r\n if \"prompts_visual_proj\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('prompts_visual_proj' ,\t\t\t\t\t\t'prompts_visual_projection' )\r\n if \"prompts_visual_ln\" in name:\r\n UpperCamelCase\t\t\t\t\t= name.replace('prompts_visual_ln' ,\t\t\t\t\t\t'prompts_visual_layernorm' )\r\n # mit\r\n if name == \"mit.positional_embedding\":\r\n UpperCamelCase\t\t\t\t\t= name.replace('positional' ,\t\t\t\t\t\t'position' )\r\n if name.startswith('mit.resblocks' ):\r\n UpperCamelCase\t\t\t\t\t= name.replace('mit.resblocks' ,\t\t\t\t\t\t'mit.encoder.layers' )\r\n # prompts generator\r\n if name.startswith('prompts_generator.norm' ):\r\n UpperCamelCase\t\t\t\t\t= name.replace('prompts_generator.norm' ,\t\t\t\t\t\t'prompts_generator.layernorm' )\r\n\r\n return name\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t__lowerCamelCase\t\t\t\t( A__ ,\t\t\t\t\t\tA__ ) ->\tOptional[int]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n for key in orig_state_dict.copy().keys():\r\n UpperCamelCase\t\t\t\t\t= orig_state_dict.pop(A__ )\r\n\r\n if \"attn.in_proj\" in key:\r\n UpperCamelCase\t\t\t\t\t= key.split('.' )\r\n if key.startswith('visual' ):\r\n UpperCamelCase\t\t\t\t\t= key_split[3]\r\n UpperCamelCase\t\t\t\t\t= config.vision_config.hidden_size\r\n if \"message_attn\" in key:\r\n if \"weight\" in key:\r\n UpperCamelCase\t\t\t\t\t= val[\r\n :dim, :\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n dim : dim * 2, :\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n -dim:, :\r\n ]\r\n else:\r\n UpperCamelCase\t\t\t\t\t= val[\r\n :dim\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n dim : dim * 2\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n -dim:\r\n ]\r\n else:\r\n if \"weight\" in key:\r\n UpperCamelCase\t\t\t\t\t= val[\r\n :dim, :\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n dim : dim * 2, :\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n -dim:, :\r\n ]\r\n else:\r\n UpperCamelCase\t\t\t\t\t= val[:dim]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n dim : dim * 2\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[-dim:]\r\n elif key.startswith('mit' ):\r\n UpperCamelCase\t\t\t\t\t= key_split[2]\r\n UpperCamelCase\t\t\t\t\t= config.vision_config.mit_hidden_size\r\n if \"weight\" in key:\r\n UpperCamelCase\t\t\t\t\t= val[:dim, :]\r\n UpperCamelCase\t\t\t\t\t= val[dim : dim * 2, :]\r\n UpperCamelCase\t\t\t\t\t= val[-dim:, :]\r\n else:\r\n UpperCamelCase\t\t\t\t\t= val[:dim]\r\n UpperCamelCase\t\t\t\t\t= val[dim : dim * 2]\r\n UpperCamelCase\t\t\t\t\t= val[-dim:]\r\n else:\r\n UpperCamelCase\t\t\t\t\t= key_split[2]\r\n UpperCamelCase\t\t\t\t\t= config.text_config.hidden_size\r\n if \"weight\" in key:\r\n UpperCamelCase\t\t\t\t\t= val[:dim, :]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n dim : dim * 2, :\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[-dim:, :]\r\n else:\r\n UpperCamelCase\t\t\t\t\t= val[:dim]\r\n UpperCamelCase\t\t\t\t\t= val[\r\n dim : dim * 2\r\n ]\r\n UpperCamelCase\t\t\t\t\t= val[-dim:]\r\n else:\r\n UpperCamelCase\t\t\t\t\t= rename_key(A__ )\r\n if new_key_name in [\"visual_projection.weight\", \"text_projection.weight\"]:\r\n UpperCamelCase\t\t\t\t\t= val.T\r\n UpperCamelCase\t\t\t\t\t= val\r\n\r\n return orig_state_dict\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t__lowerCamelCase\t\t\t\t( A__ ) ->\tOptional[Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n if num_frames == 8:\r\n UpperCamelCase\t\t\t\t\t= 'eating_spaghetti_8_frames.npy'\r\n elif num_frames == 16:\r\n UpperCamelCase\t\t\t\t\t= 'eating_spaghetti.npy'\r\n elif num_frames == 32:\r\n UpperCamelCase\t\t\t\t\t= 'eating_spaghetti_32_frames.npy'\r\n UpperCamelCase\t\t\t\t\t= hf_hub_download(\r\n repo_id='hf-internal-testing/spaghetti-video' ,\t\t\t\t\t\tfilename=A__ ,\t\t\t\t\t\trepo_type='dataset' ,\t\t\t\t\t\t)\r\n UpperCamelCase\t\t\t\t\t= np.load(A__ )\r\n return list(A__ )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t__lowerCamelCase\t\t\t\t( A__ ,\t\t\t\t\t\tA__=None ,\t\t\t\t\t\tA__=False ) ->\tList[Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n UpperCamelCase\t\t\t\t\t= {\r\n # fully supervised kinetics-400 checkpoints\r\n 'xclip-base-patch32': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth',\r\n 'xclip-base-patch32-16-frames': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth'\r\n ),\r\n 'xclip-base-patch16': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth',\r\n 'xclip-base-patch16-16-frames': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth'\r\n ),\r\n 'xclip-large-patch14': 'https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&export=download&confirm=t&uuid=b26caedc-88e2-473e-830a-9d158b653cdb',\r\n 'xclip-large-patch14-16-frames': 'https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&export=download&confirm=t&uuid=538fa810-e671-4050-b385-9a623f89804f',\r\n # fully supervised kinetics-600 checkpoints\r\n 'xclip-base-patch16-kinetics-600': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth'\r\n ),\r\n 'xclip-base-patch16-kinetics-600-16-frames': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth'\r\n ),\r\n 'xclip-large-patch14-kinetics-600': 'https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&export=download&confirm=t&uuid=141d4977-4a65-44ae-864f-4b0c19f838be',\r\n # few shot\r\n 'xclip-base-patch16-hmdb-2-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth'\r\n ),\r\n 'xclip-base-patch16-hmdb-4-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth'\r\n ),\r\n 'xclip-base-patch16-hmdb-8-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth'\r\n ),\r\n 'xclip-base-patch16-hmdb-16-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth'\r\n ),\r\n 'xclip-base-patch16-ucf-2-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth'\r\n ),\r\n 'xclip-base-patch16-ucf-4-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth'\r\n ),\r\n 'xclip-base-patch16-ucf-8-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth'\r\n ),\r\n 'xclip-base-patch16-ucf-16-shot': (\r\n 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth'\r\n ),\r\n # zero shot\r\n 'xclip-base-patch16-zero-shot': 'https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth',\r\n }\r\n\r\n UpperCamelCase\t\t\t\t\t= model_to_url[model_name]\r\n UpperCamelCase\t\t\t\t\t= 8\r\n if \"16-frames\" in model_name:\r\n UpperCamelCase\t\t\t\t\t= 16\r\n elif \"shot\" in model_name:\r\n UpperCamelCase\t\t\t\t\t= 32\r\n\r\n UpperCamelCase\t\t\t\t\t= get_xclip_config(A__ ,\t\t\t\t\t\tA__ )\r\n UpperCamelCase\t\t\t\t\t= XCLIPModel(A__ )\r\n model.eval()\r\n\r\n if \"drive\" in checkpoint_url:\r\n UpperCamelCase\t\t\t\t\t= 'pytorch_model.bin'\r\n gdown.cached_download(A__ ,\t\t\t\t\t\tA__ ,\t\t\t\t\t\tquiet=A__ )\r\n UpperCamelCase\t\t\t\t\t= torch.load(A__ ,\t\t\t\t\t\tmap_location='cpu' )['model']\r\n else:\r\n UpperCamelCase\t\t\t\t\t= torch.hub.load_state_dict_from_url(A__ )['model']\r\n\r\n UpperCamelCase\t\t\t\t\t= convert_state_dict(A__ ,\t\t\t\t\t\tA__ )\r\n\r\n UpperCamelCase\t\t\t\t\t= XCLIPModel(A__ )\r\n UpperCamelCase\t\t\t\t, UpperCamelCase\t\t\t\t\t= model.load_state_dict(A__ ,\t\t\t\t\t\tstrict=A__ )\r\n assert missing_keys == [\"text_model.embeddings.position_ids\", \"vision_model.embeddings.position_ids\"]\r\n model.eval()\r\n\r\n UpperCamelCase\t\t\t\t\t= 336 if model_name == 'xclip-large-patch14-16-frames' else 224\r\n UpperCamelCase\t\t\t\t\t= VideoMAEImageProcessor(size=A__ )\r\n UpperCamelCase\t\t\t\t\t= CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32' )\r\n UpperCamelCase\t\t\t\t\t= CLIPTokenizerFast.from_pretrained('openai/clip-vit-base-patch32' )\r\n UpperCamelCase\t\t\t\t\t= XCLIPProcessor(image_processor=A__ ,\t\t\t\t\t\ttokenizer=A__ )\r\n\r\n UpperCamelCase\t\t\t\t\t= prepare_video(A__ )\r\n UpperCamelCase\t\t\t\t\t= processor(\r\n text=['playing sports', 'eating spaghetti', 'go shopping'] ,\t\t\t\t\t\tvideos=A__ ,\t\t\t\t\t\treturn_tensors='pt' ,\t\t\t\t\t\tpadding=A__ )\r\n\r\n print('Shape of pixel values:' ,\t\t\t\t\t\tinputs.pixel_values.shape )\r\n\r\n with torch.no_grad():\r\n UpperCamelCase\t\t\t\t\t= model(**A__ )\r\n\r\n # Verify outputs\r\n UpperCamelCase\t\t\t\t\t= outputs.logits_per_video\r\n UpperCamelCase\t\t\t\t\t= logits_per_video.softmax(dim=1 )\r\n print('Probs:' ,\t\t\t\t\t\tA__ )\r\n # kinetics-400\r\n if model_name == \"xclip-base-patch32\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[0.0_019, 0.9_951, 0.0_030]] )\r\n elif model_name == \"xclip-base-patch32-16-frames\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[7.0_9_9_9e-0_4, 9.9_8_8_3e-0_1, 4.5_5_8_0e-0_4]] )\r\n elif model_name == \"xclip-base-patch16\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[0.0_083, 0.9_681, 0.0_236]] )\r\n elif model_name == \"xclip-base-patch16-16-frames\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[7.6_9_3_7e-0_4, 9.9_7_2_8e-0_1, 1.9_4_7_3e-0_3]] )\r\n elif model_name == \"xclip-large-patch14\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[0.0_062, 0.9_864, 0.0_075]] )\r\n elif model_name == \"xclip-large-patch14-16-frames\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[3.3_8_7_7e-0_4, 9.9_9_3_7e-0_1, 2.8_8_8_8e-0_4]] )\r\n # kinetics-600\r\n elif model_name == \"xclip-base-patch16-kinetics-600\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[0.0_555, 0.8_914, 0.0_531]] )\r\n elif model_name == \"xclip-base-patch16-kinetics-600-16-frames\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[3.8_5_5_4e-0_4, 9.9_9_2_9e-0_1, 3.2_7_5_4e-0_4]] )\r\n elif model_name == \"xclip-large-patch14-kinetics-600\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[0.0_036, 0.9_920, 0.0_045]] )\r\n # few shot\r\n elif model_name == \"xclip-base-patch16-hmdb-2-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[7.1_8_9_0e-0_6, 9.9_9_9_4e-0_1, 5.6_5_5_9e-0_5]] )\r\n elif model_name == \"xclip-base-patch16-hmdb-4-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[1.0_3_2_0e-0_5, 9.9_9_9_3e-0_1, 6.2_4_3_5e-0_5]] )\r\n elif model_name == \"xclip-base-patch16-hmdb-8-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[4.1_3_7_7e-0_6, 9.9_9_9_0e-0_1, 9.8_3_8_6e-0_5]] )\r\n elif model_name == \"xclip-base-patch16-hmdb-16-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[4.1_3_4_7e-0_5, 9.9_9_6_2e-0_1, 3.3_4_1_1e-0_4]] )\r\n elif model_name == \"xclip-base-patch16-ucf-2-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]] )\r\n elif model_name == \"xclip-base-patch16-ucf-4-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[8.5_8_5_7e-0_5, 9.9_9_2_8e-0_1, 6.3_2_9_1e-0_4]] )\r\n elif model_name == \"xclip-base-patch16-ucf-8-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[0.0_027, 0.9_904, 0.0_070]] )\r\n elif model_name == \"xclip-base-patch16-ucf-16-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[9.8_2_1_9e-0_4, 9.9_5_9_3e-0_1, 3.0_8_6_3e-0_3]] )\r\n # zero shot\r\n elif model_name == \"xclip-base-patch16-zero-shot\":\r\n UpperCamelCase\t\t\t\t\t= torch.tensor([[3.5_0_8_2e-0_4, 9.9_7_8_5e-0_1, 1.7_9_6_6e-0_3]] )\r\n else:\r\n raise ValueError(F\"\"\"Model name {model_name} not supported\"\"\" )\r\n assert torch.allclose(A__ ,\t\t\t\t\t\tA__ ,\t\t\t\t\t\tatol=1e-3 )\r\n print('Looks ok!' )\r\n\r\n if pytorch_dump_folder_path is not None:\r\n print(F\"\"\"Saving model {model_name} to {pytorch_dump_folder_path}\"\"\" )\r\n model.save_pretrained(A__ )\r\n\r\n if push_to_hub:\r\n print('Pushing model, processor and slow tokenizer files to the hub...' )\r\n model.push_to_hub(A__ ,\t\t\t\t\t\torganization='nielsr' )\r\n processor.push_to_hub(A__ ,\t\t\t\t\t\torganization='nielsr' )\r\n slow_tokenizer.push_to_hub(A__ ,\t\t\t\t\t\torganization='nielsr' )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n _lowerCamelCase\t: Union[str, Any] \t=\targparse.ArgumentParser()\r\n # Required parameters\r\n parser.add_argument(\r\n \"--model_name\",\r\n default=\"xclip-base-patch32\",\r\n type=str,\r\n help=\"Name of the model.\",\r\n )\r\n parser.add_argument(\r\n \"--pytorch_dump_folder_path\", default=None, type=str, help=\"Path to the output PyTorch model directory.\"\r\n )\r\n parser.add_argument(\r\n \"--push_to_hub\", action=\"store_true\", help=\"Whether or not to push the converted model to the 🤗 hub.\"\r\n )\r\n\r\n _lowerCamelCase\t: str \t=\tparser.parse_args()\r\n convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)\r\n\r\n"},"code_codestyle":{"kind":"number","value":28,"string":"28"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n'''simple docstring'''\r\n\r\n\r\nfrom typing import Optional, Tuple\r\n\r\nimport jax\r\nimport jax.numpy as jnp\r\nfrom flax import linen as nn\r\nfrom flax.core.frozen_dict import FrozenDict\r\nfrom transformers import CLIPConfig, FlaxPreTrainedModel\r\nfrom transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef \t\t\t\t__lowerCamelCase\t\t\t\t( A__ ,\t\t\t\t\t\tA__ ,\t\t\t\t\t\tA__=1e-1_2 ) ->\tDict:\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n UpperCamelCase\t\t\t\t\t= jnp.divide(emb_a.T ,\t\t\t\t\t\tjnp.clip(jnp.linalg.norm(A__ ,\t\t\t\t\t\taxis=1 ) ,\t\t\t\t\t\ta_min=A__ ) ).T\r\n UpperCamelCase\t\t\t\t\t= jnp.divide(emb_a.T ,\t\t\t\t\t\tjnp.clip(jnp.linalg.norm(A__ ,\t\t\t\t\t\taxis=1 ) ,\t\t\t\t\t\ta_min=A__ ) ).T\r\n return jnp.matmul(A__ ,\t\t\t\t\t\tnorm_emb_a.T )\r\n\r\nclass SCREAMING_SNAKE_CASE ( nn.Module\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n _SCREAMING_SNAKE_CASE\t = 42\r\n _SCREAMING_SNAKE_CASE\t = jnp.floataa\r\n\r\n\r\n\r\n\r\n\r\n\r\n def A ( self :\t\t\t\t\tList[Any] ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n UpperCamelCase\t\t\t\t\t= FlaxCLIPVisionModule(self.config.vision_config )\r\n UpperCamelCase\t\t\t\t\t= nn.Dense(self.config.projection_dim ,\t\t\t\t\t\tuse_bias=UpperCamelCase__ ,\t\t\t\t\t\tdtype=self.dtype )\r\n\r\n UpperCamelCase\t\t\t\t\t= self.param('concept_embeds' ,\t\t\t\t\t\tjax.nn.initializers.ones ,\t\t\t\t\t\t(1_7, self.config.projection_dim) )\r\n UpperCamelCase\t\t\t\t\t= self.param(\r\n 'special_care_embeds' ,\t\t\t\t\t\tjax.nn.initializers.ones ,\t\t\t\t\t\t(3, self.config.projection_dim) )\r\n\r\n UpperCamelCase\t\t\t\t\t= self.param('concept_embeds_weights' ,\t\t\t\t\t\tjax.nn.initializers.ones ,\t\t\t\t\t\t(1_7,) )\r\n UpperCamelCase\t\t\t\t\t= self.param('special_care_embeds_weights' ,\t\t\t\t\t\tjax.nn.initializers.ones ,\t\t\t\t\t\t(3,) )\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __call__( self :\t\t\t\t\tstr ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tList[str] ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n UpperCamelCase\t\t\t\t\t= self.vision_model(UpperCamelCase__ )[1]\r\n UpperCamelCase\t\t\t\t\t= self.visual_projection(UpperCamelCase__ )\r\n\r\n UpperCamelCase\t\t\t\t\t= jax_cosine_distance(UpperCamelCase__ ,\t\t\t\t\t\tself.special_care_embeds )\r\n UpperCamelCase\t\t\t\t\t= jax_cosine_distance(UpperCamelCase__ ,\t\t\t\t\t\tself.concept_embeds )\r\n\r\n # increase this value to create a stronger `nfsw` filter\r\n # at the cost of increasing the possibility of filtering benign image inputs\r\n UpperCamelCase\t\t\t\t\t= 0.0\r\n\r\n UpperCamelCase\t\t\t\t\t= special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment\r\n UpperCamelCase\t\t\t\t\t= jnp.round(UpperCamelCase__ ,\t\t\t\t\t\t3 )\r\n UpperCamelCase\t\t\t\t\t= jnp.any(special_scores > 0 ,\t\t\t\t\t\taxis=1 ,\t\t\t\t\t\tkeepdims=UpperCamelCase__ )\r\n # Use a lower threshold if an image has any special care concept\r\n UpperCamelCase\t\t\t\t\t= is_special_care * 0.0_1\r\n\r\n UpperCamelCase\t\t\t\t\t= cos_dist - self.concept_embeds_weights[None, :] + special_adjustment\r\n UpperCamelCase\t\t\t\t\t= jnp.round(UpperCamelCase__ ,\t\t\t\t\t\t3 )\r\n UpperCamelCase\t\t\t\t\t= jnp.any(concept_scores > 0 ,\t\t\t\t\t\taxis=1 )\r\n\r\n return has_nsfw_concepts\r\n\r\nclass SCREAMING_SNAKE_CASE ( _a\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n _SCREAMING_SNAKE_CASE\t = CLIPConfig\r\n _SCREAMING_SNAKE_CASE\t = \"\"\"clip_input\"\"\"\r\n _SCREAMING_SNAKE_CASE\t = FlaxStableDiffusionSafetyCheckerModule\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __init__( self :\t\t\t\t\tUnion[str, Any] ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tCLIPConfig ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tOptional[Tuple] = None ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tint = 0 ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tjnp.dtype = jnp.floataa ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tbool = True ,\t\t\t\t\t\t**UpperCamelCase__ :\t\t\t\t\tList[str] ,\t\t\t\t\t\t):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n if input_shape is None:\r\n UpperCamelCase\t\t\t\t\t= (1, 2_2_4, 2_2_4, 3)\r\n UpperCamelCase\t\t\t\t\t= self.module_class(config=UpperCamelCase__ ,\t\t\t\t\t\tdtype=UpperCamelCase__ ,\t\t\t\t\t\t**UpperCamelCase__ )\r\n super().__init__(UpperCamelCase__ ,\t\t\t\t\t\tUpperCamelCase__ ,\t\t\t\t\t\tinput_shape=UpperCamelCase__ ,\t\t\t\t\t\tseed=UpperCamelCase__ ,\t\t\t\t\t\tdtype=UpperCamelCase__ ,\t\t\t\t\t\t_do_init=_do_init )\r\n\r\n\r\n\r\n\r\n\r\n\r\n def A ( self :\t\t\t\t\tint ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tjax.random.KeyArray ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tTuple ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tFrozenDict = None ):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n UpperCamelCase\t\t\t\t\t= jax.random.normal(UpperCamelCase__ ,\t\t\t\t\t\tUpperCamelCase__ )\r\n\r\n UpperCamelCase\t\t\t\t, UpperCamelCase\t\t\t\t\t= jax.random.split(UpperCamelCase__ )\r\n UpperCamelCase\t\t\t\t\t= {'params': params_rng, 'dropout': dropout_rng}\r\n\r\n UpperCamelCase\t\t\t\t\t= self.module.init(UpperCamelCase__ ,\t\t\t\t\t\tUpperCamelCase__ )['params']\r\n\r\n return random_params\r\n\r\n\r\n\r\n\r\n\r\n\r\n def __call__( self :\t\t\t\t\tList[Any] ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tDict ,\t\t\t\t\t\tUpperCamelCase__ :\t\t\t\t\tdict = None ,\t\t\t\t\t\t):\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n UpperCamelCase\t\t\t\t\t= jnp.transpose(UpperCamelCase__ ,\t\t\t\t\t\t(0, 2, 3, 1) )\r\n\r\n return self.module.apply(\r\n {'params': params or self.params} ,\t\t\t\t\t\tjnp.array(UpperCamelCase__ ,\t\t\t\t\t\tdtype=jnp.floataa ) ,\t\t\t\t\t\trngs={} ,\t\t\t\t\t\t)\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":28,"string":"28"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":271,"cells":{"code":{"kind":"string","value":"\r\r\r\r\r\rfrom __future__ import annotations\r\rfrom math import pi\r\r\r\r\r\r\rdef \t_SCREAMING_SNAKE_CASE\t\t( SCREAMING_SNAKE_CASE\t\t:float , SCREAMING_SNAKE_CASE\t\t:float , SCREAMING_SNAKE_CASE\t\t:float ) -> dict[str, float]:\r\r if (inductance, frequency, reactance).count(0 ) != 1:\r raise ValueError(\"\"\"One and only one argument must be 0\"\"\" )\r if inductance < 0:\r raise ValueError(\"\"\"Inductance cannot be negative\"\"\" )\r if frequency < 0:\r raise ValueError(\"\"\"Frequency cannot be negative\"\"\" )\r if reactance < 0:\r raise ValueError(\"\"\"Inductive reactance cannot be negative\"\"\" )\r if inductance == 0:\r return {\"inductance\": reactance / (2 * pi * frequency)}\r elif frequency == 0:\r return {\"frequency\": reactance / (2 * pi * inductance)}\r elif reactance == 0:\r return {\"reactance\": 2 * pi * frequency * inductance}\r else:\r raise ValueError(\"\"\"Exactly one argument must be 0\"\"\" )\r\r\rif __name__ == \"__main__\":\r import doctest\r\r doctest.testmod()"},"code_codestyle":{"kind":"number","value":232,"string":"232"},"style_context":{"kind":"string","value":"\r\r\r\r\r\rfrom math import isqrt\r\r\r\r\r\r\rdef \t_SCREAMING_SNAKE_CASE\t\t( SCREAMING_SNAKE_CASE\t\t:int ) -> list[int]:\r __lowerCAmelCase\t\t\t\t\t:\tTuple = [True] * max_number\r for i in range(2 , isqrt(max_number - 1 ) + 1 ):\r if is_prime[i]:\r for j in range(i**2 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):\r __lowerCAmelCase\t\t\t\t\t:\tTuple = False\r\r return [i for i in range(2 , SCREAMING_SNAKE_CASE ) if is_prime[i]]\r\r\r\r\r\r\rdef \t_SCREAMING_SNAKE_CASE\t\t( SCREAMING_SNAKE_CASE\t\t:int = 10**8 ) -> int:\r __lowerCAmelCase\t\t\t\t\t:\tint = calculate_prime_numbers(max_number // 2 )\r\r __lowerCAmelCase\t\t\t\t\t:\tList[Any] = 0\r __lowerCAmelCase\t\t\t\t\t:\tList[str] = 0\r __lowerCAmelCase\t\t\t\t\t:\tList[Any] = len(SCREAMING_SNAKE_CASE ) - 1\r while left <= right:\r while prime_numbers[left] * prime_numbers[right] >= max_number:\r right -= 1\r semiprimes_count += right - left + 1\r left += 1\r\r return semiprimes_count\r\r\rif __name__ == \"__main__\":\r print(f'''{solution() = }''')"},"style_context_codestyle":{"kind":"number","value":232,"string":"232"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":272,"cells":{"code":{"kind":"string","value":"\r\r\r'''simple docstring'''\r\r\r\r\r\r\r\rimport copy\r\rfrom ...configuration_utils import PretrainedConfig\rfrom ...utils import logging\rfrom ..auto import CONFIG_MAPPING\r\r\ra__ :\t\t\t\t\tList[str] = logging.get_logger(__name__)\r\ra__ :\t\t\t\t\tOptional[int] = {\r 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json',\r}\rclass \t\t\t\t\tlowercase_ ( a__ ):\r __UpperCAmelCase \t\t\t=\t'deta'\r __UpperCAmelCase \t\t\t=\t{\r 'hidden_size': 'd_model',\r 'num_attention_heads': 'encoder_attention_heads',\r }\r\r\r def __init__( self ,\t\t\t\t\ta=None ,\t\t\t\t\ta=9_00 ,\t\t\t\t\ta=20_48 ,\t\t\t\t\ta=6 ,\t\t\t\t\ta=20_48 ,\t\t\t\t\ta=8 ,\t\t\t\t\ta=6 ,\t\t\t\t\ta=10_24 ,\t\t\t\t\ta=8 ,\t\t\t\t\ta=0.0 ,\t\t\t\t\ta=True ,\t\t\t\t\ta=\"relu\" ,\t\t\t\t\ta=2_56 ,\t\t\t\t\ta=0.1 ,\t\t\t\t\ta=0.0 ,\t\t\t\t\ta=0.0 ,\t\t\t\t\ta=0.02 ,\t\t\t\t\ta=1.0 ,\t\t\t\t\ta=True ,\t\t\t\t\ta=False ,\t\t\t\t\ta=\"sine\" ,\t\t\t\t\ta=5 ,\t\t\t\t\ta=4 ,\t\t\t\t\ta=4 ,\t\t\t\t\ta=True ,\t\t\t\t\ta=3_00 ,\t\t\t\t\ta=True ,\t\t\t\t\ta=True ,\t\t\t\t\ta=1 ,\t\t\t\t\ta=5 ,\t\t\t\t\ta=2 ,\t\t\t\t\ta=1 ,\t\t\t\t\ta=1 ,\t\t\t\t\ta=5 ,\t\t\t\t\ta=2 ,\t\t\t\t\ta=0.1 ,\t\t\t\t\ta=0.25 ,\t\t\t\t\t**a ,\t\t\t\t\t):\r if backbone_config is None:\r logger.info(\"`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.\" )\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tCONFIG_MAPPING[\"resnet\"](out_features=[\"stage2\", \"stage3\", \"stage4\"] )\r else:\r if isinstance(a ,\t\t\t\t\ta ):\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tbackbone_config.pop(\"model_type\" )\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tCONFIG_MAPPING[backbone_model_type]\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tconfig_class.from_dict(a )\r\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tbackbone_config\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tnum_queries\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tmax_position_embeddings\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\td_model\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tencoder_ffn_dim\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tencoder_layers\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tencoder_attention_heads\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tdecoder_ffn_dim\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tdecoder_layers\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tdecoder_attention_heads\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tdropout\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tattention_dropout\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tactivation_dropout\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tactivation_function\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tinit_std\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tinit_xavier_std\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tencoder_layerdrop\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tauxiliary_loss\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tposition_embedding_type\r # deformable attributes\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tnum_feature_levels\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tencoder_n_points\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tdecoder_n_points\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\ttwo_stage\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\ttwo_stage_num_proposals\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\twith_box_refine\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tassign_first_stage\r if two_stage is True and with_box_refine is False:\r raise ValueError(\"If two_stage is True, with_box_refine must be True.\" )\r # Hungarian matcher\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tclass_cost\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tbbox_cost\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tgiou_cost\r # Loss coefficients\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tmask_loss_coefficient\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tdice_loss_coefficient\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tbbox_loss_coefficient\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tgiou_loss_coefficient\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\teos_coefficient\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tfocal_alpha\r super().__init__(is_encoder_decoder=a ,\t\t\t\t\t**a )\r\r\r @property\r def __a\t\t\t\t\t\t\t( self ):\r return self.encoder_attention_heads\r\r\r @property\r def __a\t\t\t\t\t\t\t( self ):\r return self.d_model\r\r\r def __a\t\t\t\t\t\t\t( self ):\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tcopy.deepcopy(self.__dict__ )\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tself.backbone_config.to_dict()\r UpperCamelCase__\t\t\t\t\t\t\t\t\t\t=\t\t\t\tself.__class__.model_type\r return output\r\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":80,"string":"80"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\nimport json\r\nimport multiprocessing as mp\r\nimport re\r\nfrom collections import defaultdict\r\nfrom functools import partial\r\nfrom typing import Dict, List, Optional, Set, Tuple, Type\r\n\r\nfrom datasets import Dataset\r\nfrom datasketch import MinHash, MinHashLSH\r\nfrom dpu_utils.utils.iterators import ThreadedIterator\r\nfrom tqdm import tqdm\r\n\r\n\r\nlowercase_\t\t\t = re.compile(\"[^A-Za-z_0-9]\")\r\n# parameters used in DuplicationIndex\r\nlowercase_\t\t\t = 1_0\r\nlowercase_\t\t\t = 2_5_6\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : List[str]\t\t\t) -> Optional[MinHash]:\r\n\t\tif len(lowerCAmelCase__\t\t\t) < MIN_NUM_TOKENS:\r\n\t\t\t\treturn None\r\n\t\t__a =\t\t\tMinHash(num_perm=lowerCAmelCase__\t\t\t)\r\n\t\tfor token in set(lowerCAmelCase__\t\t\t):\r\n\t\t\t\tmin_hash.update(token.encode()\t\t\t)\r\n\t\treturn min_hash\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : str\t\t\t) -> Set[str]:\r\n\t\treturn {t for t in NON_ALPHA.split(lowerCAmelCase__\t\t\t) if len(t.strip()\t\t\t) > 0}\r\nclass \t\t\t\t\t__lowerCAmelCase\t\t\t\t\t:\r\n\r\n\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\tdef __init__( self\t\t\t\t\t\t\t, *,\r\n\t\t _a = 0.85\t\t\t\t\t\t\t, ):\r\n\t\t\t\t__a =\t\t\tduplication_jaccard_threshold\r\n\t\t\t\t__a =\t\t\tNUM_PERM\r\n\t\t\t\t__a =\t\t\tMinHashLSH(threshold=self._duplication_jaccard_threshold\t\t\t\t\t\t\t, num_perm=self._num_perm )\r\n\r\n\t\t\t\t__a =\t\t\tdefaultdict(_a )\r\n\r\n\t\tdef \t\t\t__UpperCAmelCase ( self\t\t\t\t\t\t\t, _a\t\t\t\t\t\t\t, _a ):\r\n\t\t\t\t__a =\t\t\tself._index.query(_a )\r\n\t\t\t\tif code_key in self._index.keys:\r\n\t\t\t\t\t\tprint(f'''Duplicate key {code_key}''' )\r\n\t\t\t\t\t\treturn\r\n\r\n\t\t\t\tself._index.insert(_a\t\t\t\t\t\t\t, _a )\r\n\t\t\t\tif len(_a ) > 0:\r\n\t\t\t\t\t\tfor base_duplicate in close_duplicates:\r\n\t\t\t\t\t\t\t\tif base_duplicate in self._duplicate_clusters:\r\n\t\t\t\t\t\t\t\t\t\tself._duplicate_clusters[base_duplicate].add(_a )\r\n\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tself._duplicate_clusters[close_duplicates[0]].add(_a )\r\n\r\n\t\tdef \t\t\t__UpperCAmelCase ( self ):\r\n\t\t\t\t__a =\t\t\t[]\r\n\t\t\t\tfor base, duplicates in self._duplicate_clusters.items():\r\n\t\t\t\t\t\t__a =\t\t\t[base] + list(_a )\r\n\t\t\t\t\t\t# reformat the cluster to be a list of dict\r\n\t\t\t\t\t\t__a =\t\t\t[{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster]\r\n\t\t\t\t\t\tduplicate_clusters.append(_a )\r\n\t\t\t\treturn duplicate_clusters\r\n\r\n\r\n\r\n\r\n\r\n\t\tdef \t\t\t__UpperCAmelCase ( self\t\t\t\t\t\t\t, _a ):\r\n\t\t\t\t__a =\t\t\tself.get_duplicate_clusters()\r\n\t\t\t\twith open(_a\t\t\t\t\t\t\t, '''w''' ) as f:\r\n\t\t\t\t\t\tjson.dump(_a\t\t\t\t\t\t\t, _a )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : List[str]\t\t\t) -> int:\r\n\t\t__a , __a =\t\t\telement\r\n\t\t__a =\t\t\tget_min_hash([t for t in NON_ALPHA.split(data['''content''']\t\t\t) if len(t.strip()\t\t\t) > 0]\t\t\t)\r\n\t\tif min_hash is not None:\r\n\t\t\t\treturn (index, data[\"repo_name\"], data[\"path\"]), min_hash\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : Type[Dataset]\t\t\t) -> str:\r\n\t\twith mp.Pool() as pool:\r\n\t\t\t\tfor data in pool.imap_unordered(\r\n\t\t\t\t _compute_min_hash ,\t\t\t\t\tThreadedIterator(lowerCAmelCase__ ,\t\t\t\t\tmax_queue_size=10000\t\t\t) ,\t\t\t\t\tchunksize=100 ,\t\t\t\t\t):\r\n\t\t\t\t\t\tif data is not None:\r\n\t\t\t\t\t\t\t\tyield data\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : Type[Dataset] ,\t\t\t\t\tlowerCAmelCase__ : float\t\t\t) -> Dict:\r\n\t\t__a =\t\t\tDuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase__\t\t\t)\r\n\r\n\t\tfor filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase__\t\t\t)\t\t\t) ,\t\t\t\t\tmax_queue_size=100\t\t\t)\t\t\t):\r\n\t\t\t\tdi.add(lowerCAmelCase__ ,\t\t\t\t\tlowerCAmelCase__\t\t\t)\r\n\r\n\t\t# Returns a List[Cluster] where Cluster is List[str] with the filenames.\r\n\t\treturn di.get_duplicate_clusters()\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : str ,\t\t\t\t\tlowerCAmelCase__ : str\t\t\t) -> float:\r\n\t\t__a =\t\t\tget_tokens(lowerCAmelCase__\t\t\t)\r\n\t\t__a =\t\t\tget_tokens(lowerCAmelCase__\t\t\t)\r\n\t\treturn len(tokensa & tokensa\t\t\t) / len(tokensa | tokensa\t\t\t)\r\n\r\n\r\nlowercase_\t\t\t = None\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : Optional[Any] ,\t\t\t\t\tlowerCAmelCase__ : Union[str, Any]\t\t\t) -> Any:\r\n\t\t__a =\t\t\t[]\r\n\t\tfor elementa in cluster:\r\n\t\t\t\t__a =\t\t\t_shared_dataset[elementa['''base_index''']]['''content''']\r\n\t\t\t\tfor elementa in extremes:\r\n\t\t\t\t\t\t__a =\t\t\t_shared_dataset[elementa['''base_index''']]['''content''']\r\n\t\t\t\t\t\tif jaccard_similarity(lowerCAmelCase__ ,\t\t\t\t\tlowerCAmelCase__\t\t\t) >= jaccard_threshold:\r\n\t\t\t\t\t\t\t\telementa[\"copies\"] += 1\r\n\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\telse:\r\n\t\t\t\t\t\t__a =\t\t\t1\r\n\t\t\t\t\t\textremes.append(lowerCAmelCase__\t\t\t)\r\n\t\treturn extremes\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : Union[str, Any] ,\t\t\t\t\tlowerCAmelCase__ : Optional[Any] ,\t\t\t\t\tlowerCAmelCase__ : Optional[int]\t\t\t) -> Optional[int]:\r\n\t\tglobal _shared_dataset\r\n\t\t__a =\t\t\tdataset\r\n\t\t__a =\t\t\t[]\r\n\t\t__a =\t\t\tpartial(_find_cluster_extremes_shared ,\t\t\t\t\tjaccard_threshold=lowerCAmelCase__\t\t\t)\r\n\t\twith mp.Pool() as pool:\r\n\t\t\t\tfor extremes in tqdm(\r\n\t\t\t\t pool.imap_unordered(\r\n\t\t\t\t lowerCAmelCase__ ,\t\t\t\t\tlowerCAmelCase__ ,\t\t\t\t\t) ,\t\t\t\t\ttotal=len(lowerCAmelCase__\t\t\t) ,\t\t\t\t\t):\r\n\t\t\t\t\t\textremes_list.append(lowerCAmelCase__\t\t\t)\r\n\t\treturn extremes_list\r\n\r\n\r\n\r\n\r\ndef lowercase\t\t\t\t\t\t\t(\t\tlowerCAmelCase__ : Type[Dataset] ,\t\t\t\t\tlowerCAmelCase__ : float = 0.85\t\t\t) -> Tuple[Type[Dataset], List[List[Dict]]]:\r\n\t\t__a =\t\t\tmake_duplicate_clusters(lowerCAmelCase__ ,\t\t\t\t\tlowerCAmelCase__\t\t\t)\r\n\t\t__a =\t\t\t{x['''base_index'''] for cluster in duplicate_clusters for x in cluster}\r\n\t\t__a =\t\t\t{}\r\n\t\t__a =\t\t\tfind_extremes(lowerCAmelCase__ ,\t\t\t\t\tlowerCAmelCase__ ,\t\t\t\t\tlowerCAmelCase__\t\t\t)\r\n\t\tfor extremes in extremes_clusters:\r\n\t\t\t\tfor element in extremes:\r\n\t\t\t\t\t\t__a =\t\t\telement\r\n\t\t__a =\t\t\tduplicate_indices - set(extreme_dict.keys()\t\t\t)\r\n\t\t__a =\t\t\tdataset.filter(lambda lowerCAmelCase__ ,\t\t\t\t\tlowerCAmelCase__\t\t\t: idx not in remove_indices ,\t\t\t\t\twith_indices=lowerCAmelCase__\t\t\t)\r\n\r\n\t\t# update duplicate_clusters\r\n\t\tfor cluster in duplicate_clusters:\r\n\t\t\t\tfor element in cluster:\r\n\t\t\t\t\t\t__a =\t\t\telement['''base_index'''] in extreme_dict\r\n\t\t\t\t\t\tif element[\"is_extreme\"]:\r\n\t\t\t\t\t\t\t\t__a =\t\t\textreme_dict[element['''base_index''']]['''copies''']\r\n\r\n\t\tprint(f'''Original dataset size: {len(lowerCAmelCase__\t\t\t)}'''\t\t\t)\r\n\t\tprint(f'''Number of duplicate clusters: {len(lowerCAmelCase__\t\t\t)}'''\t\t\t)\r\n\t\tprint(f'''Files in duplicate cluster: {len(lowerCAmelCase__\t\t\t)}'''\t\t\t)\r\n\t\tprint(f'''Unique files in duplicate cluster: {len(lowerCAmelCase__\t\t\t)}'''\t\t\t)\r\n\t\tprint(f'''Filtered dataset size: {len(lowerCAmelCase__\t\t\t)}'''\t\t\t)\r\n\r\n\t\treturn ds_filter, duplicate_clusters\r\n\r\n\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":45,"string":"45"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":273,"cells":{"code":{"kind":"string","value":"\n\n\n\n\n\nimport argparse\nimport json\nimport os\n\nimport fairseq\nimport torch\nfrom fairseq.data import Dictionary\n\nfrom transformers import (\n WavaVecaConformerConfig,\n WavaVecaConformerForCTC,\n WavaVecaConformerForPreTraining,\n WavaVecaCTCTokenizer,\n WavaVecaFeatureExtractor,\n WavaVecaProcessor,\n logging,\n)\n\n\nlogging.set_verbosity_info()\nUpperCamelCase__ =\tlogging.get_logger(__name__)\n\nUpperCamelCase__ =\t{\n \"post_extract_proj\": \"feature_projection.projection\",\n \"encoder.pos_conv.0\": \"encoder.pos_conv_embed.conv\",\n \"self_attn.linear_k\": \"encoder.layers.*.self_attn.linear_k\",\n \"self_attn.linear_v\": \"encoder.layers.*.self_attn.linear_v\",\n \"self_attn.linear_q\": \"encoder.layers.*.self_attn.linear_q\",\n \"self_attn.pos_bias_u\": \"encoder.layers.*.self_attn.pos_bias_u\",\n \"self_attn.pos_bias_v\": \"encoder.layers.*.self_attn.pos_bias_v\",\n \"self_attn.linear_out\": \"encoder.layers.*.self_attn.linear_out\",\n \"self_attn.linear_pos\": \"encoder.layers.*.self_attn.linear_pos\",\n \"self_attn.rotary_emb\": \"encoder.embed_positions\",\n \"self_attn_layer_norm\": \"encoder.layers.*.self_attn_layer_norm\",\n \"conv_module.pointwise_conv1\": \"encoder.layers.*.conv_module.pointwise_conv1\",\n \"conv_module.pointwise_conv2\": \"encoder.layers.*.conv_module.pointwise_conv2\",\n \"conv_module.depthwise_conv\": \"encoder.layers.*.conv_module.depthwise_conv\",\n \"conv_module.batch_norm\": \"encoder.layers.*.conv_module.batch_norm\",\n \"conv_module.layer_norm\": \"encoder.layers.*.conv_module.layer_norm\",\n \"ffn1.w_1\": \"encoder.layers.*.ffn1.intermediate_dense\",\n \"ffn1.w_2\": \"encoder.layers.*.ffn1.output_dense\",\n \"ffn1.layer_norm\": \"encoder.layers.*.ffn1_layer_norm\",\n \"ffn2.w_1\": \"encoder.layers.*.ffn2.intermediate_dense\",\n \"ffn2.w_2\": \"encoder.layers.*.ffn2.output_dense\",\n \"ffn2.layer_norm\": \"encoder.layers.*.ffn2_layer_norm\",\n \"final_layer_norm\": \"encoder.layers.*.final_layer_norm\",\n \"encoder.layer_norm\": \"encoder.layer_norm\",\n \"w2v_model.layer_norm\": \"feature_projection.layer_norm\",\n \"quantizer.weight_proj\": \"quantizer.weight_proj\",\n \"quantizer.vars\": \"quantizer.codevectors\",\n \"project_q\": \"project_q\",\n \"final_proj\": \"project_hid\",\n \"w2v_encoder.proj\": \"lm_head\",\n \"mask_emb\": \"masked_spec_embed\",\n}\nUpperCamelCase__ =\t[\n \"lm_head\",\n \"quantizer.weight_proj\",\n \"quantizer.codevectors\",\n \"project_q\",\n \"project_hid\",\n]\n\n\n\n\n\ndef _UpperCamelCase (a__\t\t\t\t:Optional[Any]\t\t\t\t, a__\t\t\t\t:Dict\t\t\t\t, a__\t\t\t\t:str\t\t\t\t, a__\t\t\t\t:Optional[int]\t\t\t\t, a__\t\t\t\t:str ):\n\n\n\n\n\n\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\t\t\t\t\t\t\tfor attribute in key.split(\"\"\".\"\"\" ):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = getattr(a__\t\t\t\t, a__ )\n\n\t\t\t\t\t\t\tif weight_type is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = getattr(a__\t\t\t\t, a__ ).shape\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = hf_pointer.shape\n\n\t\t\t\t\t\t\tif hf_shape != value.shape:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"Shape of hf {key + \".\" + weight_type if weight_type is not None else \"\"} is {hf_shape}, but should be\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\" {value.shape} for {full_name}\"\"\" )\n\n\t\t\t\t\t\t\tif weight_type == \"weight\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telif weight_type == \"weight_g\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telif weight_type == \"weight_v\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telif weight_type == \"bias\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telif weight_type == \"running_mean\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telif weight_type == \"running_var\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telif weight_type == \"num_batches_tracked\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telif weight_type == \"inv_freq\":\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\n\t\t\t\t\t\t\tlogger.info(f\"\"\"{key + \".\" + weight_type if weight_type is not None else \"\"} was initialized from {full_name}.\"\"\" )\n\n\n\n\n\ndef _UpperCamelCase (a__\t\t\t\t:Tuple\t\t\t\t, a__\t\t\t\t:Union[str, Any]\t\t\t\t, a__\t\t\t\t:Any ):\n\n\n\n\n\n\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = []\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = fairseq_model.state_dict()\n\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = hf_model.wavaveca_conformer.feature_extractor\n\n\t\t\t\t\t\t\tfor name, value in fairseq_dict.items():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = False\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"conv_layers\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tload_conv_layer(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t a__\t\t\t\t, a__\t\t\t\t, a__\t\t\t\t, a__\t\t\t\t, hf_model.config.feat_extract_norm == \"\"\"group\"\"\"\t\t\t\t, )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = True\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key, mapped_key in MAPPING.items():\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"wav2vec2_conformer.\"\"\" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif key in name or key.split(\"\"\"w2v_model.\"\"\" )[-1] == name.split(\"\"\".\"\"\" )[0]:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = True\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"*\" in mapped_key:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = name.split(a__ )[0].split(\"\"\".\"\"\" )[-2]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = mapped_key.replace(\"\"\"*\"\"\"\t\t\t\t, a__ )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"pos_bias_u\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = None\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"pos_bias_v\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = None\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"weight_g\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"weight_g\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"weight_v\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"weight_v\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"bias\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"bias\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"weight\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# TODO: don't match quantizer.weight_proj\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"weight\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"running_mean\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"running_mean\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"inv_freq\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"inv_freq\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"running_var\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"running_var\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"num_batches_tracked\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"num_batches_tracked\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = None\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tset_recursively(a__\t\t\t\t, a__\t\t\t\t, a__\t\t\t\t, a__\t\t\t\t, a__ )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not is_used:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunused_weights.append(a__ )\n\n\t\t\t\t\t\t\tlogger.warning(f\"\"\"Unused weights: {unused_weights}\"\"\" )\n\n\n\n\n\ndef _UpperCamelCase (a__\t\t\t\t:Tuple\t\t\t\t, a__\t\t\t\t:Optional[int]\t\t\t\t, a__\t\t\t\t:Optional[Any]\t\t\t\t, a__\t\t\t\t:List[str]\t\t\t\t, a__\t\t\t\t:List[Any] ):\n\n\n\n\n\n\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = full_name.split(\"\"\"conv_layers.\"\"\" )[-1]\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = name.split(\"\"\".\"\"\" )\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = int(items[0] )\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = int(items[1] )\n\n\t\t\t\t\t\t\tif type_id == 0:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"bias\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"{full_name} has size {value.shape}, but\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(f\"\"\"Feat extract conv layer {layer_id} was initialized from {full_name}.\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"weight\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"{full_name} has size {value.shape}, but\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(f\"\"\"Feat extract conv layer {layer_id} was initialized from {full_name}.\"\"\" )\n\t\t\t\t\t\t\telif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif \"bias\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"{full_name} has size {value.shape}, but\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(f\"\"\"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telif \"weight\" in name:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"{full_name} has size {value.shape}, but\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = value\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(f\"\"\"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.\"\"\" )\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tunused_weights.append(a__ )\n\n\n\n\n\n@torch.no_grad()\ndef _UpperCamelCase (a__\t\t\t\t:List[str]\t\t\t\t, a__\t\t\t\t:Optional[int]\t\t\t\t, a__\t\t\t\t:Optional[Any]=None\t\t\t\t, a__\t\t\t\t:List[Any]=None\t\t\t\t, a__\t\t\t\t:Optional[Any]=True ):\n\n\n\n\n\n\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\t\t\t\t\t\t\tif config_path is not None:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = WavaVecaConformerConfig.from_pretrained(a__\t\t\t\t, hidden_act=\"\"\"swish\"\"\" )\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = WavaVecaConformerConfig()\n\n\t\t\t\t\t\t\tif \"rope\" in checkpoint_path:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = \"\"\"rotary\"\"\"\n\n\t\t\t\t\t\t\tif is_finetuned:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif dict_path:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = Dictionary.load(a__ )\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# important change bos & pad token id since CTC symbol is and\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# not as in fairseq\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = target_dict.pad_index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = target_dict.bos_index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = target_dict.eos_index\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = len(target_dict.symbols )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = os.path.join(a__\t\t\t\t, \"\"\"vocab.json\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not os.path.isdir(a__ ):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.error(\"\"\"--pytorch_dump_folder_path ({}) should be a directory\"\"\".format(a__ ) )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tos.makedirs(a__\t\t\t\t, exist_ok=a__ )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = target_dict.indices\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# fairseq has the and switched\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = 0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith open(a__\t\t\t\t, \"\"\"w\"\"\"\t\t\t\t, encoding=\"\"\"utf-8\"\"\" ) as vocab_handle:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjson.dump(a__\t\t\t\t, a__ )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = WavaVecaCTCTokenizer(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t a__\t\t\t\t, unk_token=target_dict.unk_word\t\t\t\t, pad_token=target_dict.pad_word\t\t\t\t, bos_token=target_dict.bos_word\t\t\t\t, eos_token=target_dict.eos_word\t\t\t\t, word_delimiter_token=\"\"\"|\"\"\"\t\t\t\t, do_lower_case=a__\t\t\t\t, )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = True if config.feat_extract_norm == \"\"\"layer\"\"\" else False\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = WavaVecaFeatureExtractor(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t feature_size=1\t\t\t\t, sampling_rate=1_6000\t\t\t\t, padding_value=0\t\t\t\t, do_normalize=a__\t\t\t\t, return_attention_mask=a__\t\t\t\t, )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = WavaVecaProcessor(feature_extractor=a__\t\t\t\t, tokenizer=a__ )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprocessor.save_pretrained(a__ )\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = WavaVecaConformerForCTC(a__ )\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = WavaVecaConformerForPreTraining(a__ )\n\n\t\t\t\t\t\t\tif is_finetuned:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__\t\t\t = fairseq.checkpoint_utils.load_model_ensemble_and_task(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t [checkpoint_path]\t\t\t\t, arg_overrides={\"\"\"data\"\"\": \"\"\"/\"\"\".join(dict_path.split(\"\"\"/\"\"\" )[:-1] )} )\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = argparse.Namespace(task=\"\"\"audio_pretraining\"\"\" )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = fairseq.tasks.setup_task(a__ )\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__\t\t\t = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]\t\t\t\t, task=a__ )\n\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = model[0].eval()\n\n\t\t\t\t\t\t\trecursively_load_weights(a__\t\t\t\t, a__\t\t\t\t, not is_finetuned )\n\n\t\t\t\t\t\t\thf_wavavec.save_pretrained(a__ )\n\n\nif __name__ == \"__main__\":\n\t\t\t\t\tUpperCamelCase__ =\targparse.ArgumentParser()\n\t\t\t\t\tparser.add_argument(\"--pytorch_dump_folder_path\", default=None, type=str, help=\"Path to the output PyTorch model.\")\n\t\t\t\t\tparser.add_argument(\"--checkpoint_path\", default=None, type=str, help=\"Path to fairseq checkpoint\")\n\t\t\t\t\tparser.add_argument(\"--dict_path\", default=None, type=str, help=\"Path to dict of fine-tuned model\")\n\t\t\t\t\tparser.add_argument(\"--config_path\", default=None, type=str, help=\"Path to hf config.json of model to convert\")\n\t\t\t\t\tparser.add_argument(\n\t\t\t\t\t \"--not_finetuned\", action=\"store_true\", help=\"Whether the model to convert is a fine-tuned model or not\"\n\t\t\t\t\t)\n\t\t\t\t\tUpperCamelCase__ =\tparser.parse_args()\n\t\t\t\t\tconvert_wavaveca_conformer_checkpoint(\n\t\t\t\t\t args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned\n\t\t\t\t\t)\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":87,"string":"87"},"style_context":{"kind":"string","value":"\n\n\n\n\n\nUpperCamelCase__ =\t{\n \"meter\": \"m\",\n \"kilometer\": \"km\",\n \"megametre\": \"Mm\",\n \"gigametre\": \"Gm\",\n \"terametre\": \"Tm\",\n \"petametre\": \"Pm\",\n \"exametre\": \"Em\",\n \"zettametre\": \"Zm\",\n \"yottametre\": \"Ym\",\n}\n# Exponent of the factor(meter)\nUpperCamelCase__ =\t{\n \"m\": 0,\n \"km\": 3,\n \"Mm\": 6,\n \"Gm\": 9,\n \"Tm\": 12,\n \"Pm\": 15,\n \"Em\": 18,\n \"Zm\": 21,\n \"Ym\": 24,\n}\n\n\n\n\n\ndef _UpperCamelCase (a__\t\t\t\t:float\t\t\t\t, a__\t\t\t\t:str\t\t\t\t, a__\t\t\t\t:str ):\n\n\n\n\n\n\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = from_type.lower().strip(\"\"\"s\"\"\" )\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = to_type.lower().strip(\"\"\"s\"\"\" )\n\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = UNIT_SYMBOL.get(a__\t\t\t\t, a__ )\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = UNIT_SYMBOL.get(a__\t\t\t\t, a__ )\n\n\t\t\t\t\t\t\tif from_sanitized not in METRIC_CONVERSION:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"Invalid 'from_type' value: {from_type!r}.\\n\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"Conversion abbreviations are: {\", \".join(a__ )}\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(a__ )\n\t\t\t\t\t\t\tif to_sanitized not in METRIC_CONVERSION:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"Invalid 'to_type' value: {to_type!r}.\\n\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\"Conversion abbreviations are: {\", \".join(a__ )}\"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(a__ )\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = METRIC_CONVERSION[from_sanitized]\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = METRIC_CONVERSION[to_sanitized]\n\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = 1\n\n\t\t\t\t\t\t\tif from_exponent > to_exponent:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = from_exponent - to_exponent\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCamelCase__\t\t\t = -(to_exponent - from_exponent)\n\n\t\t\t\t\t\t\treturn value * pow(10\t\t\t\t, a__ )\n\n\nif __name__ == \"__main__\":\n\t\t\t\t\tfrom doctest import testmod\n\n\t\t\t\t\ttestmod()\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":87,"string":"87"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":274,"cells":{"code":{"kind":"string","value":"\n\nimport re\n\nfrom filelock import FileLock\n\n\ntry:\n import nltk\n\n snake_case_\t\t\t = True\nexcept (ImportError, ModuleNotFoundError):\n snake_case_\t\t\t = False\n\nif NLTK_AVAILABLE:\n with FileLock('''.lock''') as lock:\n nltk.download('''punkt''', quiet=True)\n\ndef \tsnake_case__\t\t\t( SCREAMING_SNAKE_CASE_\t\t: str\t\t\t):\n\n\n\n '''simple docstring'''\n\n\n\n\n\n re.sub(''\t, ''\t, SCREAMING_SNAKE_CASE_\t\t\t) # remove pegasus newline char\n assert NLTK_AVAILABLE, \"nltk must be installed to separate newlines between sentences. (pip install nltk)\"\n return \"\\n\".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE_\t\t\t)\t\t\t)\n\n"},"code_codestyle":{"kind":"number","value":214,"string":"214"},"style_context":{"kind":"string","value":"\n\nimport itertools\nfrom dataclasses import dataclass\nfrom typing import Any, Callable, Dict, List, Optional, Union\n\nimport pandas as pd\nimport pyarrow as pa\n\nimport datasets\nimport datasets.config\nfrom datasets.features.features import require_storage_cast\nfrom datasets.table import table_cast\nfrom datasets.utils.py_utils import Literal\n\n\nsnake_case_\t\t\t = datasets.utils.logging.get_logger(__name__)\n\nsnake_case_\t\t\t = ['''names''', '''prefix''']\nsnake_case_\t\t\t = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']\nsnake_case_\t\t\t = ['''encoding_errors''', '''on_bad_lines''']\nsnake_case_\t\t\t = ['''date_format''']\n\n\n@dataclass\nclass SCREAMING_SNAKE_CASE__\t\t\t\t\t(datasets.BuilderConfig ):\n __lowerCamelCase\t\t\t\t\t\t: str\t\t\t\t\t\t\t\t\t\t\t\t\t\t= \",\"\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[Union[int, List[int], str]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= \"infer\"\n __lowerCamelCase\t\t\t\t\t\t: Optional[List[str]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[List[str]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[Union[int, str, List[int], List[str]]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[Union[List[int], List[str]]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= True\n __lowerCamelCase\t\t\t\t\t\t: Optional[Literal[\"c\", \"python\", \"pyarrow\"]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Dict[Union[int, str], Callable[[Any], Any]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[list]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[list]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= False\n __lowerCamelCase\t\t\t\t\t\t: Optional[Union[int, List[int]]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[Union[str, List[str]]]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= True\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= True\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= False\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= True\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: str\t\t\t\t\t\t\t\t\t\t\t\t\t\t= \".\"\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: str\t\t\t\t\t\t\t\t\t\t\t\t\t\t= '\"'\n __lowerCamelCase\t\t\t\t\t\t: int\t\t\t\t\t\t\t\t\t\t\t\t\t\t= 0\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= True\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= True\n __lowerCamelCase\t\t\t\t\t\t: int\t\t\t\t\t\t\t\t\t\t\t\t\t\t= 0\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= True\n __lowerCamelCase\t\t\t\t\t\t: bool\t\t\t\t\t\t\t\t\t\t\t\t\t\t= False\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: int\t\t\t\t\t\t\t\t\t\t\t\t\t\t= 1_0000\n __lowerCamelCase\t\t\t\t\t\t: Optional[datasets.Features]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= \"strict\"\n __lowerCamelCase\t\t\t\t\t\t: Literal[\"error\", \"warn\", \"skip\"]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= \"error\"\n __lowerCamelCase\t\t\t\t\t\t: Optional[str]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= None\n\n\n\n\n\n def snake_case_\t\t\t\t( self):\n if self.delimiter is not None:\n lowercase__ : List[Any] = self.delimiter\n if self.column_names is not None:\n lowercase__ : Optional[int] = self.column_names\n\n\n\n\n\n @property\n def snake_case_\t\t\t\t( self):\n lowercase__ : Dict = {\n 'sep': self.sep,\n 'header': self.header,\n 'names': self.names,\n 'index_col': self.index_col,\n 'usecols': self.usecols,\n 'prefix': self.prefix,\n 'mangle_dupe_cols': self.mangle_dupe_cols,\n 'engine': self.engine,\n 'converters': self.converters,\n 'true_values': self.true_values,\n 'false_values': self.false_values,\n 'skipinitialspace': self.skipinitialspace,\n 'skiprows': self.skiprows,\n 'nrows': self.nrows,\n 'na_values': self.na_values,\n 'keep_default_na': self.keep_default_na,\n 'na_filter': self.na_filter,\n 'verbose': self.verbose,\n 'skip_blank_lines': self.skip_blank_lines,\n 'thousands': self.thousands,\n 'decimal': self.decimal,\n 'lineterminator': self.lineterminator,\n 'quotechar': self.quotechar,\n 'quoting': self.quoting,\n 'escapechar': self.escapechar,\n 'comment': self.comment,\n 'encoding': self.encoding,\n 'dialect': self.dialect,\n 'error_bad_lines': self.error_bad_lines,\n 'warn_bad_lines': self.warn_bad_lines,\n 'skipfooter': self.skipfooter,\n 'doublequote': self.doublequote,\n 'memory_map': self.memory_map,\n 'float_precision': self.float_precision,\n 'chunksize': self.chunksize,\n 'encoding_errors': self.encoding_errors,\n 'on_bad_lines': self.on_bad_lines,\n 'date_format': self.date_format,\n }\n\n # some kwargs must not be passed if they don't have a default value\n # some others are deprecated and we can also not pass them if they are the default value\n for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:\n if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()\t\t\t\t\t\t, a):\n del pd_read_csv_kwargs[pd_read_csv_parameter]\n\n # Remove 2.0 new arguments\n if not (datasets.config.PANDAS_VERSION.major >= 2):\n for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:\n del pd_read_csv_kwargs[pd_read_csv_parameter]\n\n # Remove 1.3 new arguments\n if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):\n for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:\n del pd_read_csv_kwargs[pd_read_csv_parameter]\n\n return pd_read_csv_kwargs\n\n\n\nclass SCREAMING_SNAKE_CASE__\t\t\t\t\t(datasets.ArrowBasedBuilder ):\n __lowerCamelCase\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t\t\t\t\t\t\t\t= CsvConfig\n\n\n\n\n\n def snake_case_\t\t\t\t( self):\n return datasets.DatasetInfo(features=self.config.features)\n\n\n\n\n\n def snake_case_\t\t\t\t( self\t\t\t\t\t\t, a):\n if not self.config.data_files:\n raise ValueError(f\"\"\"At least one data file must be specified, but got data_files={self.config.data_files}\"\"\")\n lowercase__ : Any = dl_manager.download_and_extract(self.config.data_files)\n if isinstance(a\t\t\t\t\t\t, (str, list, tuple)):\n lowercase__ : List[str] = data_files\n if isinstance(a\t\t\t\t\t\t, a):\n lowercase__ : Optional[Any] = [files]\n lowercase__ : Optional[int] = [dl_manager.iter_files(a) for file in files]\n return [datasets.SplitGenerator(name=datasets.Split.TRAIN\t\t\t\t\t\t, gen_kwargs={'files': files})]\n lowercase__ : int = []\n for split_name, files in data_files.items():\n if isinstance(a\t\t\t\t\t\t, a):\n lowercase__ : Optional[int] = [files]\n lowercase__ : Tuple = [dl_manager.iter_files(a) for file in files]\n splits.append(datasets.SplitGenerator(name=a\t\t\t\t\t\t, gen_kwargs={'files': files}))\n return splits\n\n\n\n\n\n def snake_case_\t\t\t\t( self\t\t\t\t\t\t, a):\n if self.config.features is not None:\n lowercase__ : Optional[int] = self.config.features.arrow_schema\n if all(not require_storage_cast(a) for feature in self.config.features.values()):\n # cheaper cast\n lowercase__ : Dict = pa.Table.from_arrays([pa_table[field.name] for field in schema]\t\t\t\t\t\t, schema=a)\n else:\n # more expensive cast; allows str <-> int/float or str to Audio for example\n lowercase__ : Optional[Any] = table_cast(a\t\t\t\t\t\t, a)\n return pa_table\n\n\n\n\n\n def snake_case_\t\t\t\t( self\t\t\t\t\t\t, a):\n lowercase__ : List[Any] = self.config.features.arrow_schema if self.config.features else None\n # dtype allows reading an int column as str\n lowercase__ : Optional[int] = (\n {\n name: dtype.to_pandas_dtype() if not require_storage_cast(a) else object\n for name, dtype, feature in zip(schema.names\t\t\t\t\t\t, schema.types\t\t\t\t\t\t, self.config.features.values())\n }\n if schema is not None\n else None\n )\n for file_idx, file in enumerate(itertools.chain.from_iterable(a)):\n lowercase__ : int = pd.read_csv(a\t\t\t\t\t\t, iterator=a\t\t\t\t\t\t, dtype=a\t\t\t\t\t\t, **self.config.pd_read_csv_kwargs)\n try:\n for batch_idx, df in enumerate(a):\n lowercase__ : List[str] = pa.Table.from_pandas(a)\n # Uncomment for debugging (will print the Arrow table size and elements)\n # logger.warning(f\"pa_table: {pa_table} num rows: {pa_table.num_rows}\")\n # logger.warning('\\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))\n yield (file_idx, batch_idx), self._cast_table(a)\n except ValueError as e:\n logger.error(f\"\"\"Failed to read file '{file}' with error {type(a)}: {e}\"\"\")\n raise\n\n"},"style_context_codestyle":{"kind":"number","value":214,"string":"214"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":275,"cells":{"code":{"kind":"string","value":"\rimport argparse\rimport json\rimport pickle\rfrom pathlib import Path\r\rimport requests\rimport torch\rfrom huggingface_hub import hf_hub_download\rfrom PIL import Image\r\rfrom transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig\rfrom transformers.utils import logging\r\r\rlogging.set_verbosity_info()\r__UpperCAmelCase\t\t\t\t\t\t= logging.get_logger(__name__)\r\r\rdef \t\t\t\tA__\t\t\t\t( __lowerCamelCase\t\t):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= SwinConfig.from_pretrained(\r '''microsoft/swin-tiny-patch4-window7-224''', out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4''']\t\t)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= MaskFormerConfig(backbone_config=__lowerCamelCase\t\t)\r\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''huggingface/label-files'''\r if \"ade20k-full\" in model_name:\r # this should be ok\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 8_47\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''maskformer-ade20k-full-id2label.json'''\r elif \"ade\" in model_name:\r # this should be ok\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 1_50\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''ade20k-id2label.json'''\r elif \"coco-stuff\" in model_name:\r # this should be ok\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 1_71\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''maskformer-coco-stuff-id2label.json'''\r elif \"coco\" in model_name:\r # TODO\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 1_33\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''coco-panoptic-id2label.json'''\r elif \"cityscapes\" in model_name:\r # this should be ok\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 19\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''cityscapes-id2label.json'''\r elif \"vistas\" in model_name:\r # this should be ok\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 65\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''mapillary-vistas-id2label.json'''\r\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= json.load(open(hf_hub_download(__lowerCamelCase, __lowerCamelCase, repo_type='''dataset'''\t\t), '''r'''\t\t)\t\t)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= {int(__lowerCamelCase\t\t): v for k, v in idalabel.items()}\r\r return config\r\r\rdef \t\t\t\tA__\t\t\t\t( __lowerCamelCase\t\t):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= []\r # stem\r # fmt: off\r rename_keys.append(('''backbone.patch_embed.proj.weight''', '''model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight''')\t\t)\r rename_keys.append(('''backbone.patch_embed.proj.bias''', '''model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias''')\t\t)\r rename_keys.append(('''backbone.patch_embed.norm.weight''', '''model.pixel_level_module.encoder.model.embeddings.norm.weight''')\t\t)\r rename_keys.append(('''backbone.patch_embed.norm.bias''', '''model.pixel_level_module.encoder.model.embeddings.norm.bias''')\t\t)\r # stages\r for i in range(len(config.backbone_config.depths\t\t)\t\t):\r for j in range(config.backbone_config.depths[i]\t\t):\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.norm2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''')\t\t)\r\r if i < 3:\r rename_keys.append((F'''backbone.layers.{i}.downsample.reduction.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.downsample.norm.weight''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight''')\t\t)\r rename_keys.append((F'''backbone.layers.{i}.downsample.norm.bias''', F'''model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias''')\t\t)\r rename_keys.append((F'''backbone.norm{i}.weight''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.weight''')\t\t)\r rename_keys.append((F'''backbone.norm{i}.bias''', F'''model.pixel_level_module.encoder.hidden_states_norms.{i}.bias''')\t\t)\r\r # FPN\r rename_keys.append(('''sem_seg_head.layer_4.weight''', '''model.pixel_level_module.decoder.fpn.stem.0.weight''')\t\t)\r rename_keys.append(('''sem_seg_head.layer_4.norm.weight''', '''model.pixel_level_module.decoder.fpn.stem.1.weight''')\t\t)\r rename_keys.append(('''sem_seg_head.layer_4.norm.bias''', '''model.pixel_level_module.decoder.fpn.stem.1.bias''')\t\t)\r for source_index, target_index in zip(range(3, 0, -1\t\t), range(0, 3\t\t)\t\t):\r rename_keys.append((F'''sem_seg_head.adapter_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.adapter_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias''')\t\t)\r rename_keys.append((F'''sem_seg_head.layer_{source_index}.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.weight''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.layer_{source_index}.norm.bias''', F'''model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias''')\t\t)\r rename_keys.append(('''sem_seg_head.mask_features.weight''', '''model.pixel_level_module.decoder.mask_projection.weight''')\t\t)\r rename_keys.append(('''sem_seg_head.mask_features.bias''', '''model.pixel_level_module.decoder.mask_projection.bias''')\t\t)\r\r # Transformer decoder\r for idx in range(config.decoder_config.decoder_layers\t\t):\r # self-attention out projection\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias''')\t\t)\r # cross-attention out projection\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias''')\t\t)\r # MLP 1\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc1.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc1.bias''')\t\t)\r # MLP 2\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight''', F'''model.transformer_module.decoder.layers.{idx}.fc2.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias''', F'''model.transformer_module.decoder.layers.{idx}.fc2.bias''')\t\t)\r # layernorm 1 (self-attention layernorm)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias''', F'''model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias''')\t\t)\r # layernorm 2 (cross-attention layernorm)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias''', F'''model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias''')\t\t)\r # layernorm 3 (final layernorm)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias''', F'''model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias''')\t\t)\r\r rename_keys.append(('''sem_seg_head.predictor.transformer.decoder.norm.weight''', '''model.transformer_module.decoder.layernorm.weight''')\t\t)\r rename_keys.append(('''sem_seg_head.predictor.transformer.decoder.norm.bias''', '''model.transformer_module.decoder.layernorm.bias''')\t\t)\r\r # heads on top\r rename_keys.append(('''sem_seg_head.predictor.query_embed.weight''', '''model.transformer_module.queries_embedder.weight''')\t\t)\r\r rename_keys.append(('''sem_seg_head.predictor.input_proj.weight''', '''model.transformer_module.input_projection.weight''')\t\t)\r rename_keys.append(('''sem_seg_head.predictor.input_proj.bias''', '''model.transformer_module.input_projection.bias''')\t\t)\r\r rename_keys.append(('''sem_seg_head.predictor.class_embed.weight''', '''class_predictor.weight''')\t\t)\r rename_keys.append(('''sem_seg_head.predictor.class_embed.bias''', '''class_predictor.bias''')\t\t)\r\r for i in range(3\t\t):\r rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.weight''', F'''mask_embedder.{i}.0.weight''')\t\t)\r rename_keys.append((F'''sem_seg_head.predictor.mask_embed.layers.{i}.bias''', F'''mask_embedder.{i}.0.bias''')\t\t)\r # fmt: on\r\r return rename_keys\r\r\rdef \t\t\t\tA__\t\t\t\t( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase\t\t):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= dct.pop(__lowerCamelCase\t\t)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= val\r\r\rdef \t\t\t\tA__\t\t\t\t( __lowerCamelCase, __lowerCamelCase\t\t):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= [int(backbone_config.embed_dim * 2**i\t\t) for i in range(len(backbone_config.depths\t\t)\t\t)]\r for i in range(len(backbone_config.depths\t\t)\t\t):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= num_features[i]\r for j in range(backbone_config.depths[i]\t\t):\r # fmt: off\r # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.weight'''\t\t)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= state_dict.pop(F'''backbone.layers.{i}.blocks.{j}.attn.qkv.bias'''\t\t)\r # next, add query, keys and values (in that order) to the state dict\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[:dim, :]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[: dim]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[\r dim : dim * 2, :\r ]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[\r dim : dim * 2\r ]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[\r -dim :, :\r ]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[-dim :]\r # fmt: on\r\r\rdef \t\t\t\tA__\t\t\t\t( __lowerCamelCase, __lowerCamelCase\t\t):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= config.decoder_config.hidden_size\r for idx in range(config.decoder_config.decoder_layers\t\t):\r # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight'''\t\t)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias'''\t\t)\r # next, add query, keys and values (in that order) to the state dict\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[: hidden_size, :]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[:config.hidden_size]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[hidden_size : hidden_size * 2, :]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[hidden_size : hidden_size * 2]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[-hidden_size :, :]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[-hidden_size :]\r # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight'''\t\t)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= state_dict.pop(F'''sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias'''\t\t)\r # next, add query, keys and values (in that order) to the state dict\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[: hidden_size, :]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[:config.hidden_size]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[hidden_size : hidden_size * 2, :]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[hidden_size : hidden_size * 2]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_weight[-hidden_size :, :]\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= in_proj_bias[-hidden_size :]\r # fmt: on\r\r\rdef \t\t\t\tA__\t\t\t\t( ):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= '''http://images.cocodataset.org/val2017/000000039769.jpg'''\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= Image.open(requests.get(__lowerCamelCase, stream=__lowerCamelCase\t\t).raw\t\t)\r return im\r\r\r@torch.no_grad()\rdef \t\t\t\tA__\t\t\t\t( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = False\t\t):\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= get_maskformer_config(__lowerCamelCase\t\t)\r\r # load original state_dict\r with open(__lowerCamelCase, '''rb'''\t\t) as f:\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= pickle.load(__lowerCamelCase\t\t)\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= data['''model''']\r\r # for name, param in state_dict.items():\r # print(name, param.shape)\r\r # rename keys\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= create_rename_keys(__lowerCamelCase\t\t)\r for src, dest in rename_keys:\r rename_key(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase\t\t)\r read_in_swin_q_k_v(__lowerCamelCase, config.backbone_config\t\t)\r read_in_decoder_q_k_v(__lowerCamelCase, __lowerCamelCase\t\t)\r\r # update to torch tensors\r for key, value in state_dict.items():\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= torch.from_numpy(__lowerCamelCase\t\t)\r\r # load 🤗 model\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= MaskFormerForInstanceSegmentation(__lowerCamelCase\t\t)\r model.eval()\r\r for name, param in model.named_parameters():\r print(__lowerCamelCase, param.shape\t\t)\r\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= model.load_state_dict(__lowerCamelCase, strict=__lowerCamelCase\t\t)\r assert missing_keys == [\r \"model.pixel_level_module.encoder.model.layernorm.weight\",\r \"model.pixel_level_module.encoder.model.layernorm.bias\",\r ]\r assert len(__lowerCamelCase\t\t) == 0, F'''Unexpected keys: {unexpected_keys}'''\r\r # verify results\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= prepare_img()\r if \"vistas\" in model_name:\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 65\r elif \"cityscapes\" in model_name:\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 6_55_35\r else:\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= 2_55\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= True if '''ade''' in model_name else False\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= MaskFormerImageProcessor(ignore_index=__lowerCamelCase, reduce_labels=__lowerCamelCase\t\t)\r\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= image_processor(__lowerCamelCase, return_tensors='''pt'''\t\t)\r\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= model(**__lowerCamelCase\t\t)\r\r print('''Logits:''', outputs.class_queries_logits[0, :3, :3]\t\t)\r\r if model_name == \"maskformer-swin-tiny-ade\":\r SCREAMING_SNAKE_CASE_\t\t\t\t\t= torch.tensor(\r [[3.63_53, -4.47_70, -2.60_65], [0.50_81, -4.23_94, -3.53_43], [2.19_09, -5.03_53, -1.93_23]]\t\t)\r assert torch.allclose(outputs.class_queries_logits[0, :3, :3], __lowerCamelCase, atol=1E-4\t\t)\r print('''Looks ok!'''\t\t)\r\r if pytorch_dump_folder_path is not None:\r print(F'''Saving model and image processor to {pytorch_dump_folder_path}'''\t\t)\r Path(__lowerCamelCase\t\t).mkdir(exist_ok=__lowerCamelCase\t\t)\r model.save_pretrained(__lowerCamelCase\t\t)\r image_processor.save_pretrained(__lowerCamelCase\t\t)\r\r if push_to_hub:\r print('''Pushing model and image processor to the hub...'''\t\t)\r model.push_to_hub(F'''nielsr/{model_name}'''\t\t)\r image_processor.push_to_hub(F'''nielsr/{model_name}'''\t\t)\r\r\rif __name__ == \"__main__\":\r __UpperCAmelCase\t\t\t\t\t\t= argparse.ArgumentParser()\r # Required parameters\r parser.add_argument(\r \"--model_name\",\r default=\"maskformer-swin-tiny-ade\",\r type=str,\r help=(\"Name of the MaskFormer model you\\'d like to convert\",),\r )\r parser.add_argument(\r \"--checkpoint_path\",\r default=\"/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl\",\r type=str,\r help=\"Path to the original state dict (.pth file).\",\r )\r parser.add_argument(\r \"--pytorch_dump_folder_path\", default=None, type=str, help=\"Path to the output PyTorch model directory.\"\r )\r parser.add_argument(\r \"--push_to_hub\", action=\"store_true\", help=\"Whether or not to push the converted model to the 🤗 hub.\"\r )\r\r __UpperCAmelCase\t\t\t\t\t\t= parser.parse_args()\r convert_maskformer_checkpoint(\r args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub\r )\r\r\r"},"code_codestyle":{"kind":"number","value":367,"string":"367"},"style_context":{"kind":"string","value":"\rfrom .data_collator import (\r DataCollatorForLanguageModeling,\r DataCollatorForPermutationLanguageModeling,\r DataCollatorForSeqaSeq,\r DataCollatorForSOP,\r DataCollatorForTokenClassification,\r DataCollatorForWholeWordMask,\r DataCollatorWithPadding,\r DefaultDataCollator,\r default_data_collator,\r)\rfrom .metrics import glue_compute_metrics, xnli_compute_metrics\rfrom .processors import (\r DataProcessor,\r InputExample,\r InputFeatures,\r SingleSentenceClassificationProcessor,\r SquadExample,\r SquadFeatures,\r SquadVaProcessor,\r SquadVaProcessor,\r glue_convert_examples_to_features,\r glue_output_modes,\r glue_processors,\r glue_tasks_num_labels,\r squad_convert_examples_to_features,\r xnli_output_modes,\r xnli_processors,\r xnli_tasks_num_labels,\r)\r\r\r"},"style_context_codestyle":{"kind":"number","value":257,"string":"257"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":276,"cells":{"code":{"kind":"string","value":"\r\rfrom typing import Mapping\r\rfrom ...configuration_utils import PretrainedConfig\rfrom ...onnx import OnnxSeqaSeqConfigWithPast\rfrom ...utils import logging\r\r\r_SCREAMING_SNAKE_CASE : Tuple \t\t\t=\t\t\tlogging.get_logger(__name__)\r\r_SCREAMING_SNAKE_CASE : Optional[Any] \t\t\t=\t\t\t{\r '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''',\r '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''',\r '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''',\r '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''',\r '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''',\r}\r\r\r\r\r\r\rclass UpperCAmelCase__\t\t( A__ ):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r a =\t\t\t\t\t\"t5\"\r a =\t\t\t\t\t[\"past_key_values\"]\r a =\t\t\t\t\t{\"hidden_size\": \"d_model\", \"num_attention_heads\": \"num_heads\", \"num_hidden_layers\": \"num_layers\"}\r\r\r\r\r\r\r def __init__(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tUnion[str, Any]\t, __lowerCamelCase\t\t\t\t\t\t:\t\tstr=3_2128\t, __lowerCamelCase\t\t\t\t\t\t:\t\tList[Any]=512\t, __lowerCamelCase\t\t\t\t\t\t:\t\tOptional[int]=64\t, __lowerCamelCase\t\t\t\t\t\t:\t\tList[Any]=2048\t, __lowerCamelCase\t\t\t\t\t\t:\t\tOptional[Any]=6\t, __lowerCamelCase\t\t\t\t\t\t:\t\tList[str]=None\t, __lowerCamelCase\t\t\t\t\t\t:\t\tList[str]=8\t, __lowerCamelCase\t\t\t\t\t\t:\t\tint=32\t, __lowerCamelCase\t\t\t\t\t\t:\t\tDict=128\t, __lowerCamelCase\t\t\t\t\t\t:\t\tstr=0.1\t, __lowerCamelCase\t\t\t\t\t\t:\t\tDict=1e-6\t, __lowerCamelCase\t\t\t\t\t\t:\t\tList[Any]=1.0\t, __lowerCamelCase\t\t\t\t\t\t:\t\tstr=\"relu\"\t, __lowerCamelCase\t\t\t\t\t\t:\t\tList[str]=True\t, __lowerCamelCase\t\t\t\t\t\t:\t\tOptional[int]=True\t, __lowerCamelCase\t\t\t\t\t\t:\t\tList[Any]=0\t, __lowerCamelCase\t\t\t\t\t\t:\t\tUnion[str, Any]=1\t, **__lowerCamelCase\t\t\t\t\t\t:\t\tList[Any]\t, )\t\t->\t\t\t\t\t\t\tDict:\r SCREAMING_SNAKE_CASE__ = vocab_size\r SCREAMING_SNAKE_CASE__ = d_model\r SCREAMING_SNAKE_CASE__ = d_kv\r SCREAMING_SNAKE_CASE__ = d_ff\r SCREAMING_SNAKE_CASE__ = num_layers\r SCREAMING_SNAKE_CASE__ = (\r num_decoder_layers if num_decoder_layers is not None else self.num_layers\r ) # default = symmetry\r SCREAMING_SNAKE_CASE__ = num_heads\r SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets\r SCREAMING_SNAKE_CASE__ = relative_attention_max_distance\r SCREAMING_SNAKE_CASE__ = dropout_rate\r SCREAMING_SNAKE_CASE__ = layer_norm_epsilon\r SCREAMING_SNAKE_CASE__ = initializer_factor\r SCREAMING_SNAKE_CASE__ = feed_forward_proj\r SCREAMING_SNAKE_CASE__ = use_cache\r\r SCREAMING_SNAKE_CASE__ = self.feed_forward_proj.split('''-'''\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__ = act_info[-1]\r SCREAMING_SNAKE_CASE__ = act_info[0] == '''gated'''\r\r if len(__lowerCamelCase\t\t\t\t\t) > 1 and act_info[0] != \"gated\" or len(__lowerCamelCase\t\t\t\t\t) > 2:\r raise ValueError(\r f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''\r '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '''\r '''\\'gated-gelu\\' or \\'relu\\''''\t\t\t\t\t)\r\r # for backwards compatibility\r if feed_forward_proj == \"gated-gelu\":\r SCREAMING_SNAKE_CASE__ = '''gelu_new'''\r\r super().__init__(\r pad_token_id=__lowerCamelCase\t, eos_token_id=__lowerCamelCase\t, is_encoder_decoder=__lowerCamelCase\t, **__lowerCamelCase\t, )\r\r\r\r\r\r\rclass UpperCAmelCase__\t\t( A__ ):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r @property\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tAny\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tMapping[str, Mapping[int, str]]:\r SCREAMING_SNAKE_CASE__ = {\r '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''},\r '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''},\r }\r if self.use_past:\r SCREAMING_SNAKE_CASE__ = '''past_encoder_sequence + sequence'''\r SCREAMING_SNAKE_CASE__ = {0: '''batch'''}\r SCREAMING_SNAKE_CASE__ = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''}\r else:\r SCREAMING_SNAKE_CASE__ = {0: '''batch''', 1: '''decoder_sequence'''}\r SCREAMING_SNAKE_CASE__ = {0: '''batch''', 1: '''decoder_sequence'''}\r\r if self.use_past:\r self.fill_with_past_key_values_(__lowerCamelCase\t, direction='''inputs'''\t\t\t\t\t)\r\r return common_inputs\r\r\r\r\r\r\r\r @property\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tTuple\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tint:\r return 13\r\r\r"},"code_codestyle":{"kind":"number","value":314,"string":"314"},"style_context":{"kind":"string","value":"\r\rimport unittest\r\rimport torch\rfrom torch import nn\r\rfrom accelerate.test_utils import require_cuda\rfrom accelerate.utils.memory import find_executable_batch_size, release_memory\rdef \t\t\t\tUpperCAmelCase_ (\t\t\t\t\t\t):\r\r\r\r\r\r '''simple docstring'''\r\r\r\r\r raise RuntimeError('''CUDA out of memory.'''\t\t\t\t)\r\r\r\r\r\r\rclass UpperCAmelCase__\t\t( nn.Module ):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r def __init__(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tAny\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tint:\r super().__init__()\r SCREAMING_SNAKE_CASE__ = nn.Linear(3\t, 4\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__ = nn.BatchNormad(4\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__ = nn.Linear(4\t, 5\t\t\t\t\t)\r\r\r\r\r\r\r\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tint\t, __lowerCamelCase\t\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tTuple:\r return self.lineara(self.batchnorm(self.lineara(__lowerCamelCase\t\t\t\t\t)\t\t\t\t\t)\t\t\t\t\t)\r\r\r\r\r\r\rclass UpperCAmelCase__\t\t( unittest.TestCase ):\r\r\r\r\r\r\r \"\"\"simple docstring\"\"\"\r\r\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tList[Any]\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tDict:\r SCREAMING_SNAKE_CASE__ = []\r\r @find_executable_batch_size(starting_batch_size=128\t\t\t\t\t)\r def mock_training_loop_function(__lowerCamelCase\t\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t):\r nonlocal batch_sizes\r batch_sizes.append(__lowerCamelCase\t\t\t\t\t)\r if batch_size != 8:\r raise_fake_out_of_memory()\r\r mock_training_loop_function()\r self.assertListEqual(__lowerCamelCase\t, [128, 64, 32, 16, 8]\t\t\t\t\t)\r\r\r\r\r\r\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tOptional[Any]\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tList[Any]:\r SCREAMING_SNAKE_CASE__ = []\r\r @find_executable_batch_size(starting_batch_size=128\t\t\t\t\t)\r def mock_training_loop_function(__lowerCamelCase\t\t\t\t\t\t:\t\tList[Any]\t, __lowerCamelCase\t\t\t\t\t\t:\t\tUnion[str, Any]\t\t\t\t\t):\r nonlocal batch_sizes\r batch_sizes.append(__lowerCamelCase\t\t\t\t\t)\r if batch_size != 8:\r raise_fake_out_of_memory()\r return batch_size, arga\r\r SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ = mock_training_loop_function('''hello'''\t\t\t\t\t)\r self.assertListEqual(__lowerCamelCase\t, [128, 64, 32, 16, 8]\t\t\t\t\t)\r self.assertListEqual([bs, arga]\t, [8, '''hello''']\t\t\t\t\t)\r\r\r\r\r\r\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tstr\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tList[Any]:\r @find_executable_batch_size(starting_batch_size=0\t\t\t\t\t)\r def mock_training_loop_function(__lowerCamelCase\t\t\t\t\t\t:\t\tOptional[Any]\t\t\t\t\t):\r pass\r\r with self.assertRaises(__lowerCamelCase\t\t\t\t\t) as cm:\r mock_training_loop_function()\r self.assertIn('''No executable batch size found, reached zero.'''\t, cm.exception.args[0]\t\t\t\t\t)\r\r\r\r\r\r\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tUnion[str, Any]\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tList[str]:\r @find_executable_batch_size(starting_batch_size=16\t\t\t\t\t)\r def mock_training_loop_function(__lowerCamelCase\t\t\t\t\t\t:\t\tDict\t\t\t\t\t):\r if batch_size > 0:\r raise_fake_out_of_memory()\r pass\r\r with self.assertRaises(__lowerCamelCase\t\t\t\t\t) as cm:\r mock_training_loop_function()\r self.assertIn('''No executable batch size found, reached zero.'''\t, cm.exception.args[0]\t\t\t\t\t)\r\r\r\r\r\r\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tList[Any]\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tList[str]:\r @find_executable_batch_size(starting_batch_size=128\t\t\t\t\t)\r def mock_training_loop_function(__lowerCamelCase\t\t\t\t\t\t:\t\tint\t, __lowerCamelCase\t\t\t\t\t\t:\t\tOptional[int]\t, __lowerCamelCase\t\t\t\t\t\t:\t\tAny\t\t\t\t\t):\r if batch_size != 8:\r raise raise_fake_out_of_memory()\r\r with self.assertRaises(__lowerCamelCase\t\t\t\t\t) as cm:\r mock_training_loop_function(128\t, '''hello'''\t, '''world'''\t\t\t\t\t)\r self.assertIn('''Batch size was passed into `f`'''\t, cm.exception.args[0]\t\t\t\t\t)\r self.assertIn('''`f(arg1=\\'hello\\', arg2=\\'world\\')'''\t, cm.exception.args[0]\t\t\t\t\t)\r\r\r\r\r\r\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tUnion[str, Any]\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tint:\r @find_executable_batch_size(starting_batch_size=16\t\t\t\t\t)\r def mock_training_loop_function(__lowerCamelCase\t\t\t\t\t\t:\t\tTuple\t\t\t\t\t):\r raise ValueError('''Oops, we had an error!'''\t\t\t\t\t)\r\r with self.assertRaises(__lowerCamelCase\t\t\t\t\t) as cm:\r mock_training_loop_function()\r self.assertIn('''Oops, we had an error!'''\t, cm.exception.args[0]\t\t\t\t\t)\r\r\r\r\r\r\r\r @require_cuda\r def lowercase_\t\t(\t\t\t\t\t\t\tself\t\t\t\t\t\t:\t\tOptional[int]\t\t\t\t\t)\t\t->\t\t\t\t\t\t\tstr:\r SCREAMING_SNAKE_CASE__ = torch.cuda.memory_allocated()\r SCREAMING_SNAKE_CASE__ = ModelForTest()\r model.cuda()\r self.assertGreater(torch.cuda.memory_allocated()\t, __lowerCamelCase\t\t\t\t\t)\r SCREAMING_SNAKE_CASE__ = release_memory(__lowerCamelCase\t\t\t\t\t)\r self.assertEqual(torch.cuda.memory_allocated()\t, __lowerCamelCase\t\t\t\t\t)\r\r\r"},"style_context_codestyle":{"kind":"number","value":314,"string":"314"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":277,"cells":{"code":{"kind":"string","value":"\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\nimport pytest\r\n\r\n\r\nUpperCAmelCase\t\t =\"__dummy_dataset1__\"\r\n\r\nUpperCAmelCase\t\t =\"\\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\"\r\n\r\n\r\n\r\n@pytest.fixture\r\ndef _A\t\t\t(\t\t\t\t\t):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n return DATASET_LOADING_SCRIPT_NAME\r\n\r\n\r\n\r\n@pytest.fixture\r\ndef _A\t\t\t(\t\t\t\t\t):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n return DATASET_LOADING_SCRIPT_CODE\r\n\r\n\r\n\r\n\r\n\r\n@pytest.fixture\r\ndef _A\t\t\t(\t\t\t\t\t_a\t\t\t\t\t:\t\tstr , _a\t\t\t\t\t:\t\tList[Any] , _a\t\t\t\t\t:\t\tList[Any]\t\t\t\t\t\t\t):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n A\t\t\t\t\t\t\t =\t\t\t\t\t\tdataset_loading_script_name\r\n A\t\t\t\t\t\t\t =\t\t\t\t\t\ttmp_path / \"\"\"datasets\"\"\" / script_name\r\n script_dir.mkdir(parents=_a\t\t\t\t\t\t\t)\r\n A\t\t\t\t\t\t\t =\t\t\t\t\t\tscript_dir / f'{script_name}.py'\r\n with open(_a , \"\"\"w\"\"\"\t\t\t\t\t\t\t) as f:\r\n f.write(_a\t\t\t\t\t\t\t)\r\n return str(_a\t\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":77,"string":"77"},"style_context":{"kind":"string","value":"\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\nfrom math import factorial\r\n\r\n\r\n\r\ndef _A\t\t\t(\t\t\t\t\t_a\t\t\t\t\t:\t\tint = 1_0_0\t\t\t\t\t\t\t):\r\n\r\n\r\n\r\n \"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n return sum(map(_a , str(factorial(_a\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(solution(int(input(\"Enter the Number: \").strip())))\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":77,"string":"77"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":278,"cells":{"code":{"kind":"string","value":"\rimport json\rimport os\rfrom typing import Dict, List, Optional, Tuple\r\rfrom ...tokenization_utils import PreTrainedTokenizer\rfrom ...utils import logging\r\r\rlowercase__\t\t\t\t\t\t\t:\t\t\t\t\t\t\tTuple\t\t\t\t\t\t\t\t\t\t\t\t\t=\tlogging.get_logger(__name__)\r\r\rlowercase__\t\t\t\t\t\t\t:\t\t\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t\t\t\t\t\t=\t{\r \"vocab_file\": \"vocab.json\",\r \"tokenizer_config_file\": \"tokenizer_config.json\",\r \"merges_file\": \"merges.txt\",\r}\r\rlowercase__\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t\t\t\t=\t{\r \"vocab_file\": {\r \"facebook/s2t-wav2vec2-large-en-de\": (\r \"https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/vocab.json\"\r ),\r },\r \"tokenizer_config_file\": {\r \"facebook/s2t-wav2vec2-large-en-de\": (\r \"https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/tokenizer_config.json\"\r ),\r },\r \"merges_file\": {\r \"facebook/s2t-wav2vec2-large-en-de\": (\r \"https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/merges.txt\"\r ),\r },\r}\r\rlowercase__\t\t\t\t\t\t\t:\t\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\"\"\rlowercase__\t\t\t\t\t\t\t:\t\t\t\t\t\t\tint\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\"@@ \"\r\r\r\r\rdef \t\tA_ (\t\t\t\t\t\t\tsnake_case\t\t\t\t\t\t\t: Dict )\t\t\t\t\t->\t\t\tint:\r\r\r\r\t\t\t\t\t\t'''simple docstring'''\r\r\t\t\t\t\t\t__UpperCamelCase =\tset()\r\t\t\t\t\t\t__UpperCamelCase =\tword[0]\r\t\t\t\t\t\tfor char in word[1:]:\r\t\t\t\t\t\t\t\t\t\t\t\tpairs.add((prev_char, char) )\r\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tchar\r\t\t\t\t\t\treturn pairs\r\r\r# Speech2Text2 has no max input length\rlowercase__\t\t\t\t\t\t\t:\t\t\t\t\t\t\tDict\t\t\t\t\t\t\t\t\t\t\t\t\t=\t{\"facebook/s2t-wav2vec2-large-en-de\": 1_0_2_4}\r\r\r\r\r\r\rclass \t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t(\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_\t\t\t):\r\r\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\t\t\t\t\t\t\t_snake_case \t\t\t\t\t\t= VOCAB_FILES_NAMES\r\t\t\t\t\t\t\t_snake_case \t\t\t\t\t\t= PRETRAINED_VOCAB_FILES_MAP\r\t\t\t\t\t\t\t_snake_case \t\t\t\t\t\t= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\r\t\t\t\t\t\t\t_snake_case \t\t\t\t\t\t= ['input_ids', 'attention_mask']\r\r\r\r\t\t\t\t\t\t\tdef __init__( self ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_=\"\" ,\t\tSCREAMING_SNAKE_CASE_=\"\" ,\t\tSCREAMING_SNAKE_CASE_=\"\" ,\t\tSCREAMING_SNAKE_CASE_=\"\" ,\t\tSCREAMING_SNAKE_CASE_=False ,\t\tSCREAMING_SNAKE_CASE_=None ,\t\t**SCREAMING_SNAKE_CASE_ ,\t\t)-> Optional[Any]:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(\r\t\t\t\t\t\t\t\t\t\t\t\t\t unk_token=SCREAMING_SNAKE_CASE_ ,\t\tbos_token=SCREAMING_SNAKE_CASE_ ,\t\teos_token=SCREAMING_SNAKE_CASE_ ,\t\tpad_token=SCREAMING_SNAKE_CASE_ ,\t\tdo_lower_case=SCREAMING_SNAKE_CASE_ ,\t\t**SCREAMING_SNAKE_CASE_ ,\t\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tdo_lower_case\r\r\t\t\t\t\t\t\t\t\t\t\t\t\twith open(SCREAMING_SNAKE_CASE_ ,\t\tencoding='''utf-8'''\t) as vocab_handle:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tjson.load(SCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t{v: k for k, v in self.encoder.items()}\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif merges_file is None:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.info(F\"No merges files provided. {self.__class__.__name__} can only be used for decoding.\"\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tNone\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tNone\r\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith open(SCREAMING_SNAKE_CASE_ ,\t\tencoding='''utf-8'''\t) as merges_handle:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tmerges_handle.read().split('''\\n'''\t)[:-1]\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t[tuple(merge.split()[:2]\t) for merge in merges]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tdict(zip(SCREAMING_SNAKE_CASE_ ,\t\trange(len(SCREAMING_SNAKE_CASE_\t)\t)\t)\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t{}\r\r\r\r\t\t\t\t\t\t\t@property\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self\t)-> int:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn len(self.decoder\t)\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self\t)-> Dict:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn dict(self.encoder ,\t\t**self.added_tokens_encoder\t)\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_\t)-> int:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\ttuple(token[:-1]\t) + (token[-1] + BPE_TOKEN_MERGES,)\r\t\t\t\t\t\t\t\t\t\t\t\t\tif token in self.cache:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn self.cache[token]\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tget_pairs(SCREAMING_SNAKE_CASE_\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif not pairs:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn token\r\r\t\t\t\t\t\t\t\t\t\t\t\t\twhile True:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tmin(SCREAMING_SNAKE_CASE_ ,\t\tkey=lambda SCREAMING_SNAKE_CASE_\t: self.bpe_ranks.get(SCREAMING_SNAKE_CASE_ ,\t\tfloat('''inf'''\t)\t)\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif bigram not in self.bpe_ranks:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t\t__UpperCamelCase =\tbigram\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t[]\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t0\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhile i < len(SCREAMING_SNAKE_CASE_\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tword.index(SCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\texcept ValueError:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew_word.extend(word[i:]\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew_word.extend(word[i:j]\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tj\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif word[i] == first and i < len(SCREAMING_SNAKE_CASE_\t) - 1 and word[i + 1] == second:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew_word.append(first + second\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti += 2\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnew_word.append(word[i]\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti += 1\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\ttuple(SCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tnew_word\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif len(SCREAMING_SNAKE_CASE_\t) == 1:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tget_pairs(SCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t''' '''.join(SCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\tif word == \"\\n \" + BPE_TOKEN_MERGES:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t'''\\n''' + BPE_TOKEN_MERGES\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif word.endswith(SCREAMING_SNAKE_CASE_\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tword.replace(SCREAMING_SNAKE_CASE_ ,\t\t''''''\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tword.replace(''' ''' ,\t\tSCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tword\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn word\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_\t)-> Tuple:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif self.bpe_ranks is None:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''This tokenizer was instantiated without a `merges.txt` file, so'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ''' that it can only be used for decoding, not for encoding.'''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''Make sure to provide `merges.txt` file at instantiation to enable '''\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''encoding.'''\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif self.do_lower_case:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\ttext.lower()\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\ttext.split()\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t[]\r\t\t\t\t\t\t\t\t\t\t\t\t\tfor token in text:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif token:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsplit_tokens.extend(list(self.bpe(SCREAMING_SNAKE_CASE_\t).split(''' '''\t)\t)\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn split_tokens\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_\t)-> int:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn self.encoder.get(SCREAMING_SNAKE_CASE_ ,\t\tself.encoder.get(self.unk_token\t)\t)\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_\t)-> str:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tself.decoder.get(SCREAMING_SNAKE_CASE_ ,\t\tself.unk_token\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn result\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_\t)-> str:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t''' '''.join(SCREAMING_SNAKE_CASE_\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t# make sure @@ tokens are concatenated\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t''''''.join(string.split(SCREAMING_SNAKE_CASE_\t)\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn string\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_ = None\t)-> Tuple[str]:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif not os.path.isdir(SCREAMING_SNAKE_CASE_\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.error(F\"Vocabulary path ({save_directory}) should be a directory\"\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tos.path.join(\r\t\t\t\t\t\t\t\t\t\t\t\t\t SCREAMING_SNAKE_CASE_ ,\t\t(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tos.path.join(\r\t\t\t\t\t\t\t\t\t\t\t\t\t SCREAMING_SNAKE_CASE_ ,\t\t(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\twith open(SCREAMING_SNAKE_CASE_ ,\t\t'''w''' ,\t\tencoding='''utf-8'''\t) as f:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tf.write(json.dumps(self.encoder ,\t\tindent=2 ,\t\tsort_keys=SCREAMING_SNAKE_CASE_ ,\t\tensure_ascii=SCREAMING_SNAKE_CASE_\t) + '''\\n'''\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t0\r\t\t\t\t\t\t\t\t\t\t\t\t\tif self.bpe_ranks is None:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn (vocab_file,)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\twith open(SCREAMING_SNAKE_CASE_ ,\t\t'''w''' ,\t\tencoding='''utf-8'''\t) as writer:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,\t\tkey=lambda SCREAMING_SNAKE_CASE_\t: kv[1]\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif index != token_index:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlogger.warning(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t F\"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive.\"\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ''' Please check that the tokenizer is not corrupted!'''\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\ttoken_index\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twriter.write(''' '''.join(SCREAMING_SNAKE_CASE_\t) + '''\\n'''\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tindex += 1\r\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn (vocab_file, merges_file)\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":328,"string":"328"},"style_context":{"kind":"string","value":"\rimport multiprocessing\rfrom typing import TYPE_CHECKING, Optional, Union\r\rfrom .. import Dataset, Features, config\rfrom ..formatting import query_table\rfrom ..packaged_modules.sql.sql import Sql\rfrom ..utils import logging\rfrom .abc import AbstractDatasetInputStream\r\r\rif TYPE_CHECKING:\r\t\t\t\timport sqlitea\r\r\t\t\t\timport sqlalchemy\r\r\r\r\r\r\rclass \t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t(\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE_\t\t\t):\r\r\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\t\t\t\t\t\t\tdef __init__( self ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_ = None ,\t\tSCREAMING_SNAKE_CASE_ = None ,\t\tSCREAMING_SNAKE_CASE_ = False ,\t\t**SCREAMING_SNAKE_CASE_ ,\t\t)-> Optional[int]:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(features=SCREAMING_SNAKE_CASE_ ,\t\tcache_dir=SCREAMING_SNAKE_CASE_ ,\t\tkeep_in_memory=SCREAMING_SNAKE_CASE_ ,\t\t**SCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tSql(\r\t\t\t\t\t\t\t\t\t\t\t\t\t cache_dir=SCREAMING_SNAKE_CASE_ ,\t\tfeatures=SCREAMING_SNAKE_CASE_ ,\t\tsql=SCREAMING_SNAKE_CASE_ ,\t\tcon=SCREAMING_SNAKE_CASE_ ,\t\t**SCREAMING_SNAKE_CASE_ ,\t\t)\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self\t)-> Any:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tNone\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tNone\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tNone\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tNone\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tself.builder.download_and_prepare(\r\t\t\t\t\t\t\t\t\t\t\t\t\t download_config=SCREAMING_SNAKE_CASE_ ,\t\tdownload_mode=SCREAMING_SNAKE_CASE_ ,\t\tverification_mode=SCREAMING_SNAKE_CASE_ ,\t\tbase_path=SCREAMING_SNAKE_CASE_ ,\t\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t# Build dataset for splits\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tself.builder.as_dataset(\r\t\t\t\t\t\t\t\t\t\t\t\t\t split='''train''' ,\t\tverification_mode=SCREAMING_SNAKE_CASE_ ,\t\tin_memory=self.keep_in_memory\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn dataset\r\r\r\r\r\r\rclass \t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t:\r\r\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\t\t\t\t\t\t\tdef __init__( self ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_ = None ,\t\tSCREAMING_SNAKE_CASE_ = None ,\t\t**SCREAMING_SNAKE_CASE_ ,\t\t)-> List[str]:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif num_proc is not None and num_proc <= 0:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(F\"num_proc {num_proc} must be an integer > 0.\"\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tdataset\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tname\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tcon\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tbatch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tnum_proc\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tto_sql_kwargs\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self\t)-> int:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tself.to_sql_kwargs.pop('''sql''' ,\t\tSCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tself.to_sql_kwargs.pop('''con''' ,\t\tSCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tself.to_sql_kwargs.pop('''index''' ,\t\tSCREAMING_SNAKE_CASE_\t)\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tself._write(index=SCREAMING_SNAKE_CASE_ ,\t\t**self.to_sql_kwargs\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn written\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_\t)-> Dict:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t\t__UpperCamelCase =\targs\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t{**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tquery_table(\r\t\t\t\t\t\t\t\t\t\t\t\t\t table=self.dataset.data ,\t\tkey=slice(SCREAMING_SNAKE_CASE_ ,\t\toffset + self.batch_size\t) ,\t\tindices=self.dataset._indices ,\t\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tbatch.to_pandas()\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\tdf.to_sql(self.name ,\t\tself.con ,\t\tindex=SCREAMING_SNAKE_CASE_ ,\t\t**SCREAMING_SNAKE_CASE_\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn num_rows or len(SCREAMING_SNAKE_CASE_\t)\r\r\r\r\t\t\t\t\t\t\tdef \t\t\tA__\t\t\t\t\t\t( self ,\t\tSCREAMING_SNAKE_CASE_ ,\t\t**SCREAMING_SNAKE_CASE_\t)-> int:\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase =\t0\r\r\t\t\t\t\t\t\t\t\t\t\t\t\tif self.num_proc is None or self.num_proc == 1:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor offset in logging.tqdm(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t range(0 ,\t\tlen(self.dataset\t) ,\t\tself.batch_size\t) ,\t\tunit='''ba''' ,\t\tdisable=not logging.is_progress_bar_enabled() ,\t\tdesc='''Creating SQL from Arrow format''' ,\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twritten += self._batch_sql((offset, index, to_sql_kwargs)\t)\r\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t\t__UpperCamelCase =\tlen(self.dataset\t), self.batch_size\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith multiprocessing.Pool(self.num_proc\t) as pool:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor num_rows in logging.tqdm(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t pool.imap(\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t self._batch_sql ,\t\t[(offset, index, to_sql_kwargs) for offset in range(0 ,\t\tSCREAMING_SNAKE_CASE_ ,\t\tSCREAMING_SNAKE_CASE_\t)] ,\t\t) ,\t\ttotal=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size ,\t\tunit='''ba''' ,\t\tdisable=not logging.is_progress_bar_enabled() ,\t\tdesc='''Creating SQL from Arrow format''' ,\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twritten += num_rows\r\r\t\t\t\t\t\t\t\t\t\t\t\t\treturn written\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":328,"string":"328"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":279,"cells":{"code":{"kind":"string","value":"\r\r\rfrom typing import TYPE_CHECKING\r\rfrom ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available\r\r\rsnake_case\t\t\t\t\t\t\t:\tUnion[str, Any]\t\t\t\t\t =\t\t\t\t{\r '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''],\r '''tokenization_tapas''': ['''TapasTokenizer'''],\r}\r\rtry:\r\t\t\t\t\t\tif not is_torch_available():\r\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\rexcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\tpass\relse:\r\t\t\t\t\t\tsnake_case\t\t\t\t\t\t\t:\tTuple\t\t\t\t\t =\t\t\t\t[\r\t\t\t\t\t\t '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''',\r\t\t\t\t\t\t '''TapasForMaskedLM''',\r\t\t\t\t\t\t '''TapasForQuestionAnswering''',\r\t\t\t\t\t\t '''TapasForSequenceClassification''',\r\t\t\t\t\t\t '''TapasModel''',\r\t\t\t\t\t\t '''TapasPreTrainedModel''',\r\t\t\t\t\t\t '''load_tf_weights_in_tapas''',\r\t\t\t\t\t\t]\rtry:\r\t\t\t\t\t\tif not is_tf_available():\r\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\rexcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\tpass\relse:\r\t\t\t\t\t\tsnake_case\t\t\t\t\t\t\t:\tList[Any]\t\t\t\t\t =\t\t\t\t[\r\t\t\t\t\t\t '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''',\r\t\t\t\t\t\t '''TFTapasForMaskedLM''',\r\t\t\t\t\t\t '''TFTapasForQuestionAnswering''',\r\t\t\t\t\t\t '''TFTapasForSequenceClassification''',\r\t\t\t\t\t\t '''TFTapasModel''',\r\t\t\t\t\t\t '''TFTapasPreTrainedModel''',\r\t\t\t\t\t\t]\r\r\rif TYPE_CHECKING:\r\t\t\t\t\t\tfrom .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig\r\t\t\t\t\t\tfrom .tokenization_tapas import TapasTokenizer\r\r\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\tif not is_torch_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\t\t\t\t\t\texcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\t\t\t\t\t\tpass\r\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\tfrom .modeling_tapas import (\r\t\t\t\t\t\t\t\t\t\t\t\t TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,\r\t\t\t\t\t\t\t\t\t\t\t\t TapasForMaskedLM,\r\t\t\t\t\t\t\t\t\t\t\t\t TapasForQuestionAnswering,\r\t\t\t\t\t\t\t\t\t\t\t\t TapasForSequenceClassification,\r\t\t\t\t\t\t\t\t\t\t\t\t TapasModel,\r\t\t\t\t\t\t\t\t\t\t\t\t TapasPreTrainedModel,\r\t\t\t\t\t\t\t\t\t\t\t\t load_tf_weights_in_tapas,\r\t\t\t\t\t\t\t\t\t\t\t\t)\r\r\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\tif not is_tf_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\t\t\t\t\t\texcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\t\t\t\t\t\tpass\r\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\tfrom .modeling_tf_tapas import (\r\t\t\t\t\t\t\t\t\t\t\t\t TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST,\r\t\t\t\t\t\t\t\t\t\t\t\t TFTapasForMaskedLM,\r\t\t\t\t\t\t\t\t\t\t\t\t TFTapasForQuestionAnswering,\r\t\t\t\t\t\t\t\t\t\t\t\t TFTapasForSequenceClassification,\r\t\t\t\t\t\t\t\t\t\t\t\t TFTapasModel,\r\t\t\t\t\t\t\t\t\t\t\t\t TFTapasPreTrainedModel,\r\t\t\t\t\t\t\t\t\t\t\t\t)\r\r\relse:\r\t\t\t\t\t\timport sys\r\r\t\t\t\t\t\tsnake_case\t\t\t\t\t\t\t:\tUnion[str, Any]\t\t\t\t\t =\t\t\t\t_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":109,"string":"109"},"style_context":{"kind":"string","value":"\r\r\rfrom __future__ import annotations\r\r\r\r\r\r\rdef \t\t\t\t\t\t\t__lowercase (\t\t\t__lowerCAmelCase\t\t\t\t\t\t\t: list[int] , __lowerCAmelCase\t\t\t\t\t\t\t: int , __lowerCAmelCase\t\t\t\t\t\t\t: int , __lowerCAmelCase\t\t\t\t\t\t\t: int ):\r\t\t\t\t\t\t\tif (direction == 1 and array[indexa] > array[indexa]) or (\r\t\t\t\t\t\t\t direction == 0 and array[indexa] < array[indexa]\r\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\ta__\t\t\t\t, a__\t\t\t\t\t=\t\t\t\t\tarray[indexa], array[indexa]\r\r\r\r\r\r\rdef \t\t\t\t\t\t\t__lowercase (\t\t\t__lowerCAmelCase\t\t\t\t\t\t\t: list[int] , __lowerCAmelCase\t\t\t\t\t\t\t: int , __lowerCAmelCase\t\t\t\t\t\t\t: int , __lowerCAmelCase\t\t\t\t\t\t\t: int ):\r\t\t\t\t\t\t\tif length > 1:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\ta__\t\t\t\t\t=\t\t\t\t\tint(length / 2 )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor i in range(__lowerCAmelCase , low + middle ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcomp_and_swap(__lowerCAmelCase , __lowerCAmelCase , i + middle , __lowerCAmelCase )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tbitonic_merge(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tbitonic_merge(__lowerCAmelCase , low + middle , __lowerCAmelCase , __lowerCAmelCase )\r\r\r\r\r\r\rdef \t\t\t\t\t\t\t__lowercase (\t\t\t__lowerCAmelCase\t\t\t\t\t\t\t: list[int] , __lowerCAmelCase\t\t\t\t\t\t\t: int , __lowerCAmelCase\t\t\t\t\t\t\t: int , __lowerCAmelCase\t\t\t\t\t\t\t: int ):\r\t\t\t\t\t\t\tif length > 1:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\ta__\t\t\t\t\t=\t\t\t\t\tint(length / 2 )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tbitonic_sort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , 1 )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tbitonic_sort(__lowerCAmelCase , low + middle , __lowerCAmelCase , 0 )\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tbitonic_merge(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )\r\r\rif __name__ == \"__main__\":\r\t\t\t\t\t\tsnake_case\t\t\t\t\t\t\t:\tint\t\t\t\t\t =\t\t\t\tinput('''Enter numbers separated by a comma:\\n''').strip()\r\t\t\t\t\t\tsnake_case\t\t\t\t\t\t\t:\tOptional[int]\t\t\t\t\t =\t\t\t\t[int(item.strip()) for item in user_input.split(''',''')]\r\r\t\t\t\t\t\tbitonic_sort(unsorted, 0, len(unsorted), 1)\r\t\t\t\t\t\tprint('''\\nSorted array in ascending order is: ''', end='''''')\r\t\t\t\t\t\tprint(*unsorted, sep=''', ''')\r\r\t\t\t\t\t\tbitonic_merge(unsorted, 0, len(unsorted), 0)\r\t\t\t\t\t\tprint('''Sorted array in descending order is: ''', end='''''')\r\t\t\t\t\t\tprint(*unsorted, sep=''', ''')\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":109,"string":"109"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":280,"cells":{"code":{"kind":"string","value":"\n\n'''simple docstring'''\nimport os\nfrom pathlib import Path\nfrom unittest.mock import patch\n\nimport pytest\nimport zstandard as zstd\n\nfrom datasets.download.download_config import DownloadConfig\nfrom datasets.utils.file_utils import (\n OfflineModeIsEnabled,\n cached_path,\n fsspec_get,\n fsspec_head,\n ftp_get,\n ftp_head,\n get_from_cache,\n http_get,\n http_head,\n)\n\n\n_snake_case = '\\\\n Text data.\\n Second line of data.'\n\n_snake_case = 'file'\n\n\n\n\n\n\n\n@pytest.fixture(scope=\"session\" )\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tList[Any]:\n _lowercase\t\t\t: List[Any]\t\t\t = tmp_path_factory.mktemp(\"data\" ) / (FILE_PATH + \".zstd\")\n _lowercase\t\t\t: str\t\t\t = bytes(A__\t\t,\t\t\t\t\t\t\t\"utf-8\" )\n with zstd.open(A__\t\t,\t\t\t\t\t\t\t\"wb\" ) as f:\n f.write(A__ )\n return path\n\n\n\n\n\n\n\n@pytest.fixture\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tOptional[Any]:\n with open(os.path.join(tmpfs.local_root_dir\t\t,\t\t\t\t\t\t\tA__ )\t\t,\t\t\t\t\t\t\t\"w\" ) as f:\n f.write(A__ )\n return FILE_PATH\n\n\n\n\n\n\n\n@pytest.mark.parametrize(\"compression_format\"\t\t,\t\t\t\t\t\t\t[\"gzip\", \"xz\", \"zstd\"] )\ndef \t\t\t\t\t_A\t\t(\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case )\t\t\t->\tList[str]:\n _lowercase\t\t\t: List[str]\t\t\t = {\"gzip\": gz_file, \"xz\": xz_file, \"zstd\": zstd_path}\n _lowercase\t\t\t: List[Any]\t\t\t = input_paths[compression_format]\n _lowercase\t\t\t: int\t\t\t = tmp_path / \"cache\"\n _lowercase\t\t\t: Optional[int]\t\t\t = DownloadConfig(cache_dir=A__\t\t,\t\t\t\t\t\t\textract_compressed_file=A__ )\n _lowercase\t\t\t: str\t\t\t = cached_path(A__\t\t,\t\t\t\t\t\t\tdownload_config=A__ )\n with open(A__ ) as f:\n _lowercase\t\t\t: Any\t\t\t = f.read()\n with open(A__ ) as f:\n _lowercase\t\t\t: List[Any]\t\t\t = f.read()\n assert extracted_file_content == expected_file_content\n\n\n\n\n\n\n\n@pytest.mark.parametrize(\"default_extracted\"\t\t,\t\t\t\t\t\t\t[True, False] )\n@pytest.mark.parametrize(\"default_cache_dir\"\t\t,\t\t\t\t\t\t\t[True, False] )\ndef \t\t\t\t\t_A\t\t(\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case\t\t,\t\t\t\t\t\t\tsnake_case )\t\t\t->\tList[str]:\n _lowercase\t\t\t: Optional[Any]\t\t\t = \"custom_cache\"\n _lowercase\t\t\t: str\t\t\t = \"custom_extracted_dir\"\n _lowercase\t\t\t: Dict\t\t\t = tmp_path / \"custom_extracted_path\"\n if default_extracted:\n _lowercase\t\t\t: Dict\t\t\t = (\"downloads\" if default_cache_dir else custom_cache_dir, \"extracted\")\n else:\n monkeypatch.setattr(\"datasets.config.EXTRACTED_DATASETS_DIR\"\t\t,\t\t\t\t\t\t\tA__ )\n monkeypatch.setattr(\"datasets.config.EXTRACTED_DATASETS_PATH\"\t\t,\t\t\t\t\t\t\tstr(A__ ) )\n _lowercase\t\t\t: List[Any]\t\t\t = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)\n\n _lowercase\t\t\t: str\t\t\t = xz_file\n _lowercase\t\t\t: Optional[Any]\t\t\t = (\n DownloadConfig(extract_compressed_file=A__ )\n if default_cache_dir\n else DownloadConfig(cache_dir=tmp_path / custom_cache_dir\t\t,\t\t\t\t\t\t\textract_compressed_file=A__ )\n )\n _lowercase\t\t\t: Tuple\t\t\t = cached_path(A__\t\t,\t\t\t\t\t\t\tdownload_config=A__ )\n assert Path(A__ ).parent.parts[-2:] == expected\n\n\n\n\n\n\n\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tAny:\n # absolute path\n _lowercase\t\t\t: Union[str, Any]\t\t\t = str(Path(A__ ).resolve() )\n assert cached_path(A__ ) == text_file\n # relative path\n _lowercase\t\t\t: Dict\t\t\t = str(Path(A__ ).resolve().relative_to(Path(os.getcwd() ) ) )\n assert cached_path(A__ ) == text_file\n\n\n\n\n\n\n\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tint:\n # absolute path\n _lowercase\t\t\t: Dict\t\t\t = str(tmp_path.resolve() / \"__missing_file__.txt\" )\n with pytest.raises(A__ ):\n cached_path(A__ )\n # relative path\n _lowercase\t\t\t: Any\t\t\t = \"./__missing_file__.txt\"\n with pytest.raises(A__ ):\n cached_path(A__ )\n\n\n\n\n\n\n\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tAny:\n _lowercase\t\t\t: Union[str, Any]\t\t\t = get_from_cache(F'''tmp://{tmpfs_file}''' )\n with open(A__ ) as f:\n _lowercase\t\t\t: Optional[Any]\t\t\t = f.read()\n assert output_file_content == FILE_CONTENT\n\n\n\n\n\n\n\n@patch(\"datasets.config.HF_DATASETS_OFFLINE\"\t\t,\t\t\t\t\t\t\tA__ )\ndef \t\t\t\t\t_A\t\t(\t)\t\t\t->\tOptional[Any]:\n with pytest.raises(A__ ):\n cached_path(\"https://huggingface.co\" )\n\n\n\n\n\n\n\n@patch(\"datasets.config.HF_DATASETS_OFFLINE\"\t\t,\t\t\t\t\t\t\tA__ )\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tOptional[Any]:\n _lowercase\t\t\t: List[Any]\t\t\t = tmp_path_factory.mktemp(\"data\" ) / \"file.html\"\n with pytest.raises(A__ ):\n http_get(\"https://huggingface.co\"\t\t,\t\t\t\t\t\t\ttemp_file=A__ )\n with pytest.raises(A__ ):\n http_head(\"https://huggingface.co\" )\n\n\n\n\n\n\n\n@patch(\"datasets.config.HF_DATASETS_OFFLINE\"\t\t,\t\t\t\t\t\t\tA__ )\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tOptional[int]:\n _lowercase\t\t\t: str\t\t\t = tmp_path_factory.mktemp(\"data\" ) / \"file.html\"\n with pytest.raises(A__ ):\n ftp_get(\"ftp://huggingface.co\"\t\t,\t\t\t\t\t\t\ttemp_file=A__ )\n with pytest.raises(A__ ):\n ftp_head(\"ftp://huggingface.co\" )\n\n\n\n\n\n\n\n@patch(\"datasets.config.HF_DATASETS_OFFLINE\"\t\t,\t\t\t\t\t\t\tA__ )\ndef \t\t\t\t\t_A\t\t(\tsnake_case )\t\t\t->\tOptional[Any]:\n _lowercase\t\t\t: List[str]\t\t\t = tmp_path_factory.mktemp(\"data\" ) / \"file.html\"\n with pytest.raises(A__ ):\n fsspec_get(\"s3://huggingface.co\"\t\t,\t\t\t\t\t\t\ttemp_file=A__ )\n with pytest.raises(A__ ):\n fsspec_head(\"s3://huggingface.co\" )\n\n\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":250,"string":"250"},"style_context":{"kind":"string","value":"\n\n\n\n\n\n\n\"\"\"simple docstring\"\"\"\nfrom typing import List, Union\n\nfrom ..utils import (\n add_end_docstrings,\n is_tf_available,\n is_torch_available,\n is_vision_available,\n logging,\n requires_backends,\n)\nfrom .base import PIPELINE_INIT_ARGS, Pipeline\n\n\nif is_vision_available():\n\t\t\tfrom PIL import Image\n\n\t\t\tfrom ..image_utils import load_image\n\nif is_tf_available():\n\t\t\timport tensorflow as tf\n\n\t\t\tfrom ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\n\t\t\tfrom ..tf_utils import stable_softmax\n\nif is_torch_available():\n\t\t\tfrom ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\n\nlowerCamelCase_\t\t\t\t\t= logging.get_logger(__name__)\n\n\n\n\n\n\n\n@add_end_docstrings(__A )\nclass \t\t\tUpperCamelCase_ (__A ):\n\n\n\n\n\n\tdef __init__( self\t\t\t\t\t: int\t,\t*lowerCAmelCase_\t\t\t\t\t: Tuple\t,\t**lowerCAmelCase_\t\t\t\t\t: List[str]\t\t\t\t\t\t)\t\t\t\t\t\t->\t\t\tOptional[Any]:\n\t\t\t\tsuper().__init__(*lowerCAmelCase_\t,\t**lowerCAmelCase_\t\t\t\t\t\t)\n\t\t\t\trequires_backends(self\t,\t\"vision\"\t\t\t\t\t\t)\n\t\t\t\tself.check_model_type(\n\t\t\t\t TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\n\t\t\t\t if self.framework == \"tf\"\n\t\t\t\t else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING\t\t\t\t\t\t)\n\n\n\n\n\n\tdef _SCREAMING_SNAKE_CASE ( self\t\t\t\t\t: str\t,\tlowerCAmelCase_\t\t\t\t\t: Optional[int]=None\t\t\t\t\t\t)\t\t\t\t\t\t->\t\t\tList[Any]:\n\t\t\t\tUpperCAmelCase_ : str\t\t\t =\t\t\t\t\t{}\n\t\t\t\tif top_k is not None:\n\t\t\t\t\t\t\tUpperCAmelCase_ : List[str]\t\t\t =\t\t\t\t\ttop_k\n\t\t\t\treturn {}, {}, postprocess_params\n\n\n\n\n\n\tdef __call__( self\t\t\t\t\t: str\t,\tlowerCAmelCase_\t\t\t\t\t: Union[str, List[str], \"Image.Image\", List[\"Image.Image\"]]\t,\t**lowerCAmelCase_\t\t\t\t\t: Any\t\t\t\t\t\t)\t\t\t\t\t\t->\t\t\tTuple:\n\t\t\t\treturn super().__call__(lowerCAmelCase_\t,\t**lowerCAmelCase_\t\t\t\t\t\t)\n\n\n\n\n\n\tdef _SCREAMING_SNAKE_CASE ( self\t\t\t\t\t: str\t,\tlowerCAmelCase_\t\t\t\t\t: str\t\t\t\t\t\t)\t\t\t\t\t\t->\t\t\tAny:\n\t\t\t\tUpperCAmelCase_ : Tuple\t\t\t =\t\t\t\t\tload_image(lowerCAmelCase_\t\t\t\t\t\t)\n\t\t\t\tUpperCAmelCase_ : Dict\t\t\t =\t\t\t\t\tself.image_processor(images=lowerCAmelCase_\t,\treturn_tensors=self.framework\t\t\t\t\t\t)\n\t\t\t\treturn model_inputs\n\n\n\n\n\n\tdef _SCREAMING_SNAKE_CASE ( self\t\t\t\t\t: List[Any]\t,\tlowerCAmelCase_\t\t\t\t\t: Dict\t\t\t\t\t\t)\t\t\t\t\t\t->\t\t\tstr:\n\t\t\t\tUpperCAmelCase_ : Any\t\t\t =\t\t\t\t\tself.model(**lowerCAmelCase_\t\t\t\t\t\t)\n\t\t\t\treturn model_outputs\n\n\n\n\n\n\tdef _SCREAMING_SNAKE_CASE ( self\t\t\t\t\t: Tuple\t,\tlowerCAmelCase_\t\t\t\t\t: Union[str, Any]\t,\tlowerCAmelCase_\t\t\t\t\t: Optional[int]=5\t\t\t\t\t\t)\t\t\t\t\t\t->\t\t\tAny:\n\t\t\t\tif top_k > self.model.config.num_labels:\n\t\t\t\t\t\t\tUpperCAmelCase_ : int\t\t\t =\t\t\t\t\tself.model.config.num_labels\n\n\t\t\t\tif self.framework == \"pt\":\n\t\t\t\t\t\t\tUpperCAmelCase_ : str\t\t\t =\t\t\t\t\tmodel_outputs.logits.softmax(-1\t\t\t\t\t\t)[0]\n\t\t\t\t\t\t\tUpperCAmelCase_ ,\tUpperCAmelCase_ : Tuple\t\t\t =\t\t\t\t\tprobs.topk(lowerCAmelCase_\t\t\t\t\t\t)\n\t\t\t\telif self.framework == \"tf\":\n\t\t\t\t\t\t\tUpperCAmelCase_ : str\t\t\t =\t\t\t\t\tstable_softmax(model_outputs.logits\t,\taxis=-1\t\t\t\t\t\t)[0]\n\t\t\t\t\t\t\tUpperCAmelCase_ : Union[str, Any]\t\t\t =\t\t\t\t\ttf.math.top_k(lowerCAmelCase_\t,\tk=lowerCAmelCase_\t\t\t\t\t\t)\n\t\t\t\t\t\t\tUpperCAmelCase_ ,\tUpperCAmelCase_ : List[Any]\t\t\t =\t\t\t\t\ttopk.values.numpy(), topk.indices.numpy()\n\t\t\t\telse:\n\t\t\t\t\t\t\traise ValueError(f\"\"\"Unsupported framework: {self.framework}\"\"\"\t\t\t\t\t\t)\n\n\t\t\t\tUpperCAmelCase_ : int\t\t\t =\t\t\t\t\tscores.tolist()\n\t\t\t\tUpperCAmelCase_ : Optional[Any]\t\t\t =\t\t\t\t\tids.tolist()\n\t\t\t\treturn [{\"score\": score, \"label\": self.model.config.idalabel[_id]} for score, _id in zip(lowerCAmelCase_\t,\tlowerCAmelCase_\t\t\t\t\t\t)]\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":268,"string":"268"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":281,"cells":{"code":{"kind":"string","value":"\r\r\r\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\rfrom collections.abc import Callable\rfrom math import pi, sqrt\rfrom random import uniform\rfrom statistics import mean\rdef a__ ( SCREAMING_SNAKE_CASE : int ):\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r def is_in_circle(SCREAMING_SNAKE_CASE : float ,\t\t\t\tSCREAMING_SNAKE_CASE : float ) -> bool:\r lowerCAmelCase\t\t\t\t\t:\t\t\t\t\tAny\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tsqrt((x**2) + (y**2) )\r # Our circle has a radius of 1, so a distance\r # greater than 1 would land outside the circle.\r return distance_from_centre <= 1\r\r # The proportion of guesses that landed in the circle\r lowerCAmelCase\t\t\t\t\t:\t\t\t\t\tAny\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tmean(\r int(is_in_circle(uniform(-1.0 ,\t\t\t\t1.0 ) ,\t\t\t\tuniform(-1.0 ,\t\t\t\t1.0 ) ) )\r for _ in range(SCREAMING_SNAKE_CASE ) )\r # The ratio of the area for circle to square is pi/4.\r lowerCAmelCase\t\t\t\t\t:\t\t\t\t\tList[str]\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tproportion * 4\r print(f\"\"\"The estimated value of pi is {pi_estimate}\"\"\" )\r print(f\"\"\"The numpy value of pi is {pi}\"\"\" )\r print(f\"\"\"The total error is {abs(pi - pi_estimate )}\"\"\" )\rdef a__ ( SCREAMING_SNAKE_CASE : int ,\t\t\t\tSCREAMING_SNAKE_CASE : Callable[[float], float] ,\t\t\t\tSCREAMING_SNAKE_CASE : float = 0.0 ,\t\t\t\tSCREAMING_SNAKE_CASE : float = 1.0 ,\t\t\t\t):\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r return mean(\r function_to_integrate(uniform(SCREAMING_SNAKE_CASE ,\t\t\t\tSCREAMING_SNAKE_CASE ) ) for _ in range(SCREAMING_SNAKE_CASE ) ) * (max_value - min_value)\rdef a__ ( SCREAMING_SNAKE_CASE : int ,\t\t\t\tSCREAMING_SNAKE_CASE : float = 0.0 ,\t\t\t\tSCREAMING_SNAKE_CASE : float = 1.0 ):\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r def identity_function(SCREAMING_SNAKE_CASE : float ) -> float:\r return x\r\r lowerCAmelCase\t\t\t\t\t:\t\t\t\t\tUnion[str, Any]\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tarea_under_curve_estimator(\r SCREAMING_SNAKE_CASE ,\t\t\t\tSCREAMING_SNAKE_CASE ,\t\t\t\tSCREAMING_SNAKE_CASE ,\t\t\t\tSCREAMING_SNAKE_CASE )\r lowerCAmelCase\t\t\t\t\t:\t\t\t\t\tOptional[int]\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\t(max_value * max_value - min_value * min_value) / 2\r\r print(\"******************\" )\r print(f\"\"\"Estimating area under y=x where x varies from {min_value} to {max_value}\"\"\" )\r print(f\"\"\"Estimated value is {estimated_value}\"\"\" )\r print(f\"\"\"Expected value is {expected_value}\"\"\" )\r print(f\"\"\"Total error is {abs(estimated_value - expected_value )}\"\"\" )\r print(\"******************\" )\rdef a__ ( SCREAMING_SNAKE_CASE : int ):\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r def function_to_integrate(SCREAMING_SNAKE_CASE : float ) -> float:\r return sqrt(4.0 - x * x )\r\r lowerCAmelCase\t\t\t\t\t:\t\t\t\t\tDict\t\t\t\t\t\t\t\t=\t\t\t\t\t\t\tarea_under_curve_estimator(\r SCREAMING_SNAKE_CASE ,\t\t\t\tSCREAMING_SNAKE_CASE ,\t\t\t\t0.0 ,\t\t\t\t2.0 )\r\r print(\"******************\" )\r print(\"Estimating pi using area_under_curve_estimator\" )\r print(f\"\"\"Estimated value is {estimated_value}\"\"\" )\r print(f\"\"\"Expected value is {pi}\"\"\" )\r print(f\"\"\"Total error is {abs(estimated_value - pi )}\"\"\" )\r print(\"******************\" )\r\r\rif __name__ == \"__main__\":\r import doctest\r\r doctest.testmod()\r\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":133,"string":"133"},"style_context":{"kind":"string","value":"\r\r\r\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\rimport re\r\rfrom filelock import FileLock\r\r\rtry:\r import nltk\r\r lowerCAmelCase__\t\t\t\t = True\rexcept (ImportError, ModuleNotFoundError):\r lowerCAmelCase__\t\t\t\t = False\r\rif NLTK_AVAILABLE:\r with FileLock('''.lock''') as lock:\r nltk.download('''punkt''', quiet=True)\rdef a__ ( SCREAMING_SNAKE_CASE : str ):\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r re.sub(\"\" ,\t\t\t\t\"\" ,\t\t\t\tSCREAMING_SNAKE_CASE ) # remove pegasus newline char\r assert NLTK_AVAILABLE, \"nltk must be installed to separate newlines between sentences. (pip install nltk)\"\r return \"\\n\".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE ) )\r\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":133,"string":"133"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":282,"cells":{"code":{"kind":"string","value":"\r\r\r\r'''simple docstring'''\r\r\r\r\r\r\rimport torch\r\rfrom diffusers import DDPMScheduler\r\rfrom .test_schedulers import SchedulerCommonTest\r\r\r\rclass \t\t\t\t\t\t\tlowercase ( _lowerCamelCase\t\t\t\t):\r\r\r \"\"\"simple docstring\"\"\"\r\r\r UpperCAmelCase\t\t\t\t\t\t\t= (DDPMScheduler,)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself ,**a_\t\t\t\t\t\t\t)\t\t-> List[str]:\r _UpperCAmelCase :\t\t\t\t\t\tList[str]\t\t\t = {\r \"\"\"num_train_timesteps\"\"\": 1_000,\r \"\"\"beta_start\"\"\": 0.0001,\r \"\"\"beta_end\"\"\": 0.02,\r \"\"\"beta_schedule\"\"\": \"\"\"linear\"\"\",\r \"\"\"variance_type\"\"\": \"\"\"fixed_small\"\"\",\r \"\"\"clip_sample\"\"\": True,\r }\r\r config.update(**a_\t\t\t\t\t\t\t)\r return config\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Any:\r for timesteps in [1, 5, 100, 1_000]:\r self.check_over_configs(num_train_timesteps=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Optional[Any]:\r for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] ,[0.002, 0.02, 0.2, 2]\t\t\t\t\t\t\t):\r self.check_over_configs(beta_start=a_ ,beta_end=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Tuple:\r for schedule in [\"linear\", \"squaredcos_cap_v2\"]:\r self.check_over_configs(beta_schedule=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Optional[Any]:\r for variance in [\"fixed_small\", \"fixed_large\", \"other\"]:\r self.check_over_configs(variance_type=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> str:\r for clip_sample in [True, False]:\r self.check_over_configs(clip_sample=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> int:\r self.check_over_configs(thresholding=a_\t\t\t\t\t\t\t)\r for threshold in [0.5, 1.0, 2.0]:\r for prediction_type in [\"epsilon\", \"sample\", \"v_prediction\"]:\r self.check_over_configs(\r thresholding=a_ ,prediction_type=a_ ,sample_max_value=a_ ,)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Optional[Any]:\r for prediction_type in [\"epsilon\", \"sample\", \"v_prediction\"]:\r self.check_over_configs(prediction_type=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Optional[Any]:\r for t in [0, 500, 999]:\r self.check_over_forward(time_step=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Any:\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = self.scheduler_classes[0]\r _UpperCAmelCase :\t\t\t\t\t\tint\t\t\t = self.get_scheduler_config()\r _UpperCAmelCase :\t\t\t\t\t\tOptional[Any]\t\t\t = scheduler_class(**a_\t\t\t\t\t\t\t)\r\r assert torch.sum(torch.abs(scheduler._get_variance(0\t\t\t\t\t\t\t) - 0.0\t\t\t\t\t\t\t)\t\t\t\t\t\t\t) < 1E-5\r assert torch.sum(torch.abs(scheduler._get_variance(487\t\t\t\t\t\t\t) - 0.0_0979\t\t\t\t\t\t\t)\t\t\t\t\t\t\t) < 1E-5\r assert torch.sum(torch.abs(scheduler._get_variance(999\t\t\t\t\t\t\t) - 0.02\t\t\t\t\t\t\t)\t\t\t\t\t\t\t) < 1E-5\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Optional[int]:\r _UpperCAmelCase :\t\t\t\t\t\tDict\t\t\t = self.scheduler_classes[0]\r _UpperCAmelCase :\t\t\t\t\t\tList[Any]\t\t\t = self.get_scheduler_config()\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = scheduler_class(**a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tList[Any]\t\t\t = len(a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tOptional[Any]\t\t\t = self.dummy_model()\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = self.dummy_sample_deter\r _UpperCAmelCase :\t\t\t\t\t\tOptional[int]\t\t\t = torch.manual_seed(0\t\t\t\t\t\t\t)\r\r for t in reversed(range(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t):\r # 1. predict noise residual\r _UpperCAmelCase :\t\t\t\t\t\tList[Any]\t\t\t = model(a_ ,a_\t\t\t\t\t\t\t)\r\r # 2. predict previous mean of sample x_t-1\r _UpperCAmelCase :\t\t\t\t\t\tUnion[str, Any]\t\t\t = scheduler.step(a_ ,a_ ,a_ ,generator=a_\t\t\t\t\t\t\t).prev_sample\r\r # if t > 0:\r # noise = self.dummy_sample_deter\r # variance = scheduler.get_variance(t) ** (0.5) * noise\r #\r # sample = pred_prev_sample + variance\r _UpperCAmelCase :\t\t\t\t\t\tstr\t\t\t = pred_prev_sample\r\r _UpperCAmelCase :\t\t\t\t\t\tList[str]\t\t\t = torch.sum(torch.abs(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = torch.mean(torch.abs(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r assert abs(result_sum.item() - 258.9606\t\t\t\t\t\t\t) < 1E-2\r assert abs(result_mean.item() - 0.3372\t\t\t\t\t\t\t) < 1E-3\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Dict:\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = self.scheduler_classes[0]\r _UpperCAmelCase :\t\t\t\t\t\tOptional[int]\t\t\t = self.get_scheduler_config(prediction_type=\"\"\"v_prediction\"\"\"\t\t\t\t\t\t\t)\r _UpperCAmelCase :\t\t\t\t\t\tstr\t\t\t = scheduler_class(**a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = len(a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = self.dummy_model()\r _UpperCAmelCase :\t\t\t\t\t\tDict\t\t\t = self.dummy_sample_deter\r _UpperCAmelCase :\t\t\t\t\t\tOptional[Any]\t\t\t = torch.manual_seed(0\t\t\t\t\t\t\t)\r\r for t in reversed(range(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t):\r # 1. predict noise residual\r _UpperCAmelCase :\t\t\t\t\t\tDict\t\t\t = model(a_ ,a_\t\t\t\t\t\t\t)\r\r # 2. predict previous mean of sample x_t-1\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = scheduler.step(a_ ,a_ ,a_ ,generator=a_\t\t\t\t\t\t\t).prev_sample\r\r # if t > 0:\r # noise = self.dummy_sample_deter\r # variance = scheduler.get_variance(t) ** (0.5) * noise\r #\r # sample = pred_prev_sample + variance\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = pred_prev_sample\r\r _UpperCAmelCase :\t\t\t\t\t\tOptional[Any]\t\t\t = torch.sum(torch.abs(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r _UpperCAmelCase :\t\t\t\t\t\tList[str]\t\t\t = torch.mean(torch.abs(a_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\r\r assert abs(result_sum.item() - 202.0296\t\t\t\t\t\t\t) < 1E-2\r assert abs(result_mean.item() - 0.2631\t\t\t\t\t\t\t) < 1E-3\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> List[Any]:\r _UpperCAmelCase :\t\t\t\t\t\tint\t\t\t = self.scheduler_classes[0]\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = self.get_scheduler_config()\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = scheduler_class(**a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = [100, 87, 50, 1, 0]\r\r scheduler.set_timesteps(timesteps=a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tstr\t\t\t = scheduler.timesteps\r\r for i, timestep in enumerate(a_\t\t\t\t\t\t\t):\r if i == len(a_\t\t\t\t\t\t\t) - 1:\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = -1\r else:\r _UpperCAmelCase :\t\t\t\t\t\tUnion[str, Any]\t\t\t = timesteps[i + 1]\r\r _UpperCAmelCase :\t\t\t\t\t\tstr\t\t\t = scheduler.previous_timestep(a_\t\t\t\t\t\t\t)\r _UpperCAmelCase :\t\t\t\t\t\tList[str]\t\t\t = prev_t.item()\r\r self.assertEqual(a_ ,a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Dict:\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = self.scheduler_classes[0]\r _UpperCAmelCase :\t\t\t\t\t\tList[Any]\t\t\t = self.get_scheduler_config()\r _UpperCAmelCase :\t\t\t\t\t\tOptional[int]\t\t\t = scheduler_class(**a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tint\t\t\t = [100, 87, 50, 51, 0]\r\r with self.assertRaises(a_ ,msg=\"\"\"`custom_timesteps` must be in descending order.\"\"\"\t\t\t\t\t\t\t):\r scheduler.set_timesteps(timesteps=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Optional[int]:\r _UpperCAmelCase :\t\t\t\t\t\tList[Any]\t\t\t = self.scheduler_classes[0]\r _UpperCAmelCase :\t\t\t\t\t\tList[str]\t\t\t = self.get_scheduler_config()\r _UpperCAmelCase :\t\t\t\t\t\tOptional[Any]\t\t\t = scheduler_class(**a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = [100, 87, 50, 1, 0]\r _UpperCAmelCase :\t\t\t\t\t\tAny\t\t\t = len(a_\t\t\t\t\t\t\t)\r\r with self.assertRaises(a_ ,msg=\"\"\"Can only pass one of `num_inference_steps` or `custom_timesteps`.\"\"\"\t\t\t\t\t\t\t):\r scheduler.set_timesteps(num_inference_steps=a_ ,timesteps=a_\t\t\t\t\t\t\t)\r\r\r\r\r\r\r\r def _snake_case (\t\t\t\t\t\t\tself\t\t\t\t\t\t\t)\t\t-> Any:\r _UpperCAmelCase :\t\t\t\t\t\tDict\t\t\t = self.scheduler_classes[0]\r _UpperCAmelCase :\t\t\t\t\t\tTuple\t\t\t = self.get_scheduler_config()\r _UpperCAmelCase :\t\t\t\t\t\tOptional[Any]\t\t\t = scheduler_class(**a_\t\t\t\t\t\t\t)\r\r _UpperCAmelCase :\t\t\t\t\t\tUnion[str, Any]\t\t\t = [scheduler.config.num_train_timesteps]\r\r with self.assertRaises(\r a_ ,msg=\"\"\"`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}\"\"\" ,):\r scheduler.set_timesteps(timesteps=a_\t\t\t\t\t\t\t)\r\r\r\r"},"code_codestyle":{"kind":"number","value":215,"string":"215"},"style_context":{"kind":"string","value":"\r\r\r\r'''simple docstring'''\r\r\r\r\r\r\rfrom __future__ import annotations\r\rimport typing\rfrom collections import Counter\r\r\r\r\rdef snake_case_\t\t\t\t\t( lowerCAmelCase_\t\t)->\t\ttyping.Counter[int]:\r\r\r\r\r\r '''simple docstring'''\r\r\r _UpperCAmelCase :\t\t\t\t\t\ttyping.Counter[int]\t\t\t = Counter()\r for base in range(1 , max_perimeter + 1\t\t):\r for perpendicular in range(lowerCAmelCase_ , max_perimeter + 1\t\t):\r _UpperCAmelCase :\t\t\t\t\t\tList[str]\t\t\t = (base * base + perpendicular * perpendicular) ** 0.5\r if hypotenuse == int(lowerCAmelCase_\t\t):\r _UpperCAmelCase :\t\t\t\t\t\tOptional[Any]\t\t\t = int(base + perpendicular + hypotenuse\t\t)\r if perimeter > max_perimeter:\r continue\r triplets[perimeter] += 1\r return triplets\r\r\r\r\rdef snake_case_\t\t\t\t\t( lowerCAmelCase_ = 1000\t\t)->\t\tint:\r\r\r\r\r\r '''simple docstring'''\r\r\r _UpperCAmelCase :\t\t\t\t\t\tint\t\t\t = pythagorean_triple(lowerCAmelCase_\t\t)\r return triplets.most_common(1\t\t)[0][0]\r\r\rif __name__ == \"__main__\":\r print(f\"\"\"Perimeter {solution()} has maximum solutions\"\"\")\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":215,"string":"215"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":283,"cells":{"code":{"kind":"string","value":"\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\nfrom operator import delitem, getitem, setitem\r\n\r\nimport pytest\r\n\r\nfrom data_structures.hashing.hash_map import HashMap\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: List[str] ) ->\t\t\t\t\tstr:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn getitem, k\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: int\t\t,__a\t\t\t\t: List[Any] ) ->\t\t\t\t\tOptional[int]:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn setitem, k, v\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: Any ) ->\t\t\t\t\tOptional[Any]:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn delitem, k\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: Any\t\t,__a\t\t\t\t: List[str]\t\t,*__a\t\t\t\t: Any ) ->\t\t\t\t\tDict:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\treturn fun(__a\t\t,*__a ), None\r\n\t\t\t\t\texcept Exception as e:\r\n\t\t\t\t\t\t\t\t\t\treturn None, e\r\n\r\n\r\na__\t\t\t\t=\t\t(\r\n _set('''key_a''', '''val_a'''),\r\n _set('''key_b''', '''val_b'''),\r\n)\r\n\r\na__\t\t\t\t=\t\t[\r\n _set('''key_a''', '''val_a'''),\r\n _set('''key_a''', '''val_b'''),\r\n]\r\n\r\na__\t\t\t\t=\t\t[\r\n _set('''key_a''', '''val_a'''),\r\n _set('''key_b''', '''val_b'''),\r\n _del('''key_a'''),\r\n _del('''key_b'''),\r\n _set('''key_a''', '''val_a'''),\r\n _del('''key_a'''),\r\n]\r\n\r\na__\t\t\t\t=\t\t[\r\n _get('''key_a'''),\r\n _del('''key_a'''),\r\n _set('''key_a''', '''val_a'''),\r\n _del('''key_a'''),\r\n _del('''key_a'''),\r\n _get('''key_a'''),\r\n]\r\n\r\na__\t\t\t\t=\t\t[\r\n *[_set(x, x) for x in range(5)], # guaranteed upsize\r\n]\r\n\r\na__\t\t\t\t=\t\t[\r\n *[_set(x, x) for x in range(5)], # guaranteed upsize\r\n *[_del(x) for x in range(5)],\r\n _set('''key_a''', '''val_b'''),\r\n]\r\n\r\n\r\n\r\n@pytest.mark.parametrize(\r\n '''operations'''\t\t,(\r\n pytest.param(_add_items\t\t,id='''add items''' ),\r\n pytest.param(_overwrite_items\t\t,id='''overwrite items''' ),\r\n pytest.param(_delete_items\t\t,id='''delete items''' ),\r\n pytest.param(_access_absent_items\t\t,id='''access absent items''' ),\r\n pytest.param(_add_with_resize_up\t\t,id='''add with resize up''' ),\r\n pytest.param(_add_with_resize_down\t\t,id='''add with resize down''' ),\r\n )\t\t,)\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: int ) ->\t\t\t\t\tint:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\t_a : str \t\t\t\t=\t\tHashMap(initial_block_size=4 )\r\n\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\t{}\r\n\t\t\t\t\tfor _, (fun, *args) in enumerate(__a ):\r\n\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\t_run_operation(__a\t\t,__a\t\t,*__a )\r\n\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\t_run_operation(__a\t\t,__a\t\t,*__a )\r\n\t\t\t\t\t\t\t\t\t\tassert my_res == py_res\r\n\t\t\t\t\t\t\t\t\t\tassert str(__a ) == str(__a )\r\n\t\t\t\t\t\t\t\t\t\tassert set(__a ) == set(__a )\r\n\t\t\t\t\t\t\t\t\t\tassert len(__a ) == len(__a )\r\n\t\t\t\t\t\t\t\t\t\tassert set(my.items() ) == set(py.items() )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( ) ->\t\t\t\t\tOptional[Any]:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\tdef is_public(__a\t\t\t\t: str ) -> bool:\r\n\t\t\t\t\t\t\t\t\t\treturn not name.startswith('''_''' )\r\n\r\n\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\t{name for name in dir({} ) if is_public(__a )}\r\n\t\t\t\t\t_a : Tuple \t\t\t\t=\t\t{name for name in dir(HashMap() ) if is_public(__a )}\r\n\r\n\t\t\t\t\tassert dict_public_names > hash_public_names\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":352,"string":"352"},"style_context":{"kind":"string","value":"\r\n\r\nfrom typing import Dict, Iterable, Optional, Union\r\n\r\nimport numpy as np\r\n\r\nfrom ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict\r\nfrom ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image\r\nfrom ...image_utils import (\r\n IMAGENET_STANDARD_MEAN,\r\n IMAGENET_STANDARD_STD,\r\n ChannelDimension,\r\n ImageInput,\r\n PILImageResampling,\r\n make_list_of_images,\r\n to_numpy_array,\r\n valid_images,\r\n)\r\nfrom ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends\r\n\r\n\r\nif is_vision_available():\r\n\t\t\timport PIL\r\n\r\n# soft dependency\r\nif is_pytesseract_available():\r\n\t\t\timport pytesseract\r\n\r\na__\t\t\t\t=\t\tlogging.get_logger(__name__)\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: Union[str, Any]\t\t,__a\t\t\t\t: str\t\t,__a\t\t\t\t: Union[str, Any] ) ->\t\t\t\t\tList[str]:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\treturn [\r\n\t\t\t\t\t int(1_000 * (box[0] / width) ),\r\n\t\t\t\t\t int(1_000 * (box[1] / height) ),\r\n\t\t\t\t\t int(1_000 * (box[2] / width) ),\r\n\t\t\t\t\t int(1_000 * (box[3] / height) ),\r\n\t\t\t\t\t]\r\n\r\n\r\n\r\ndef __UpperCAmelCase\t\t\t( __a\t\t\t\t: np.ndarray\t\t,__a\t\t\t\t: Optional[str]\t\t,__a\t\t\t\t: Optional[str] ) ->\t\t\t\t\tList[Any]:\r\n\r\n\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\t\t\t\t\t_a : str \t\t\t\t=\t\tto_pil_image(__a )\r\n\t\t\t\t\t_a\t\t\t\t, _a : Optional[Any] \t\t\t\t=\t\tpil_image.size\r\n\t\t\t\t\t_a : Tuple \t\t\t\t=\t\tpytesseract.image_to_data(__a\t\t,lang=__a\t\t,output_type='''dict'''\t\t,config=__a )\r\n\t\t\t\t\t_a\t\t\t\t, _a\t\t\t\t, _a\t\t\t\t, _a\t\t\t\t, _a : List[str] \t\t\t\t=\t\tdata['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height''']\r\n\r\n\t\t\t\t\t# filter empty words and corresponding coordinates\r\n\t\t\t\t\t_a : Dict \t\t\t\t=\t\t[idx for idx, word in enumerate(__a ) if not word.strip()]\r\n\t\t\t\t\t_a : str \t\t\t\t=\t\t[word for idx, word in enumerate(__a ) if idx not in irrelevant_indices]\r\n\t\t\t\t\t_a : List[str] \t\t\t\t=\t\t[coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices]\r\n\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\t[coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices]\r\n\t\t\t\t\t_a : str \t\t\t\t=\t\t[coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices]\r\n\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\t[coord for idx, coord in enumerate(__a ) if idx not in irrelevant_indices]\r\n\r\n\t\t\t\t\t# turn coordinates into (left, top, left+width, top+height) format\r\n\t\t\t\t\t_a : int \t\t\t\t=\t\t[]\r\n\t\t\t\t\tfor x, y, w, h in zip(__a\t\t,__a\t\t,__a\t\t,__a ):\r\n\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\t[x, y, x + w, y + h]\r\n\t\t\t\t\t\t\t\t\t\tactual_boxes.append(__a )\r\n\r\n\t\t\t\t\t# finally, normalize the bounding boxes\r\n\t\t\t\t\t_a : Dict \t\t\t\t=\t\t[]\r\n\t\t\t\t\tfor box in actual_boxes:\r\n\t\t\t\t\t\t\t\t\t\tnormalized_boxes.append(normalize_box(__a\t\t,__a\t\t,__a ) )\r\n\r\n\t\t\t\t\tassert len(__a ) == len(__a ), \"Not as many words as there are bounding boxes\"\r\n\r\n\t\t\t\t\treturn words, normalized_boxes\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass UpperCAmelCase_\t\t( __lowercase ):\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tUpperCAmelCase__\t:\t\t\t\t\t\tOptional[int] = [\"pixel_values\"]\r\n\r\n\r\n\t\t\t\t\t\t\tdef __init__( self\t,\t\t\t\t\t\t\t_a = True\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = PILImageResampling.BILINEAR\t,\t\t\t\t\t\t\t_a = True\t,\t\t\t\t\t\t\t_a = 1 / 2_5_5\t,\t\t\t\t\t\t\t_a = True\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = True\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = \"\"\t,\t\t\t\t\t\t\t**_a\t,\t\t\t\t\t\t\t) -> None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(**_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tsize if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\tget_size_dict(_a\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\tdo_resize\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\tsize\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\tresample\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\tdo_rescale\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\trescale_value\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[Any] \t\t\t\t=\t\tdo_normalize\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\timage_mean if image_mean is not None else IMAGENET_STANDARD_MEAN\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\timage_std if image_std is not None else IMAGENET_STANDARD_STD\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tapply_ocr\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\tocr_lang\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\ttesseract_config\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a = PILImageResampling.BILINEAR\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t**_a\t,\t\t\t\t\t\t\t) -> np.ndarray:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\tget_size_dict(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif \"height\" not in size or \"width\" not in size:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(F\"\"\"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}\"\"\"\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\t(size['''height'''], size['''width'''])\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn resize(_a\t,\t\t\t\t\t\t\tsize=_a\t,\t\t\t\t\t\t\tresample=_a\t,\t\t\t\t\t\t\tdata_format=_a\t,\t\t\t\t\t\t\t**_a\t)\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t**_a\t,\t\t\t\t\t\t\t) -> np.ndarray:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn rescale(_a\t,\t\t\t\t\t\t\tscale=_a\t,\t\t\t\t\t\t\tdata_format=_a\t,\t\t\t\t\t\t\t**_a\t)\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t**_a\t,\t\t\t\t\t\t\t) -> np.ndarray:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn normalize(_a\t,\t\t\t\t\t\t\tmean=_a\t,\t\t\t\t\t\t\tstd=_a\t,\t\t\t\t\t\t\tdata_format=_a\t,\t\t\t\t\t\t\t**_a\t)\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tdef __lowercase ( self\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a=None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = None\t,\t\t\t\t\t\t\t_a = ChannelDimension.FIRST\t,\t\t\t\t\t\t\t**_a\t,\t\t\t\t\t\t\t) -> PIL.Image.Image:\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\tdo_resize if do_resize is not None else self.do_resize\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\tsize if size is not None else self.size\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\tget_size_dict(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tresample if resample is not None else self.resample\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\tdo_rescale if do_rescale is not None else self.do_rescale\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Union[str, Any] \t\t\t\t=\t\trescale_factor if rescale_factor is not None else self.rescale_factor\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\tdo_normalize if do_normalize is not None else self.do_normalize\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\timage_mean if image_mean is not None else self.image_mean\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Tuple \t\t\t\t=\t\timage_std if image_std is not None else self.image_std\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\tapply_ocr if apply_ocr is not None else self.apply_ocr\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : int \t\t\t\t=\t\tocr_lang if ocr_lang is not None else self.ocr_lang\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\ttesseract_config if tesseract_config is not None else self.tesseract_config\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tmake_list_of_images(_a\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif not valid_images(_a\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''torch.Tensor, tf.Tensor or jax.ndarray.'''\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif do_resize and size is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('''Size must be specified if do_resize is True.'''\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif do_rescale and rescale_factor is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('''Rescale factor must be specified if do_rescale is True.'''\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif do_normalize and (image_mean is None or image_std is None):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('''If do_normalize is True, image_mean and image_std must be specified.'''\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t# All transformations expect numpy arrays.\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : Any \t\t\t\t=\t\t[to_numpy_array(_a\t) for image in images]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t# Tesseract OCR to get words + normalized bounding boxes\r\n\t\t\t\t\t\t\t\t\t\t\t\tif apply_ocr:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trequires_backends(self\t,\t\t\t\t\t\t\t'''pytesseract'''\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\t[]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : str \t\t\t\t=\t\t[]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor image in images:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a\t\t\t\t, _a : Union[str, Any] \t\t\t\t=\t\tapply_tesseract(_a\t,\t\t\t\t\t\t\t_a\t,\t\t\t\t\t\t\t_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twords_batch.append(_a\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tboxes_batch.append(_a\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif do_resize:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\t[self.resize(image=_a\t,\t\t\t\t\t\t\tsize=_a\t,\t\t\t\t\t\t\tresample=_a\t) for image in images]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif do_rescale:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[Any] \t\t\t\t=\t\t[self.rescale(image=_a\t,\t\t\t\t\t\t\tscale=_a\t) for image in images]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif do_normalize:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\t[self.normalize(image=_a\t,\t\t\t\t\t\t\tmean=_a\t,\t\t\t\t\t\t\tstd=_a\t) for image in images]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\t[to_channel_dimension_format(_a\t,\t\t\t\t\t\t\t_a\t) for image in images]\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t_a : List[str] \t\t\t\t=\t\tBatchFeature(data={'''pixel_values''': images}\t,\t\t\t\t\t\t\ttensor_type=_a\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif apply_ocr:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : Optional[int] \t\t\t\t=\t\twords_batch\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t_a : List[Any] \t\t\t\t=\t\tboxes_batch\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn data\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":15,"string":"15"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":284,"cells":{"code":{"kind":"string","value":"\n\n\n\n\n\n\n\"\"\"simple docstring\"\"\"\n\n\n\n\n\n\nfrom ...configuration_utils import PretrainedConfig\nfrom ...utils import logging\n\n\nUpperCAmelCase_ : Any \t\t\t= logging.get_logger(__name__)\n\nUpperCAmelCase_ : Any \t\t\t= {\n '''facebook/dpr-ctx_encoder-single-nq-base''': (\n '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json'''\n ),\n '''facebook/dpr-question_encoder-single-nq-base''': (\n '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json'''\n ),\n '''facebook/dpr-reader-single-nq-base''': (\n '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json'''\n ),\n '''facebook/dpr-ctx_encoder-multiset-base''': (\n '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json'''\n ),\n '''facebook/dpr-question_encoder-multiset-base''': (\n '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json'''\n ),\n '''facebook/dpr-reader-multiset-base''': (\n '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json'''\n ),\n}\n\n\n\n\nclass \t\t\t\t\t\t\tlowerCAmelCase__\t\t\t\t(\t\t\tlowercase__ ):\n\n\n\n\n\n\n '''simple docstring'''\n\n __UpperCamelCase\t = \"\"\"dpr\"\"\"\n def __init__(\t\t\t\t\t\tself : Dict\t\t\t\t\t\t,\tlowercase_ : Tuple=30522\t\t\t\t\t\t,\tlowercase_ : Optional[int]=768\t\t\t\t\t\t,\tlowercase_ : Any=12\t\t\t\t\t\t,\tlowercase_ : Optional[Any]=12\t\t\t\t\t\t,\tlowercase_ : Dict=3072\t\t\t\t\t\t,\tlowercase_ : Optional[int]=\"gelu\"\t\t\t\t\t\t,\tlowercase_ : Optional[Any]=0.1\t\t\t\t\t\t,\tlowercase_ : Union[str, Any]=0.1\t\t\t\t\t\t,\tlowercase_ : Optional[int]=512\t\t\t\t\t\t,\tlowercase_ : Optional[int]=2\t\t\t\t\t\t,\tlowercase_ : Optional[int]=0.02\t\t\t\t\t\t,\tlowercase_ : Tuple=1e-12\t\t\t\t\t\t,\tlowercase_ : List[str]=0\t\t\t\t\t\t,\tlowercase_ : Optional[int]=\"absolute\"\t\t\t\t\t\t,\tlowercase_ : int = 0\t\t\t\t\t\t,\t**lowercase_ : Union[str, Any]\t\t\t\t\t\t,\t):\n\n\n\n\n '''simple docstring'''\n\n\n super().__init__(pad_token_id=_A\t\t\t\t\t\t,\t**_A)\n\n SCREAMING_SNAKE_CASE_ : Any \t\t\t\t\t\t=\t\tvocab_size\n SCREAMING_SNAKE_CASE_ : Union[str, Any] \t\t\t\t\t\t=\t\thidden_size\n SCREAMING_SNAKE_CASE_ : Optional[int] \t\t\t\t\t\t=\t\tnum_hidden_layers\n SCREAMING_SNAKE_CASE_ : int \t\t\t\t\t\t=\t\tnum_attention_heads\n SCREAMING_SNAKE_CASE_ : Optional[Any] \t\t\t\t\t\t=\t\thidden_act\n SCREAMING_SNAKE_CASE_ : Union[str, Any] \t\t\t\t\t\t=\t\tintermediate_size\n SCREAMING_SNAKE_CASE_ : Union[str, Any] \t\t\t\t\t\t=\t\thidden_dropout_prob\n SCREAMING_SNAKE_CASE_ : List[Any] \t\t\t\t\t\t=\t\tattention_probs_dropout_prob\n SCREAMING_SNAKE_CASE_ : Any \t\t\t\t\t\t=\t\tmax_position_embeddings\n SCREAMING_SNAKE_CASE_ : Optional[int] \t\t\t\t\t\t=\t\ttype_vocab_size\n SCREAMING_SNAKE_CASE_ : List[str] \t\t\t\t\t\t=\t\tinitializer_range\n SCREAMING_SNAKE_CASE_ : Optional[Any] \t\t\t\t\t\t=\t\tlayer_norm_eps\n SCREAMING_SNAKE_CASE_ : Union[str, Any] \t\t\t\t\t\t=\t\tprojection_dim\n SCREAMING_SNAKE_CASE_ : int \t\t\t\t\t\t=\t\tposition_embedding_type\n\n\n"},"code_codestyle":{"kind":"number","value":91,"string":"91"},"style_context":{"kind":"string","value":"\r\r\r'''simple docstring'''\r\rfrom typing import TYPE_CHECKING\r\rfrom ...utils import (\r OptionalDependencyNotAvailable,\r _LazyModule,\r is_flax_available,\r is_tf_available,\r is_torch_available,\r)\r\r\rlowerCAmelCase :Union[str, Any] \t=\t\t\t{\r '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig''']\r}\r\rtry:\r\t\t\t\t\t\t\tif not is_torch_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\rexcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\tpass\relse:\r\t\t\t\t\t\t\tlowerCAmelCase :str \t=\t\t\t['''VisionEncoderDecoderModel''']\r\rtry:\r\t\t\t\t\t\t\tif not is_tf_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\rexcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\tpass\relse:\r\t\t\t\t\t\t\tlowerCAmelCase :Optional[int] \t=\t\t\t['''TFVisionEncoderDecoderModel''']\r\rtry:\r\t\t\t\t\t\t\tif not is_flax_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\rexcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\tpass\relse:\r\t\t\t\t\t\t\tlowerCAmelCase :Union[str, Any] \t=\t\t\t['''FlaxVisionEncoderDecoderModel''']\r\rif TYPE_CHECKING:\r\t\t\t\t\t\t\tfrom .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig\r\r\t\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not is_torch_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\t\t\t\t\t\t\texcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass\r\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom .modeling_vision_encoder_decoder import VisionEncoderDecoderModel\r\r\t\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not is_tf_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\t\t\t\t\t\t\texcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass\r\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel\r\r\t\t\t\t\t\t\ttry:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tif not is_flax_available():\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\t\t\t\t\t\t\texcept OptionalDependencyNotAvailable:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tpass\r\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t\tfrom .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel\r\relse:\r\t\t\t\t\t\t\timport sys\r\r\t\t\t\t\t\t\tlowerCAmelCase :int \t=\t\t\t_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)"},"style_context_codestyle":{"kind":"number","value":331,"string":"331"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":285,"cells":{"code":{"kind":"string","value":"\r\r\r\r'''simple docstring'''\rfrom ...configuration_utils import PretrainedConfig\rfrom ...utils import logging\r\r\rsnake_case_\t\t\t: Tuple \t= logging.get_logger(__name__)\r\rsnake_case_\t\t\t: str \t= {\r 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json',\r # See all GLPN models at https://huggingface.co/models?filter=glpn\r}\r\r\r\r\r\r\rclass \t\t\t\t\t\t\tlowercase__ (\t\t\t\t\t\t\t__SCREAMING_SNAKE_CASE ):\r\tlowercase__ = \"\"\"glpn\"\"\"\r\r\r\r\r\r\tdef __init__(\t\t\tself : Any\t\t\t,lowerCamelCase__ : Optional[int]=3\t\t\t,lowerCamelCase__ : Tuple=4\t\t\t,lowerCamelCase__ : Optional[Any]=[2, 2, 2, 2]\t\t\t,lowerCamelCase__ : int=[8, 4, 2, 1]\t\t\t,lowerCamelCase__ : Union[str, Any]=[32, 64, 160, 256]\t\t\t,lowerCamelCase__ : Dict=[7, 3, 3, 3]\t\t\t,lowerCamelCase__ : Union[str, Any]=[4, 2, 2, 2]\t\t\t,lowerCamelCase__ : List[Any]=[1, 2, 5, 8]\t\t\t,lowerCamelCase__ : Tuple=[4, 4, 4, 4]\t\t\t,lowerCamelCase__ : Dict=\"gelu\"\t\t\t,lowerCamelCase__ : str=0.0\t\t\t,lowerCamelCase__ : int=0.0\t\t\t,lowerCamelCase__ : Optional[int]=0.0_2\t\t\t,lowerCamelCase__ : Union[str, Any]=0.1\t\t\t,lowerCamelCase__ : str=1E-6\t\t\t,lowerCamelCase__ : Optional[Any]=64\t\t\t,lowerCamelCase__ : List[str]=10\t\t\t,lowerCamelCase__ : Dict=-1\t\t\t,**lowerCamelCase__ : Union[str, Any]\t\t\t,):\r\r\r\r\r\r\r\r\t\t\t\t\t\t\t'''simple docstring'''\r\t\t\t\t\t\t\tsuper().__init__(**UpperCamelCase__\t\t\t)\r\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tDict\t\t\t = num_channels\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tList[str]\t\t\t = num_encoder_blocks\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = depths\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tList[Any]\t\t\t = sr_ratios\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tTuple\t\t\t = hidden_sizes\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tDict\t\t\t = patch_sizes\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tstr\t\t\t = strides\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tDict\t\t\t = mlp_ratios\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = num_attention_heads\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tList[Any]\t\t\t = hidden_act\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tUnion[str, Any]\t\t\t = hidden_dropout_prob\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tint\t\t\t = attention_probs_dropout_prob\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tTuple\t\t\t = initializer_range\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = drop_path_rate\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tList[Any]\t\t\t = layer_norm_eps\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tList[str]\t\t\t = decoder_hidden_size\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tDict\t\t\t = max_depth\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tAny\t\t\t = head_in_index\r\r\r\r"},"code_codestyle":{"kind":"number","value":367,"string":"367"},"style_context":{"kind":"string","value":"\r\r\r\r'''simple docstring'''\rfrom collections import OrderedDict\rfrom typing import Mapping\r\rfrom ...configuration_utils import PretrainedConfig\rfrom ...onnx import OnnxConfig\rfrom ...utils import logging\r\r\rsnake_case_\t\t\t: Optional[int] \t= logging.get_logger(__name__)\r\rsnake_case_\t\t\t: List[Any] \t= {\r 'facebook/xlm-roberta-xl': 'https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json',\r 'facebook/xlm-roberta-xxl': 'https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json',\r # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl\r}\r\r\r\r\r\r\rclass \t\t\t\t\t\t\tlowercase__ (\t\t\t\t\t\t\tlowercase ):\r\tlowercase__ = \"\"\"xlm-roberta-xl\"\"\"\r\r\r\r\r\r\tdef __init__(\t\t\tself : Optional[int]\t\t\t,lowerCamelCase__ : Optional[Any]=250880\t\t\t,lowerCamelCase__ : Tuple=2560\t\t\t,lowerCamelCase__ : Union[str, Any]=36\t\t\t,lowerCamelCase__ : List[str]=32\t\t\t,lowerCamelCase__ : Optional[Any]=10240\t\t\t,lowerCamelCase__ : Tuple=\"gelu\"\t\t\t,lowerCamelCase__ : int=0.1\t\t\t,lowerCamelCase__ : int=0.1\t\t\t,lowerCamelCase__ : Optional[int]=514\t\t\t,lowerCamelCase__ : List[str]=1\t\t\t,lowerCamelCase__ : Dict=0.0_2\t\t\t,lowerCamelCase__ : Any=1E-05\t\t\t,lowerCamelCase__ : Union[str, Any]=1\t\t\t,lowerCamelCase__ : str=0\t\t\t,lowerCamelCase__ : Tuple=2\t\t\t,lowerCamelCase__ : Union[str, Any]=\"absolute\"\t\t\t,lowerCamelCase__ : Optional[Any]=True\t\t\t,lowerCamelCase__ : List[str]=None\t\t\t,**lowerCamelCase__ : Dict\t\t\t,):\r\r\r\r\r\r\r\r\t\t\t\t\t\t\t'''simple docstring'''\r\t\t\t\t\t\t\tsuper().__init__(pad_token_id=lowerCamelCase__\t\t\t,bos_token_id=lowerCamelCase__\t\t\t,eos_token_id=lowerCamelCase__\t\t\t,**lowerCamelCase__\t\t\t)\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[int]\t\t\t = vocab_size\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = hidden_size\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tstr\t\t\t = num_hidden_layers\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tstr\t\t\t = num_attention_heads\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tAny\t\t\t = hidden_act\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tDict\t\t\t = intermediate_size\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[int]\t\t\t = hidden_dropout_prob\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tAny\t\t\t = attention_probs_dropout_prob\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tList[Any]\t\t\t = max_position_embeddings\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tstr\t\t\t = type_vocab_size\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = initializer_range\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[int]\t\t\t = layer_norm_eps\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[int]\t\t\t = position_embedding_type\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = use_cache\r\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = classifier_dropout\r\r\r\r\r\r\rclass \t\t\t\t\t\t\tlowercase__ (\t\t\t\t\t\t\tlowercase ):\r\r\r\r\r\r\t@property\r\tdef UpperCamelCase_ (\t\t\tself : List[Any]\t\t\t):\r\r\r\r\r\r\r\r\t\t\t\t\t\t\t'''simple docstring'''\r\t\t\t\t\t\t\tif self.task == \"multiple-choice\":\r\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase :\t\tUnion[str, Any]\t\t\t = {0: 'batch', 1: 'choice', 2: 'sequence'}\r\t\t\t\t\t\t\telse:\r\t\t\t\t\t\t\t\t\t\t\t\t\t_UpperCamelCase :\t\tOptional[Any]\t\t\t = {0: 'batch', 1: 'sequence'}\r\t\t\t\t\t\t\treturn OrderedDict(\r\t\t\t\t\t\t\t [\r\t\t\t\t\t\t\t ('input_ids', dynamic_axis),\r\t\t\t\t\t\t\t ('attention_mask', dynamic_axis),\r\t\t\t\t\t\t\t ]\t\t\t)\r\r\r"},"style_context_codestyle":{"kind":"number","value":236,"string":"236"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":286,"cells":{"code":{"kind":"string","value":"\r\r'''simple docstring'''\r\r# Function to print upper half of diamond (pyramid)\r\r\r\r\r\rdef lowercase\t\t\t\t\t( __magic_name__\t\t\t\t\t\t\t):\r\r\r\r\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\r\t\t\t\t\tfor i in range(0 , __magic_name__\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\tfor _ in range(0 , n - i - 1\t\t\t\t\t\t\t): # printing spaces\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint(\" \" , end=\"\"\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\tfor _ in range(0 , i + 1\t\t\t\t\t\t\t): # printing stars\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint(\"* \" , end=\"\"\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\tprint()\r\r\r\r\r\rdef lowercase\t\t\t\t\t( __magic_name__\t\t\t\t\t\t\t):\r\r\r\r\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\r\t\t\t\t\tfor i in range(__magic_name__ , 0 , -1\t\t\t\t\t\t\t):\r\t\t\t\t\t\t\t\t\t\tfor _ in range(__magic_name__ , 0 , -1\t\t\t\t\t\t\t): # printing stars\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint(\"* \" , end=\"\"\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\tprint()\r\t\t\t\t\t\t\t\t\t\tfor _ in range(n - i + 1 , 0 , -1\t\t\t\t\t\t\t): # printing spaces\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tprint(\" \" , end=\"\"\t\t\t\t\t\t\t)\r\r\r\r\r\rdef lowercase\t\t\t\t\t( __magic_name__\t\t\t\t\t\t\t):\r\r\r\r\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\r\t\t\t\t\tif n <= 0:\r\t\t\t\t\t\t\t\t\t\tprint(\" ... .... nothing printing :(\"\t\t\t\t\t\t\t)\r\t\t\t\t\t\t\t\t\t\treturn\r\t\t\t\t\tfloyd(__magic_name__\t\t\t\t\t\t\t) # upper half\r\t\t\t\t\treverse_floyd(__magic_name__\t\t\t\t\t\t\t) # lower half\r\r\rif __name__ == \"__main__\":\r\t\t\t\tprint(R\"| /\\ | |- | |- |--| |\\ /| |-\")\r\t\t\t\tprint(R\"|/ \\| |- |_ |_ |__| | \\/ | |_\")\r\t\t\t\ta :\t\t\tint = 1\r\t\t\t\twhile K:\r\t\t\t\t\t\t\t\ta :\t\t\tTuple = int(input(\"enter the number and , and see the magic : \"))\r\t\t\t\t\t\t\t\tprint()\r\t\t\t\t\t\t\t\tpretty_print(user_number)\r\t\t\t\t\t\t\t\ta :\t\t\tstr = int(input(\"press 0 to exit... and 1 to continue...\"))\r\r\t\t\t\tprint(\"Good Bye...\")\r"},"code_codestyle":{"kind":"number","value":311,"string":"311"},"style_context":{"kind":"string","value":"\r\r'''simple docstring'''\r\rimport jax.numpy as jnp\r\rfrom ...utils import logging\rfrom ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel\rfrom .configuration_mta import MTaConfig\r\r\ra :\t\t\tOptional[Any] = logging.get_logger(__name__)\r\ra :\t\t\tTuple = \"T5Config\"\r\r\r\r\r\rdef lowercase\t\t\t\t\t( __magic_name__ , __magic_name__ , __magic_name__\t\t\t\t\t\t\t):\r\r\r\r\t\t\t\t\t'''simple docstring'''\r\r\r\r\r\r\r\r\t\t\t\t\tUpperCAmelCase\t\t:\t\t\t\t\t\t\tAny \t\t\t\t\t= jnp.zeros_like(__magic_name__\t\t\t\t\t\t\t)\r\t\t\t\t\tUpperCAmelCase\t\t:\t\t\t\t\t\t\tOptional[int] \t\t\t\t\t= shifted_input_ids.at[:, 1:].set(input_ids[:, :-1]\t\t\t\t\t\t\t)\r\t\t\t\t\tUpperCAmelCase\t\t:\t\t\t\t\t\t\tstr \t\t\t\t\t= shifted_input_ids.at[:, 0].set(__magic_name__\t\t\t\t\t\t\t)\r\r\t\t\t\t\tUpperCAmelCase\t\t:\t\t\t\t\t\t\tAny \t\t\t\t\t= jnp.where(shifted_input_ids == -100 , __magic_name__ , __magic_name__\t\t\t\t\t\t\t)\r\t\t\t\t\treturn shifted_input_ids\r\r\r\r\r\r\r\rclass UpperCamelCase__ ( lowercase__ ):\r\r\r\t\t\"\"\"simple docstring\"\"\"\r\r\t\tSCREAMING_SNAKE_CASE__ :\tint =\t\t\t\t\t\t\t\"mt5\"\r\t\tSCREAMING_SNAKE_CASE__ :\tDict =\t\t\t\t\t\t\tMTaConfig\r\r\r\r\r\r\r\rclass UpperCamelCase__ ( lowercase__ ):\r\r\r\t\t\"\"\"simple docstring\"\"\"\r\r\t\tSCREAMING_SNAKE_CASE__ :\tint =\t\t\t\t\t\t\t\"mt5\"\r\t\tSCREAMING_SNAKE_CASE__ :\tstr =\t\t\t\t\t\t\tMTaConfig\r\r\r\r\r\r\r\rclass UpperCamelCase__ ( lowercase__ ):\r\r\r\t\t\"\"\"simple docstring\"\"\"\r\r\t\tSCREAMING_SNAKE_CASE__ :\tList[Any] =\t\t\t\t\t\t\t\"mt5\"\r\t\tSCREAMING_SNAKE_CASE__ :\tstr =\t\t\t\t\t\t\tMTaConfig\r"},"style_context_codestyle":{"kind":"number","value":311,"string":"311"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":287,"cells":{"code":{"kind":"string","value":"\r\nimport os\r\nimport tempfile\r\nfrom functools import partial\r\nfrom unittest import TestCase\r\nfrom unittest.mock import patch\r\n\r\nimport datasets\r\nimport datasets.config\r\n\r\nfrom .utils import require_beam\r\n\r\n\r\n\r\n\r\nclass \t\t\tlowerCamelCase__\t\t\t\t\t\t\t( datasets.BeamBasedBuilder):\r\n\r\n\r\n\r\n\r\n\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\tdef _lowerCamelCase ( self\t\t:int\t\t\t\t\t\t)\t\t->\t\t\tUnion[str, Any]:\r\n\t\t\treturn datasets.DatasetInfo(\r\n\t\t\t features=datasets.Features({\"content\": datasets.Value(\"string\"\t\t\t\t\t\t)}\t\t\t\t\t\t)\t\t\t\t\t, supervised_keys=_a\t\t\t\t\t, )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tdef _lowerCamelCase ( self\t\t:Tuple\t\t\t\t\t, a\t\t:Optional[Any]\t\t\t\t\t, a\t\t:int\t\t\t\t\t\t)\t\t->\t\t\tUnion[str, Any]:\r\n\t\t\treturn [datasets.SplitGenerator(name=datasets.Split.TRAIN\t\t\t\t\t, gen_kwargs={\"examples\": get_test_dummy_examples()}\t\t\t\t\t\t)]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tdef _lowerCamelCase ( self\t\t:Dict\t\t\t\t\t, a\t\t:Any\t\t\t\t\t, a\t\t:str\t\t\t\t\t\t)\t\t->\t\t\tTuple:\r\n\t\t\timport apache_beam as beam\r\n\r\n\t\t\treturn pipeline | \"Load Examples\" >> beam.Create(_a\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\nclass \t\t\tlowerCamelCase__\t\t\t\t\t\t\t( datasets.BeamBasedBuilder):\r\n\r\n\r\n\r\n\r\n\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\tdef _lowerCamelCase ( self\t\t:Union[str, Any]\t\t\t\t\t\t)\t\t->\t\t\tDict:\r\n\t\t\treturn datasets.DatasetInfo(\r\n\t\t\t features=datasets.Features({\"a\": datasets.Sequence({\"b\": datasets.Value(\"string\"\t\t\t\t\t\t)}\t\t\t\t\t\t)}\t\t\t\t\t\t)\t\t\t\t\t, supervised_keys=_a\t\t\t\t\t, )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tdef _lowerCamelCase ( self\t\t:Any\t\t\t\t\t, a\t\t:Optional[int]\t\t\t\t\t, a\t\t:Any\t\t\t\t\t\t)\t\t->\t\t\tList[str]:\r\n\t\t\treturn [\r\n\t\t\t datasets.SplitGenerator(name=datasets.Split.TRAIN\t\t\t\t\t, gen_kwargs={\"examples\": get_test_nested_examples()}\t\t\t\t\t\t)\r\n\t\t\t]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tdef _lowerCamelCase ( self\t\t:Optional[Any]\t\t\t\t\t, a\t\t:int\t\t\t\t\t, a\t\t:List[str]\t\t\t\t\t\t)\t\t->\t\t\tOptional[Any]:\r\n\t\t\timport apache_beam as beam\r\n\r\n\t\t\treturn pipeline | \"Load Examples\" >> beam.Create(_a\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\ndef _SCREAMING_SNAKE_CASE (\t\t) -> List[Any]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\treturn [(i, {\"content\": content}) for i, content in enumerate([\"foo\", \"bar\", \"foobar\"])]\r\n\r\n\r\n\r\n\r\ndef _SCREAMING_SNAKE_CASE (\t\t) -> str:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\treturn [(i, {\"a\": {\"b\": [content]}}) for i, content in enumerate([\"foo\", \"bar\", \"foobar\"])]\r\n\r\n\r\n\r\n\r\nclass \t\t\tlowerCamelCase__\t\t\t\t\t\t\t( _a):\r\n\r\n\r\n\r\n\r\n\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\t@require_beam\r\n\tdef _lowerCamelCase ( self\t\t:Any\t\t\t\t\t\t)\t\t->\t\t\tstr:\r\n\t\t\t__UpperCamelCase : int = len(get_test_dummy_examples()\t\t\t\t\t\t)\r\n\t\t\twith tempfile.TemporaryDirectory() as tmp_cache_dir:\r\n\t\t\t\t\t__UpperCamelCase : Optional[int] = DummyBeamDataset(cache_dir=_a\t\t\t\t\t, beam_runner=\"DirectRunner\"\t\t\t\t\t\t)\r\n\t\t\t\t\tbuilder.download_and_prepare()\r\n\t\t\t\t\tself.assertTrue(\r\n\t\t\t\t\t os.path.exists(\r\n\t\t\t\t\t os.path.join(_a\t\t\t\t\t, builder.name\t\t\t\t\t, \"default\"\t\t\t\t\t, \"0.0.0\"\t\t\t\t\t, f'{builder.name}-train.arrow'\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertDictEqual(builder.info.features\t\t\t\t\t, datasets.Features({\"content\": datasets.Value(\"string\"\t\t\t\t\t\t)}\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\t__UpperCamelCase : Any = builder.as_dataset()\r\n\t\t\t\t\tself.assertEqual(dset[\"train\"].num_rows\t\t\t\t\t, _a\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertEqual(dset[\"train\"].info.splits[\"train\"].num_examples\t\t\t\t\t, _a\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertDictEqual(dset[\"train\"][0]\t\t\t\t\t, get_test_dummy_examples()[0][1]\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertDictEqual(\r\n\t\t\t\t\t dset[\"train\"][expected_num_examples - 1]\t\t\t\t\t, get_test_dummy_examples()[expected_num_examples - 1][1]\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertTrue(\r\n\t\t\t\t\t os.path.exists(os.path.join(_a\t\t\t\t\t, builder.name\t\t\t\t\t, \"default\"\t\t\t\t\t, \"0.0.0\"\t\t\t\t\t, \"dataset_info.json\"\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tdel dset\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t@require_beam\r\n\tdef _lowerCamelCase ( self\t\t:int\t\t\t\t\t\t)\t\t->\t\t\tstr:\r\n\t\t\timport apache_beam as beam\r\n\r\n\t\t\t__UpperCamelCase : List[Any] = beam.io.parquetio.WriteToParquet\r\n\r\n\t\t\t__UpperCamelCase : List[Any] = len(get_test_dummy_examples()\t\t\t\t\t\t)\r\n\t\t\twith tempfile.TemporaryDirectory() as tmp_cache_dir:\r\n\t\t\t\t\t__UpperCamelCase : Optional[int] = DummyBeamDataset(cache_dir=_a\t\t\t\t\t, beam_runner=\"DirectRunner\"\t\t\t\t\t\t)\r\n\t\t\t\t\twith patch(\"apache_beam.io.parquetio.WriteToParquet\"\t\t\t\t\t\t) as write_parquet_mock:\r\n\t\t\t\t\t\t\t__UpperCamelCase : int = partial(_a\t\t\t\t\t, num_shards=2\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\tbuilder.download_and_prepare()\r\n\t\t\t\t\tself.assertTrue(\r\n\t\t\t\t\t os.path.exists(\r\n\t\t\t\t\t os.path.join(\r\n\t\t\t\t\t _a\t\t\t\t\t, builder.name\t\t\t\t\t, \"default\"\t\t\t\t\t, \"0.0.0\"\t\t\t\t\t, f'{builder.name}-train-00000-of-00002.arrow'\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertTrue(\r\n\t\t\t\t\t os.path.exists(\r\n\t\t\t\t\t os.path.join(\r\n\t\t\t\t\t _a\t\t\t\t\t, builder.name\t\t\t\t\t, \"default\"\t\t\t\t\t, \"0.0.0\"\t\t\t\t\t, f'{builder.name}-train-00000-of-00002.arrow'\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertDictEqual(builder.info.features\t\t\t\t\t, datasets.Features({\"content\": datasets.Value(\"string\"\t\t\t\t\t\t)}\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\t__UpperCamelCase : Union[str, Any] = builder.as_dataset()\r\n\t\t\t\t\tself.assertEqual(dset[\"train\"].num_rows\t\t\t\t\t, _a\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertEqual(dset[\"train\"].info.splits[\"train\"].num_examples\t\t\t\t\t, _a\t\t\t\t\t\t)\r\n\t\t\t\t\t# Order is not preserved when sharding, so we just check that all the elements are there\r\n\t\t\t\t\tself.assertListEqual(sorted(dset[\"train\"][\"content\"]\t\t\t\t\t\t)\t\t\t\t\t, sorted([\"foo\", \"bar\", \"foobar\"]\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertTrue(\r\n\t\t\t\t\t os.path.exists(os.path.join(_a\t\t\t\t\t, builder.name\t\t\t\t\t, \"default\"\t\t\t\t\t, \"0.0.0\"\t\t\t\t\t, \"dataset_info.json\"\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tdel dset\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t@require_beam\r\n\tdef _lowerCamelCase ( self\t\t:Union[str, Any]\t\t\t\t\t\t)\t\t->\t\t\tUnion[str, Any]:\r\n\t\t\twith tempfile.TemporaryDirectory() as tmp_cache_dir:\r\n\t\t\t\t\t__UpperCamelCase : Union[str, Any] = DummyBeamDataset(cache_dir=_a\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertRaises(datasets.builder.MissingBeamOptions\t\t\t\t\t, builder.download_and_prepare\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t@require_beam\r\n\tdef _lowerCamelCase ( self\t\t:Optional[Any]\t\t\t\t\t\t)\t\t->\t\t\tList[Any]:\r\n\t\t\t__UpperCamelCase : Dict = len(get_test_nested_examples()\t\t\t\t\t\t)\r\n\t\t\twith tempfile.TemporaryDirectory() as tmp_cache_dir:\r\n\t\t\t\t\t__UpperCamelCase : Optional[Any] = NestedBeamDataset(cache_dir=_a\t\t\t\t\t, beam_runner=\"DirectRunner\"\t\t\t\t\t\t)\r\n\t\t\t\t\tbuilder.download_and_prepare()\r\n\t\t\t\t\tself.assertTrue(\r\n\t\t\t\t\t os.path.exists(\r\n\t\t\t\t\t os.path.join(_a\t\t\t\t\t, builder.name\t\t\t\t\t, \"default\"\t\t\t\t\t, \"0.0.0\"\t\t\t\t\t, f'{builder.name}-train.arrow'\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertDictEqual(\r\n\t\t\t\t\t builder.info.features\t\t\t\t\t, datasets.Features({\"a\": datasets.Sequence({\"b\": datasets.Value(\"string\"\t\t\t\t\t\t)}\t\t\t\t\t\t)}\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\t__UpperCamelCase : int = builder.as_dataset()\r\n\t\t\t\t\tself.assertEqual(dset[\"train\"].num_rows\t\t\t\t\t, _a\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertEqual(dset[\"train\"].info.splits[\"train\"].num_examples\t\t\t\t\t, _a\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertDictEqual(dset[\"train\"][0]\t\t\t\t\t, get_test_nested_examples()[0][1]\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertDictEqual(\r\n\t\t\t\t\t dset[\"train\"][expected_num_examples - 1]\t\t\t\t\t, get_test_nested_examples()[expected_num_examples - 1][1]\t\t\t\t\t\t)\r\n\t\t\t\t\tself.assertTrue(\r\n\t\t\t\t\t os.path.exists(os.path.join(_a\t\t\t\t\t, builder.name\t\t\t\t\t, \"default\"\t\t\t\t\t, \"0.0.0\"\t\t\t\t\t, \"dataset_info.json\"\t\t\t\t\t\t)\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\tdel dset"},"code_codestyle":{"kind":"number","value":370,"string":"370"},"style_context":{"kind":"string","value":"\r\nimport argparse\r\nimport os\r\n\r\nimport evaluate\r\nimport torch\r\nfrom datasets import load_dataset\r\nfrom torch.optim import AdamW\r\nfrom torch.utils.data import DataLoader\r\nfrom transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed\r\n\r\nfrom accelerate import Accelerator, DistributedType\r\n\r\n\r\n########################################################################\r\n# This is a fully working simple example to use Accelerate,\r\n# specifically showcasing the experiment tracking capability,\r\n# and builds off the `nlp_example.py` script.\r\n#\r\n# This example trains a Bert base model on GLUE MRPC\r\n# in any of the following settings (with the same script):\r\n# - single CPU or single GPU\r\n# - multi GPUS (using PyTorch distributed mode)\r\n# - (multi) TPUs\r\n# - fp16 (mixed-precision) or fp32 (normal precision)\r\n#\r\n# To help focus on the differences in the code, building `DataLoaders`\r\n# was refactored into its own function.\r\n# New additions from the base script can be found quickly by\r\n# looking for the # New Code # tags\r\n#\r\n# To run it in each of these various modes, follow the instructions\r\n# in the readme for examples:\r\n# https://github.com/huggingface/accelerate/tree/main/examples\r\n#\r\n########################################################################\r\n\r\nlowercase : Any\t\t\t\t\t\t\t\t\t\t\t\t\t=\t16\r\nlowercase : Optional[int]\t\t\t\t\t\t\t\t\t\t\t\t\t=\t32\r\n\r\n\r\n\r\n\r\ndef _SCREAMING_SNAKE_CASE (\t\t_lowerCamelCase\t\t\t: Accelerator\t\t\t\t\t\t, _lowerCamelCase\t\t\t: int = 16) -> int:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase : Any = AutoTokenizer.from_pretrained(\"bert-base-cased\")\r\n\t\t\t\t\t\t\t__UpperCamelCase : Optional[Any] = load_dataset(\"glue\"\t\t\t\t\t\t, \"mrpc\")\r\n\r\n\t\t\t\t\t\t\tdef tokenize_function(_lowerCamelCase\t\t\t: Dict):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# max_length=None => use the model max length (it's actually the default)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : List[str] = tokenizer(examples[\"sentence1\"]\t\t\t\t\t\t, examples[\"sentence2\"]\t\t\t\t\t\t, truncation=_lowerCamelCase\t\t\t\t\t\t, max_length=_lowerCamelCase)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn outputs\r\n\r\n\t\t\t\t\t\t\t# Apply the method we just defined to all the examples in all the splits of the dataset\r\n\t\t\t\t\t\t\t# starting with the main process first:\r\n\t\t\t\t\t\t\twith accelerator.main_process_first():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Optional[int] = datasets.map(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t _lowerCamelCase\t\t\t\t\t\t, batched=_lowerCamelCase\t\t\t\t\t\t, remove_columns=[\"idx\", \"sentence1\", \"sentence2\"]\t\t\t\t\t\t, )\r\n\r\n\t\t\t\t\t\t\t# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the\r\n\t\t\t\t\t\t\t# transformers library\r\n\t\t\t\t\t\t\t__UpperCamelCase : List[str] = tokenized_datasets.rename_column(\"label\"\t\t\t\t\t\t, \"labels\")\r\n\r\n\t\t\t\t\t\t\tdef collate_fn(_lowerCamelCase\t\t\t: Union[str, Any]):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# On TPU it's best to pad everything to the same length or training will be very slow.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : str = 128 if accelerator.distributed_type == DistributedType.TPU else None\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# When using mixed precision we want round multiples of 8/16\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif accelerator.mixed_precision == \"fp8\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Optional[Any] = 16\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telif accelerator.mixed_precision != \"no\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Dict = 8\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Optional[Any] = None\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn tokenizer.pad(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t _lowerCamelCase\t\t\t\t\t\t, padding=\"longest\"\t\t\t\t\t\t, max_length=_lowerCamelCase\t\t\t\t\t\t, pad_to_multiple_of=_lowerCamelCase\t\t\t\t\t\t, return_tensors=\"pt\"\t\t\t\t\t\t, )\r\n\r\n\t\t\t\t\t\t\t# Instantiate dataloaders.\r\n\t\t\t\t\t\t\t__UpperCamelCase : Optional[Any] = DataLoader(\r\n\t\t\t\t\t\t\t tokenized_datasets[\"train\"]\t\t\t\t\t\t, shuffle=_lowerCamelCase\t\t\t\t\t\t, collate_fn=_lowerCamelCase\t\t\t\t\t\t, batch_size=_lowerCamelCase)\r\n\t\t\t\t\t\t\t__UpperCamelCase : int = DataLoader(\r\n\t\t\t\t\t\t\t tokenized_datasets[\"validation\"]\t\t\t\t\t\t, shuffle=_lowerCamelCase\t\t\t\t\t\t, collate_fn=_lowerCamelCase\t\t\t\t\t\t, batch_size=_lowerCamelCase)\r\n\r\n\t\t\t\t\t\t\treturn train_dataloader, eval_dataloader\r\n\r\n\r\n# For testing only\r\nif os.environ.get('TESTING_MOCKED_DATALOADERS', None) == \"1\":\r\n\t\tfrom accelerate.test_utils.training import mocked_dataloaders\r\n\r\n\t\tlowercase : Union[str, Any]\t\t\t\t\t\t\t\t\t\t\t\t\t=\tmocked_dataloaders # noqa: F811\r\n\r\n\r\n\r\n\r\ndef _SCREAMING_SNAKE_CASE (\t\t_lowerCamelCase\t\t\t: Optional[Any]\t\t\t\t\t\t, _lowerCamelCase\t\t\t: Union[str, Any]) -> str:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\tif os.environ.get(\"TESTING_MOCKED_DATALOADERS\"\t\t\t\t\t\t, _lowerCamelCase) == \"1\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : List[str] = 2\r\n\t\t\t\t\t\t\t# Initialize Accelerator\r\n\r\n\t\t\t\t\t\t\t# New Code #\r\n\t\t\t\t\t\t\t# We pass in \"all\" to `log_with` to grab all available trackers in the environment\r\n\t\t\t\t\t\t\t# Note: If using a custom `Tracker` class, should be passed in here such as:\r\n\t\t\t\t\t\t\t# >>> log_with = [\"all\", MyCustomTrackerClassInstance()]\r\n\t\t\t\t\t\t\tif args.with_tracking:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Union[str, Any] = Accelerator(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t cpu=args.cpu\t\t\t\t\t\t, mixed_precision=args.mixed_precision\t\t\t\t\t\t, log_with=\"all\"\t\t\t\t\t\t, project_dir=args.project_dir)\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Optional[Any] = Accelerator(cpu=args.cpu\t\t\t\t\t\t, mixed_precision=args.mixed_precision)\r\n\t\t\t\t\t\t\t# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs\r\n\t\t\t\t\t\t\t__UpperCamelCase : List[str] = config[\"lr\"]\r\n\t\t\t\t\t\t\t__UpperCamelCase : Optional[Any] = int(config[\"num_epochs\"])\r\n\t\t\t\t\t\t\t__UpperCamelCase : List[Any] = int(config[\"seed\"])\r\n\t\t\t\t\t\t\t__UpperCamelCase : Any = int(config[\"batch_size\"])\r\n\t\t\t\t\t\t\tset_seed(_lowerCamelCase)\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t__UpperCamelCase : List[Any] = get_dataloaders(_lowerCamelCase\t\t\t\t\t\t, _lowerCamelCase)\r\n\t\t\t\t\t\t\t__UpperCamelCase : List[str] = evaluate.load(\"glue\"\t\t\t\t\t\t, \"mrpc\")\r\n\r\n\t\t\t\t\t\t\t# If the batch size is too big we use gradient accumulation\r\n\t\t\t\t\t\t\t__UpperCamelCase : Union[str, Any] = 1\r\n\t\t\t\t\t\t\tif batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : List[Any] = batch_size // MAX_GPU_BATCH_SIZE\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Union[str, Any] = MAX_GPU_BATCH_SIZE\r\n\r\n\t\t\t\t\t\t\t# Instantiate the model (we build the model here so that the seed also control new weights initialization)\r\n\t\t\t\t\t\t\t__UpperCamelCase : str = AutoModelForSequenceClassification.from_pretrained(\"bert-base-cased\"\t\t\t\t\t\t, return_dict=_lowerCamelCase)\r\n\r\n\t\t\t\t\t\t\t# We could avoid this line since the accelerator is set with `device_placement=True` (default value).\r\n\t\t\t\t\t\t\t# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer\r\n\t\t\t\t\t\t\t# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).\r\n\t\t\t\t\t\t\t__UpperCamelCase : Optional[int] = model.to(accelerator.device)\r\n\r\n\t\t\t\t\t\t\t# Instantiate optimizer\r\n\t\t\t\t\t\t\t__UpperCamelCase : List[str] = AdamW(params=model.parameters()\t\t\t\t\t\t, lr=_lowerCamelCase)\r\n\r\n\t\t\t\t\t\t\t# Instantiate scheduler\r\n\t\t\t\t\t\t\t__UpperCamelCase : Union[str, Any] = get_linear_schedule_with_warmup(\r\n\t\t\t\t\t\t\t optimizer=_lowerCamelCase\t\t\t\t\t\t, num_warmup_steps=100\t\t\t\t\t\t, num_training_steps=(len(_lowerCamelCase) * num_epochs) // gradient_accumulation_steps\t\t\t\t\t\t, )\r\n\r\n\t\t\t\t\t\t\t# Prepare everything\r\n\t\t\t\t\t\t\t# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the\r\n\t\t\t\t\t\t\t# prepare method.\r\n\t\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t__UpperCamelCase : Union[str, Any] = accelerator.prepare(\r\n\t\t\t\t\t\t\t _lowerCamelCase\t\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t\t, _lowerCamelCase\t\t\t\t\t\t, _lowerCamelCase)\r\n\r\n\t\t\t\t\t\t\t# New Code #\r\n\t\t\t\t\t\t\t# We need to initialize the trackers we use. Overall configurations can also be stored\r\n\t\t\t\t\t\t\tif args.with_tracking:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Dict = os.path.split(_lowerCamelCase)[-1].split(\".\")[0]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.init_trackers(_lowerCamelCase\t\t\t\t\t\t, _lowerCamelCase)\r\n\r\n\t\t\t\t\t\t\t# Now we train the model\r\n\t\t\t\t\t\t\tfor epoch in range(_lowerCamelCase):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmodel.train()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# New Code #\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# For our tracking example, we will log the total loss of each epoch\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif args.with_tracking:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Tuple = 0\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor step, batch in enumerate(_lowerCamelCase):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# We could avoid this line since we set the accelerator with `device_placement=True`.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbatch.to(accelerator.device)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Dict = model(**_lowerCamelCase)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Any = outputs.loss\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# New Code #\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif args.with_tracking:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttotal_loss += loss.detach().float()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : List[Any] = loss / gradient_accumulation_steps\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.backward(_lowerCamelCase)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif step % gradient_accumulation_steps == 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toptimizer.step()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlr_scheduler.step()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toptimizer.zero_grad()\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tmodel.eval()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor step, batch in enumerate(_lowerCamelCase):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# We could avoid this line since we set the accelerator with `device_placement=True` (the default).\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbatch.to(accelerator.device)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twith torch.no_grad():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Union[str, Any] = model(**_lowerCamelCase)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : str = outputs.logits.argmax(dim=-1)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase ,\t\t\t\t\t\t__UpperCamelCase : Dict = accelerator.gather_for_metrics((predictions, batch[\"labels\"]))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmetric.add_batch(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t predictions=_lowerCamelCase\t\t\t\t\t\t, references=_lowerCamelCase\t\t\t\t\t\t, )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase : Optional[Any] = metric.compute()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Use accelerator.print to print only on the main process.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.print(F'epoch {epoch}:'\t\t\t\t\t\t, _lowerCamelCase)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# New Code #\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# To actually log, we call `Accelerator.log`\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif args.with_tracking:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.log(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"accuracy\": eval_metric[\"accuracy\"],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"f1\": eval_metric[\"f1\"],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"train_loss\": total_loss.item() / len(_lowerCamelCase),\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"epoch\": epoch,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t }\t\t\t\t\t\t, step=_lowerCamelCase\t\t\t\t\t\t, )\r\n\r\n # New Code #\r\n # When a run is finished, you should call `accelerator.end_training()`\r\n # to close all of the open trackers\r\n\t\t\t\t\t\t\tif args.with_tracking:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taccelerator.end_training()\r\n\r\n\r\n\r\n\r\ndef _SCREAMING_SNAKE_CASE (\t\t) -> Optional[int]:\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase : str = argparse.ArgumentParser(description=\"Simple example of training script.\")\r\n\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t \"--mixed_precision\"\t\t\t\t\t\t, type=_lowerCamelCase\t\t\t\t\t\t, default=_lowerCamelCase\t\t\t\t\t\t, choices=[\"no\", \"fp16\", \"bf16\", \"fp8\"]\t\t\t\t\t\t, help=\"Whether to use mixed precision. Choose\"\r\n\t\t\t\t\t\t\t \"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.\"\r\n\t\t\t\t\t\t\t \"and an Nvidia Ampere GPU.\"\t\t\t\t\t\t, )\r\n\t\t\t\t\t\t\tparser.add_argument(\"--cpu\"\t\t\t\t\t\t, action=\"store_true\"\t\t\t\t\t\t, help=\"If passed, will train on the CPU.\")\r\n\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t \"--with_tracking\"\t\t\t\t\t\t, action=\"store_true\"\t\t\t\t\t\t, help=\"Whether to load in all available experiment trackers from the environment and use them for logging.\"\t\t\t\t\t\t, )\r\n\t\t\t\t\t\t\tparser.add_argument(\r\n\t\t\t\t\t\t\t \"--project_dir\"\t\t\t\t\t\t, type=_lowerCamelCase\t\t\t\t\t\t, default=\"logs\"\t\t\t\t\t\t, help=\"Location on where to store experiment tracking logs` and relevent project information\"\t\t\t\t\t\t, )\r\n\t\t\t\t\t\t\t__UpperCamelCase : Union[str, Any] = parser.parse_args()\r\n\t\t\t\t\t\t\t__UpperCamelCase : str = {\"lr\": 2e-5, \"num_epochs\": 3, \"seed\": 42, \"batch_size\": 16}\r\n\t\t\t\t\t\t\ttraining_function(_lowerCamelCase\t\t\t\t\t\t, _lowerCamelCase)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\tmain()"},"style_context_codestyle":{"kind":"number","value":151,"string":"151"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":288,"cells":{"code":{"kind":"string","value":"\n\n\n\n\n'''simple docstring'''\n\n\n\n\n\n\n\nfrom math import sqrt\n\n\n\n\n\ndef \t\t\t\t\t\tsnake_case_\t\t\t\t\t\t\t(_a\t:\t\t\t\t\t\t\tOptional[Any] = 1_0_0_0_0_0_0 ):\n UpperCAmelCase\t\t\t =\t\t0\n UpperCAmelCase\t\t\t =\t\t0\n UpperCAmelCase\t\t\t =\t\t4_2\n\n while num_cuboids <= limit:\n max_cuboid_size += 1\n for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ):\n if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer():\n num_cuboids += (\n min(snake_case__ , sum_shortest_sides // 2 )\n - max(1 , sum_shortest_sides - max_cuboid_size )\n + 1\n )\n\n return max_cuboid_size\n\n\nif __name__ == \"__main__\":\n print(f\"\"\"{solution() = }\"\"\")\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":34,"string":"34"},"style_context":{"kind":"string","value":"import unittest\r\n\r\nimport numpy as np\r\n\r\ndef SCREAMING_SNAKE_CASE_ (\t\t\t\t\t\tsnake_case__ , snake_case__ , snake_case__ , snake_case__ = None , ) ->\tnp.ndarray:\r\n\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.shape(snake_case__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.shape(snake_case__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.shape(snake_case__\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\tif shape_a[0] != shape_b[0]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\t(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''Expected the same number of rows for A and B. '''\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"Instead found A of size {shape_a} and B of size {shape_b}\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(snake_case__\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\tif shape_b[1] != shape_c[1]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\t(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''Expected the same number of columns for B and C. '''\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"Instead found B of size {shape_b} and C of size {shape_c}\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(snake_case__\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tpseudo_inv\r\n\t\t\t\t\t\t\tif a_inv is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.linalg.inv(snake_case__\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\texcept np.linalg.LinAlgError:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''Input matrix A is not invertible. Cannot compute Schur complement.'''\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\treturn mat_c - mat_b.T @ a_inv @ mat_b\r\n\r\n\r\n\r\n\r\nclass lowercase_ ( unittest.TestCase\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\tdef \t\t\tSCREAMING_SNAKE_CASE_\t\t\t\t(\t\t\t\t\t\t\tself\t\t\t\t)\t\t\t\t\t\t->None:\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[0, 3], [3, 0], [2, 3]]\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[2, 1], [6, 3]]\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tschur_complement(__SCREAMING_SNAKE_CASE\t\t,\t\t\t__SCREAMING_SNAKE_CASE\t\t,\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.block([[a, b], [b.T, c]]\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.linalg.det(__SCREAMING_SNAKE_CASE\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.linalg.det(__SCREAMING_SNAKE_CASE\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.linalg.det(__SCREAMING_SNAKE_CASE\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\tself.assertAlmostEqual(__SCREAMING_SNAKE_CASE\t\t,\t\t\tdet_a * det_s\t\t\t\t)\r\n\r\n\r\n\tdef \t\t\tSCREAMING_SNAKE_CASE_\t\t\t\t(\t\t\t\t\t\t\tself\t\t\t\t)\t\t\t\t\t\t->None:\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[0, 3], [3, 0], [2, 3]]\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[2, 1], [6, 3]]\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\twith self.assertRaises(__SCREAMING_SNAKE_CASE\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tschur_complement(__SCREAMING_SNAKE_CASE\t\t,\t\t\t__SCREAMING_SNAKE_CASE\t\t,\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\tdef \t\t\tSCREAMING_SNAKE_CASE_\t\t\t\t(\t\t\t\t\t\t\tself\t\t\t\t)\t\t\t\t\t\t->None:\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[0, 3], [3, 0], [2, 3]]\t\t\t\t)\r\n\t\t\t\t\t\t\t\tlowerCAmelCase\t\t\t=\t\tnp.array([[2, 1, 3], [6, 3, 5]]\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\twith self.assertRaises(__SCREAMING_SNAKE_CASE\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tschur_complement(__SCREAMING_SNAKE_CASE\t\t,\t\t\t__SCREAMING_SNAKE_CASE\t\t,\t\t\t__SCREAMING_SNAKE_CASE\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\timport doctest\r\n\r\n\tdoctest.testmod()\r\n\tunittest.main()\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":338,"string":"338"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":289,"cells":{"code":{"kind":"string","value":"\rfrom __future__ import annotations\r\rimport time\r\rimport numpy as np\r\rlowercase : Optional[Any]\t\t\t\t\t\t =\t\t\t\t\t\t\t[8, 5, 9, 7]\rlowercase : Union[str, Any]\t\t\t\t\t\t =\t\t\t\t\t\t\t[\r [2, 0, 1, 1],\r [0, 1, 2, 1],\r [4, 0, 0, 3],\r [0, 2, 1, 0],\r [1, 0, 3, 0],\r]\rlowercase : Optional[Any]\t\t\t\t\t\t =\t\t\t\t\t\t\t[\r [3, 2, 1, 4],\r [0, 2, 5, 2],\r [5, 1, 0, 5],\r [1, 5, 3, 0],\r [3, 0, 3, 3],\r]\r\rclass __snake_case\t\t:\r def __init__( self\t\t,snake_case\t\t,snake_case\t\t,snake_case\t\t,):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tAny\t =\t\t\t\tclaim_vector\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any]\t =\t\t\t\tallocated_resources_table\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tDict\t =\t\t\t\tmaximum_claim_table\r def _SCREAMING_SNAKE_CASE\t( self\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r return [\r sum(p_item[i] for p_item in self.__allocated_resources_table\t\t\t\t)\r for i in range(len(self.__allocated_resources_table[0]\t\t\t\t)\t\t\t\t)\r ]\r def _SCREAMING_SNAKE_CASE\t( self\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r return np.array(self.__claim_vector\t\t\t\t) - np.array(\r self.__processes_resource_summation()\t\t\t\t)\r def _SCREAMING_SNAKE_CASE\t( self\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r return [\r list(np.array(self.__maximum_claim_table[i]\t\t\t\t) - np.array(snake_case\t\t\t\t)\t\t\t\t)\r for i, allocated_resource in enumerate(self.__allocated_resources_table\t\t\t\t)\r ]\r def _SCREAMING_SNAKE_CASE\t( self\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r return {self.__need().index(snake_case\t\t\t\t): i for i in self.__need()}\r def _SCREAMING_SNAKE_CASE\t( self\t\t,**snake_case\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tAny\t =\t\t\t\tself.__need()\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[str]\t =\t\t\t\tself.__allocated_resources_table\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tint\t =\t\t\t\tself.__available_resources()\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tint\t =\t\t\t\tself.__need_index_manager()\r for kw, val in kwargs.items():\r if kw and val is True:\r self.__pretty_data()\r print(\"\"\"_\"\"\" * 50 + \"\"\"\\n\"\"\"\t\t\t\t)\r while need_list:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[str]\t =\t\t\t\tFalse\r for each_need in need_list:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tTrue\r for index, need in enumerate(snake_case\t\t\t\t):\r if need > available_resources[index]:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tFalse\r break\r if execution:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tTrue\r # get the original index of the process from ind_ctrl db\r for original_need_index, need_clone in need_index_manager.items():\r if each_need == need_clone:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any]\t =\t\t\t\toriginal_need_index\r print(f\"Process {process_number + 1} is executing.\"\t\t\t\t)\r # remove the process run from stack\r need_list.remove(snake_case\t\t\t\t)\r # update available/freed resources stack\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tDict\t =\t\t\t\tnp.array(snake_case\t\t\t\t) + np.array(\r alloc_resources_table[process_number]\t\t\t\t)\r print(\r \"\"\"Updated available resource stack for processes: \"\"\"\r + \"\"\" \"\"\".join([str(snake_case\t\t\t\t) for x in available_resources]\t\t\t\t)\t\t\t\t)\r break\r if safe:\r print(\"\"\"The process is in a safe state.\\n\"\"\"\t\t\t\t)\r else:\r print(\"\"\"System in unsafe state. Aborting...\\n\"\"\"\t\t\t\t)\r break\r def _SCREAMING_SNAKE_CASE\t( self\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r print(\"\"\" \"\"\" * 9 + \"\"\"Allocated Resource Table\"\"\"\t\t\t\t)\r for item in self.__allocated_resources_table:\r print(\r f\"P{self.__allocated_resources_table.index(snake_case\t\t\t\t) + 1}\"\r + \"\"\" \"\"\".join(f\"{it:>8}\" for it in item\t\t\t\t)\r + \"\"\"\\n\"\"\"\t\t\t\t)\r print(\"\"\" \"\"\" * 9 + \"\"\"System Resource Table\"\"\"\t\t\t\t)\r for item in self.__maximum_claim_table:\r print(\r f\"P{self.__maximum_claim_table.index(snake_case\t\t\t\t) + 1}\"\r + \"\"\" \"\"\".join(f\"{it:>8}\" for it in item\t\t\t\t)\r + \"\"\"\\n\"\"\"\t\t\t\t)\r print(\r \"\"\"Current Usage by Active Processes: \"\"\"\r + \"\"\" \"\"\".join(str(snake_case\t\t\t\t) for x in self.__claim_vector\t\t\t\t)\t\t\t\t)\r print(\r \"\"\"Initial Available Resources: \"\"\"\r + \"\"\" \"\"\".join(str(snake_case\t\t\t\t) for x in self.__available_resources()\t\t\t\t)\t\t\t\t)\r time.sleep(1\t\t\t\t)\r\r\rif __name__ == \"__main__\":\r import doctest\r\r doctest.testmod()\r"},"code_codestyle":{"kind":"number","value":359,"string":"359"},"style_context":{"kind":"string","value":"\rimport os\rimport re\rimport shutil\rfrom argparse import ArgumentParser, Namespace\r\rfrom datasets.commands import BaseDatasetsCLICommand\rfrom datasets.utils.logging import get_logger\r\r\rlowercase : Tuple\t\t\t\t\t\t =\t\t\t\t\t\t\t\"\"\"<<<<<<< This should probably be modified because it mentions: \"\"\"\r\rlowercase : Any\t\t\t\t\t\t =\t\t\t\t\t\t\t\"\"\"=======\n>>>>>>>\n\"\"\"\r\rlowercase : List[str]\t\t\t\t\t\t =\t\t\t\t\t\t\t[\r \"\"\"TextEncoderConfig\"\"\",\r \"\"\"ByteTextEncoder\"\"\",\r \"\"\"SubwordTextEncoder\"\"\",\r \"\"\"encoder_config\"\"\",\r \"\"\"maybe_build_from_corpus\"\"\",\r \"\"\"manual_dir\"\"\",\r]\r\rlowercase : Any\t\t\t\t\t\t =\t\t\t\t\t\t\t[\r # (pattern, replacement)\r # Order is important here for some replacements\r (R\"\"\"tfds\\.core\"\"\", R\"\"\"datasets\"\"\"),\r (R\"\"\"tf\\.io\\.gfile\\.GFile\"\"\", R\"\"\"open\"\"\"),\r (R\"\"\"tf\\.([\\w\\d]+)\"\"\", R\"\"\"datasets.Value('\\1')\"\"\"),\r (R\"\"\"tfds\\.features\\.Text\\(\\)\"\"\", R\"\"\"datasets.Value('string')\"\"\"),\r (R\"\"\"tfds\\.features\\.Text\\(\"\"\", R\"\"\"datasets.Value('string'),\"\"\"),\r (R\"\"\"features\\s*=\\s*tfds.features.FeaturesDict\\(\"\"\", R\"\"\"features=datasets.Features(\"\"\"),\r (R\"\"\"tfds\\.features\\.FeaturesDict\\(\"\"\", R\"\"\"dict(\"\"\"),\r (R\"\"\"The TensorFlow Datasets Authors\"\"\", R\"\"\"The TensorFlow Datasets Authors and the HuggingFace Datasets Authors\"\"\"),\r (R\"\"\"tfds\\.\"\"\", R\"\"\"datasets.\"\"\"),\r (R\"\"\"dl_manager\\.manual_dir\"\"\", R\"\"\"self.config.data_dir\"\"\"),\r (R\"\"\"self\\.builder_config\"\"\", R\"\"\"self.config\"\"\"),\r]\r\r\r\r\r\r\r\rdef \t\t\t\t\t\t_snake_case( SCREAMING_SNAKE_CASE__ )\t\t\t-> List[Any]:\r return ConvertCommand(args.tfds_path , args.datasets_directory )\r\r\r\r\rclass __snake_case\t\t(\t\t\t\tlowerCAmelCase\t\t\t\t\t):\r @staticmethod\r def \t\t\t\t_SCREAMING_SNAKE_CASE\t( snake_case\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tstr\t =\t\t\t\tparser.add_parser(\r \"\"\"convert\"\"\"\t\t,help=\"\"\"Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.\"\"\"\t\t,)\r train_parser.add_argument(\r \"\"\"--tfds_path\"\"\"\t\t,type=snake_case\t\t,required=snake_case\t\t,help=\"\"\"Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.\"\"\"\t\t,)\r train_parser.add_argument(\r \"\"\"--datasets_directory\"\"\"\t\t,type=snake_case\t\t,required=snake_case\t\t,help=\"\"\"Path to the HuggingFace Datasets folder.\"\"\"\t\t\t\t)\r train_parser.set_defaults(func=snake_case\t\t\t\t)\r def __init__( self\t\t,snake_case\t\t,snake_case\t\t,*snake_case\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tget_logger(\"\"\"datasets-cli/converting\"\"\"\t\t\t\t)\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int]\t =\t\t\t\ttfds_path\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tDict\t =\t\t\t\tdatasets_directory\r def \t\t\t\t_SCREAMING_SNAKE_CASE\t( self\t\t\t\t):\r\r\r\r '''simple docstring'''\r\r\r\r\r\r\r\r if os.path.isdir(self._tfds_path\t\t\t\t):\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[str]\t =\t\t\t\tos.path.abspath(self._tfds_path\t\t\t\t)\r elif os.path.isfile(self._tfds_path\t\t\t\t):\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tTuple\t =\t\t\t\tos.path.dirname(self._tfds_path\t\t\t\t)\r else:\r raise ValueError(\"\"\"--tfds_path is neither a directory nor a file. Please check path.\"\"\"\t\t\t\t)\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int]\t =\t\t\t\tos.path.abspath(self._datasets_directory\t\t\t\t)\r\r self._logger.info(f\"Converting datasets from {abs_tfds_path} to {abs_datasets_path}\"\t\t\t\t)\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[Any]\t =\t\t\t\t[]\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int]\t =\t\t\t\t[]\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tDict\t =\t\t\t\t{}\r\r if os.path.isdir(self._tfds_path\t\t\t\t):\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tint\t =\t\t\t\tos.listdir(snake_case\t\t\t\t)\r else:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[Any]\t =\t\t\t\t[os.path.basename(self._tfds_path\t\t\t\t)]\r\r for f_name in file_names:\r self._logger.info(f\"Looking at file {f_name}\"\t\t\t\t)\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[Any]\t =\t\t\t\tos.path.join(snake_case\t\t,snake_case\t\t\t\t)\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[str]\t =\t\t\t\tos.path.join(snake_case\t\t,snake_case\t\t\t\t)\r\r if not os.path.isfile(snake_case\t\t\t\t) or \"__init__\" in f_name or \"_test\" in f_name or \".py\" not in f_name:\r self._logger.info(\"\"\"Skipping file\"\"\"\t\t\t\t)\r continue\r\r with open(snake_case\t\t,encoding=\"\"\"utf-8\"\"\"\t\t\t\t) as f:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tstr\t =\t\t\t\tf.readlines()\r\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any]\t =\t\t\t\t[]\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tFalse\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tFalse\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int]\t =\t\t\t\t[]\r for line in lines:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tint\t =\t\t\t\tline\r\r # Convert imports\r if \"import tensorflow.compat.v2 as tf\" in out_line:\r continue\r elif \"@tfds.core\" in out_line:\r continue\r elif \"builder=self\" in out_line:\r continue\r elif \"import tensorflow_datasets.public_api as tfds\" in out_line:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any]\t =\t\t\t\t\"\"\"import datasets\\n\"\"\"\r elif \"import tensorflow\" in out_line:\r # order is important here\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[Any]\t =\t\t\t\t\"\"\"\"\"\"\r continue\r elif \"from absl import logging\" in out_line:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int]\t =\t\t\t\t\"\"\"from datasets import logging\\n\"\"\"\r elif \"getLogger\" in out_line:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tAny\t =\t\t\t\tout_line.replace(\"\"\"getLogger\"\"\"\t\t,\"\"\"get_logger\"\"\"\t\t\t\t)\r elif any(expression in out_line for expression in TO_HIGHLIGHT\t\t\t\t):\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tTrue\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tlist(filter(lambda snake_case\t\t\t\t: e in out_line\t\t,snake_case\t\t\t\t)\t\t\t\t)\r out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(snake_case\t\t\t\t) + \"\"\"\\n\"\"\"\t\t\t\t)\r out_lines.append(snake_case\t\t\t\t)\r out_lines.append(snake_case\t\t\t\t)\r continue\r else:\r for pattern, replacement in TO_CONVERT:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any]\t =\t\t\t\tre.sub(snake_case\t\t,snake_case\t\t,snake_case\t\t\t\t)\r\r # Take care of saving utilities (to later move them together with main script)\r if \"tensorflow_datasets\" in out_line:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tDict\t =\t\t\t\tre.match(r\"\"\"from\\stensorflow_datasets.*import\\s([^\\.\\r\\n]+)\"\"\"\t\t,snake_case\t\t\t\t)\r tfds_imports.extend(imp.strip() for imp in match.group(1\t\t\t\t).split(\"\"\",\"\"\"\t\t\t\t)\t\t\t\t)\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int]\t =\t\t\t\t\"\"\"from . import \"\"\" + match.group(1\t\t\t\t)\r\r # Check we have not forget anything\r if \"tf.\" in out_line or \"tfds.\" in out_line or \"tensorflow_datasets\" in out_line:\r raise ValueError(f\"Error converting {out_line.strip()}\"\t\t\t\t)\r\r if \"GeneratorBasedBuilder\" in out_line or \"BeamBasedBuilder\" in out_line:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tAny\t =\t\t\t\tTrue\r out_lines.append(snake_case\t\t\t\t)\r\r if is_builder or \"wmt\" in f_name:\r # We create a new directory for each dataset\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tUnion[str, Any]\t =\t\t\t\tf_name.replace(\"\"\".py\"\"\"\t\t,\"\"\"\"\"\"\t\t\t\t)\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[Any]\t =\t\t\t\tos.path.join(snake_case\t\t,snake_case\t\t\t\t)\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tList[str]\t =\t\t\t\tos.path.join(snake_case\t\t,snake_case\t\t\t\t)\r os.makedirs(snake_case\t\t,exist_ok=snake_case\t\t\t\t)\r self._logger.info(f\"Adding directory {output_dir}\"\t\t\t\t)\r imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}\t\t\t\t)\r else:\r # Utilities will be moved at the end\r utils_files.append(snake_case\t\t\t\t)\r\r if needs_manual_update:\r with_manual_update.append(snake_case\t\t\t\t)\r\r with open(snake_case\t\t,\"\"\"w\"\"\"\t\t,encoding=\"\"\"utf-8\"\"\"\t\t\t\t) as f:\r f.writelines(snake_case\t\t\t\t)\r self._logger.info(f\"Converted in {output_file}\"\t\t\t\t)\r\r for utils_file in utils_files:\r try:\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tOptional[int]\t =\t\t\t\tos.path.basename(snake_case\t\t\t\t)\r lowercase\t\t\t\t\t\t\t:\t\t\t\t\tint\t =\t\t\t\timports_to_builder_map[f_name.replace(\"\"\".py\"\"\"\t\t,\"\"\"\"\"\"\t\t\t\t)]\r self._logger.info(f\"Moving {dest_folder} to {utils_file}\"\t\t\t\t)\r shutil.copy(snake_case\t\t,snake_case\t\t\t\t)\r except KeyError:\r self._logger.error(f\"Cannot find destination folder for {utils_file}. Please copy manually.\"\t\t\t\t)\r\r if with_manual_update:\r for file_path in with_manual_update:\r self._logger.warning(\r f\"You need to manually update file {file_path} to remove configurations using 'TextEncoderConfig'.\"\t\t\t\t)\r"},"style_context_codestyle":{"kind":"number","value":285,"string":"285"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":290,"cells":{"code":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\n\n\n\n\nlowercase_\t\t = \"\\n# Transformers installation\\n! pip install transformers datasets\\n# To install from source instead of the last release, comment the command above and uncomment the following one.\\n# ! pip install git+https://github.com/huggingface/transformers.git\\n\"\n\nlowercase_\t\t = [{\"type\": \"code\", \"content\": INSTALL_CONTENT}]\nlowercase_\t\t = {\n \"{processor_class}\": \"FakeProcessorClass\",\n \"{model_class}\": \"FakeModelClass\",\n \"{object_class}\": \"FakeObjectClass\",\n}\n\n\n\n"},"code_codestyle":{"kind":"number","value":211,"string":"211"},"style_context":{"kind":"string","value":"\n\n\n\n'''simple docstring'''\n\n\n\n\n\n# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim\n\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple, Union\n\nimport flax\nimport jax\nimport jax.numpy as jnp\n\nfrom ..configuration_utils import ConfigMixin, register_to_config\nfrom .scheduling_utils_flax import (\n CommonSchedulerState,\n FlaxKarrasDiffusionSchedulers,\n FlaxSchedulerMixin,\n FlaxSchedulerOutput,\n add_noise_common,\n get_velocity_common,\n)\n\n\n\n\n\n\n@flax.struct.dataclass\nclass __A\t\t\t:\n\n\n\n '''simple docstring'''\n\n\n\n\n\n\n\n __lowerCamelCase : CommonSchedulerState\n\n # setable values\n __lowerCamelCase : jnp.ndarray\n __lowerCamelCase : jnp.ndarray\n __lowerCamelCase : Optional[int] = None\n\n\n\n @classmethod\n def \t\t\t\t\ta__ (cls , A , A , A ) -> str:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n return cls(common=A , init_noise_sigma=A , timesteps=A )\n\n\n\n\n\n\n@dataclass\nclass __A\t\t\t( A\t\t\t\t\t\t):\n\n\n\n '''simple docstring'''\n\n\n\n\n\n\n\n __lowerCamelCase : DDPMSchedulerState\n\n\n\n\n\n\nclass __A\t\t\t( A , A\t\t\t\t\t\t):\n\n\n\n '''simple docstring'''\n\n\n\n\n\n\n\n __lowerCamelCase : Dict = [e.name for e in FlaxKarrasDiffusionSchedulers]\n\n __lowerCamelCase : jnp.dtype\n\n\n\n @property\n def \t\t\t\t\ta__ (self ) -> List[str]:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n return True\n\n\n\n @register_to_config\n def __init__(self , A = 1_000 , A = 0.0001 , A = 0.02 , A = \"linear\" , A = None , A = \"fixed_small\" , A = True , A = \"epsilon\" , A = jnp.floataa , ) -> Union[str, Any]:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n _a = dtype\n\n\n\n def \t\t\t\t\ta__ (self , A = None ) -> DDPMSchedulerState:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n if common is None:\n _a = CommonSchedulerState.create(self )\n\n # standard deviation of the initial noise distribution\n _a = jnp.array(1.0 , dtype=self.dtype )\n\n _a = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1]\n\n return DDPMSchedulerState.create(\n common=A , init_noise_sigma=A , timesteps=A , )\n\n\n\n def \t\t\t\t\ta__ (self , A , A , A = None ) -> jnp.ndarray:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n return sample\n\n\n\n def \t\t\t\t\ta__ (self , A , A , A = () ) -> DDPMSchedulerState:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n _a = self.config.num_train_timesteps // num_inference_steps\n # creates integer timesteps by multiplying by ratio\n # rounding to avoid issues when num_inference_step is power of 3\n _a = (jnp.arange(0 , A ) * step_ratio).round()[::-1]\n\n return state.replace(\n num_inference_steps=A , timesteps=A , )\n\n\n\n def \t\t\t\t\ta__ (self , A , A , A=None , A=None ) -> int:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n _a = state.common.alphas_cumprod[t]\n _a = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )\n\n # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)\n # and sample from it to get previous sample\n # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample\n _a = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t]\n\n if variance_type is None:\n _a = self.config.variance_type\n\n # hacks - were probably added for training stability\n if variance_type == \"fixed_small\":\n _a = jnp.clip(A , a_min=1E-20 )\n # for rl-diffuser https://arxiv.org/abs/2205.09991\n elif variance_type == \"fixed_small_log\":\n _a = jnp.log(jnp.clip(A , a_min=1E-20 ) )\n elif variance_type == \"fixed_large\":\n _a = state.common.betas[t]\n elif variance_type == \"fixed_large_log\":\n # Glide max_log\n _a = jnp.log(state.common.betas[t] )\n elif variance_type == \"learned\":\n return predicted_variance\n elif variance_type == \"learned_range\":\n _a = variance\n _a = state.common.betas[t]\n _a = (predicted_variance + 1) / 2\n _a = frac * max_log + (1 - frac) * min_log\n\n return variance\n\n\n\n def \t\t\t\t\ta__ (self , A , A , A , A , A = None , A = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n _a = timestep\n\n if key is None:\n _a = jax.random.PRNGKey(0 )\n\n if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in [\"learned\", \"learned_range\"]:\n _a , _a = jnp.split(A , sample.shape[1] , axis=1 )\n else:\n _a = None\n\n # 1. compute alphas, betas\n _a = state.common.alphas_cumprod[t]\n _a = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )\n _a = 1 - alpha_prod_t\n _a = 1 - alpha_prod_t_prev\n\n # 2. compute predicted original sample from predicted noise also called\n # \"predicted x_0\" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf\n if self.config.prediction_type == \"epsilon\":\n _a = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5\n elif self.config.prediction_type == \"sample\":\n _a = model_output\n elif self.config.prediction_type == \"v_prediction\":\n _a = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output\n else:\n raise ValueError(\n f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` '''\n ''' for the FlaxDDPMScheduler.''' )\n\n # 3. Clip \"predicted x_0\"\n if self.config.clip_sample:\n _a = jnp.clip(A , -1 , 1 )\n\n # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t\n # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf\n _a = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t\n _a = state.common.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t\n\n # 5. Compute predicted previous sample µ_t\n # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf\n _a = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample\n\n # 6. Add noise\n def random_variance():\n _a = jax.random.split(A , num=1 )\n _a = jax.random.normal(A , shape=model_output.shape , dtype=self.dtype )\n return (self._get_variance(A , A , predicted_variance=A ) ** 0.5) * noise\n\n _a = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) )\n\n _a = pred_prev_sample + variance\n\n if not return_dict:\n return (pred_prev_sample, state)\n\n return FlaxDDPMSchedulerOutput(prev_sample=A , state=A )\n\n\n\n def \t\t\t\t\ta__ (self , A , A , A , A , ) -> jnp.ndarray:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n return add_noise_common(state.common , A , A , A )\n\n\n\n def \t\t\t\t\ta__ (self , A , A , A , A , ) -> jnp.ndarray:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n return get_velocity_common(state.common , A , A , A )\n\n\n\n def __len__(self ) -> Tuple:\n\n\n \"\"\"simple docstring\"\"\"\n\n\n\n return self.config.num_train_timesteps\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":211,"string":"211"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":291,"cells":{"code":{"kind":"string","value":"\"\"\"simple docstring\"\"\"\r\n\r\nfrom __future__ import annotations\r\n\r\nimport os\r\nfrom collections.abc import Mapping\r\n\r\n__lowercase\t\t\t\t =\t\t\t\t\t\t\ttuple[int, int]\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass \t\t\t\t\t\t_lowercase\t\t\t\t:\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef __init__(\t\t\t\t\t\t\tself : Optional[int] ,\t\t\t\tUpperCamelCase__ : set[int] ,\t\t\t\tUpperCamelCase__ : Mapping[EdgeT, int]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tNone:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=vertices\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t={\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t (min(UpperCamelCase__\t\t\t\t\t\t\t), max(UpperCamelCase__\t\t\t\t\t\t\t)): weight for edge, weight in edges.items()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : str ,\t\t\t\tUpperCamelCase__ : EdgeT ,\t\t\t\tUpperCamelCase__ : int\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tNone:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.vertices.add(edge[0]\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.vertices.add(edge[1]\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=weight\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef UpperCAmelCase_\t\t\t\t(\t\t\t\t\t\t\tself : List[Any]\t\t\t\t\t\t\t)\t\t\t\t\t\t\t->\t\t\t\t\t\t\tGraph:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=Graph({min(self.vertices\t\t\t\t\t\t\t)} ,\t\t\t\t{}\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=42\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=42\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=42\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=42\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\twhile len(subgraph.vertices\t\t\t\t\t\t\t) < len(self.vertices\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=max(self.edges.values()\t\t\t\t\t\t\t) + 1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor edge, weight in self.edges.items():\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif weight < min_weight:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=edge\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=weight\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsubgraph.add_edge(UpperCamelCase__ ,\t\t\t\tUpperCamelCase__\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn subgraph\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef lowerCAmelCase\t(__UpperCamelCase : str = \"p107_network.txt\"\t):\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=os.path.abspath(os.path.dirname(__UpperCamelCase\t)\t)\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=os.path.join(__UpperCamelCase ,\t\t\t__UpperCamelCase\t)\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t={}\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=42\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=42\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=42\r\n\r\n\t\t\t\t\t\t\twith open(__UpperCamelCase\t) as f:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=f.read().strip().split('''\\n'''\t)\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=[line.split(''','''\t) for line in data]\r\n\r\n\t\t\t\t\t\t\tfor edgea in range(1 ,\t\t\tlen(__UpperCamelCase\t)\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor edgea in range(__UpperCamelCase\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif adjaceny_matrix[edgea][edgea] != \"-\":\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=int(adjaceny_matrix[edgea][edgea]\t)\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=Graph(set(range(len(__UpperCamelCase\t)\t)\t) ,\t\t\t__UpperCamelCase\t)\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=graph.prims_algorithm()\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=sum(graph.edges.values()\t)\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=sum(subgraph.edges.values()\t)\r\n\r\n\t\t\t\t\t\t\treturn initial_total - optimal_total\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\tprint(f'''{solution() = }''')\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":85,"string":"85"},"style_context":{"kind":"string","value":"\"\"\"simple docstring\"\"\"\r\n\r\ndef lowerCAmelCase\t(__UpperCamelCase : Dict ,\t\t\t__UpperCamelCase : Optional[Any]\t):\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=[0 for i in range(r + 1\t)]\r\n\t\t\t\t\t\t\t# nc0 = 1\r\n\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=1\r\n\t\t\t\t\t\t\tfor i in range(1 ,\t\t\tn + 1\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t# to compute current row from previous row.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t\t=min(__UpperCamelCase ,\t\t\t__UpperCamelCase\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twhile j > 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tc[j] += c[j - 1]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tj -= 1\r\n\t\t\t\t\t\t\treturn c[r]\r\n\r\n\r\n\r\n\r\n\r\n\r\nprint(binomial_coefficient(n=10, r=5))\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":85,"string":"85"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":292,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\nfrom typing import TYPE_CHECKING\r\n\r\nfrom ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available\r\nfrom ...utils import OptionalDependencyNotAvailable\r\n\r\n\r\nlowerCAmelCase =\t\t\t\t\t\t\t{'configuration_dpt': ['DPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DPTConfig']}\r\n\r\ntry:\r\n\t\t\tif not is_vision_available():\r\n\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\nexcept OptionalDependencyNotAvailable:\r\n\t\t\tpass\r\nelse:\r\n\t\t\tlowerCAmelCase =\t\t\t\t\t\t\t['DPTFeatureExtractor']\r\n\t\t\tlowerCAmelCase =\t\t\t\t\t\t\t['DPTImageProcessor']\r\n\r\ntry:\r\n\t\t\tif not is_torch_available():\r\n\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\nexcept OptionalDependencyNotAvailable:\r\n\t\t\tpass\r\nelse:\r\n\t\t\tlowerCAmelCase =\t\t\t\t\t\t\t[\r\n\t\t\t 'DPT_PRETRAINED_MODEL_ARCHIVE_LIST',\r\n\t\t\t 'DPTForDepthEstimation',\r\n\t\t\t 'DPTForSemanticSegmentation',\r\n\t\t\t 'DPTModel',\r\n\t\t\t 'DPTPreTrainedModel',\r\n\t\t\t]\r\n\r\n\r\nif TYPE_CHECKING:\r\n\t\t\tfrom .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig\r\n\r\n\t\t\ttry:\r\n\t\t\t\t\t\tif not is_vision_available():\r\n\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\n\t\t\texcept OptionalDependencyNotAvailable:\r\n\t\t\t\t\t\tpass\r\n\t\t\telse:\r\n\t\t\t\t\t\tfrom .feature_extraction_dpt import DPTFeatureExtractor\r\n\t\t\t\t\t\tfrom .image_processing_dpt import DPTImageProcessor\r\n\r\n\t\t\ttry:\r\n\t\t\t\t\t\tif not is_torch_available():\r\n\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\r\n\t\t\texcept OptionalDependencyNotAvailable:\r\n\t\t\t\t\t\tpass\r\n\t\t\telse:\r\n\t\t\t\t\t\tfrom .modeling_dpt import (\r\n\t\t\t\t\t\t DPT_PRETRAINED_MODEL_ARCHIVE_LIST,\r\n\t\t\t\t\t\t DPTForDepthEstimation,\r\n\t\t\t\t\t\t DPTForSemanticSegmentation,\r\n\t\t\t\t\t\t DPTModel,\r\n\t\t\t\t\t\t DPTPreTrainedModel,\r\n\t\t\t\t\t\t)\r\n\r\n\r\nelse:\r\n\t\t\timport sys\r\n\r\n\t\t\tlowerCAmelCase =\t\t\t\t\t\t\t_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":110,"string":"110"},"style_context":{"kind":"string","value":"\r\n\r\n\r\ndef \t\t\t_a ( SCREAMING_SNAKE_CASE ):\r\n\r\n\r\n\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\treturn credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') )\r\ndef \t\t\t_a ( SCREAMING_SNAKE_CASE ):\r\n\r\n\r\n\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\tlowercase__ = credit_card_number\r\n\t\tlowercase__ = 0\r\n\t\tlowercase__ = len(SCREAMING_SNAKE_CASE ) - 2\r\n\t\tfor i in range(SCREAMING_SNAKE_CASE\t\t\t\t\t\t,\t\t\t\t-1\t\t\t\t\t\t,\t\t\t\t-2 ):\r\n\t\t\t\t# double the value of every second digit\r\n\t\t\t\tlowercase__ = int(cc_number[i] )\r\n\t\t\t\tdigit *= 2\r\n\t\t\t\t# If doubling of a number results in a two digit number\r\n\t\t\t\t# i.e greater than 9(e.g., 6 × 2 = 12),\r\n\t\t\t\t# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),\r\n\t\t\t\t# to get a single digit number.\r\n\t\t\t\tif digit > 9:\r\n\t\t\t\t\t\tdigit %= 10\r\n\t\t\t\t\t\tdigit += 1\r\n\t\t\t\tlowercase__ = cc_number[:i] + str(SCREAMING_SNAKE_CASE ) + cc_number[i + 1 :]\r\n\t\t\t\ttotal += digit\r\n\r\n\t\t# Sum up the remaining digits\r\n\t\tfor i in range(len(SCREAMING_SNAKE_CASE ) - 1\t\t\t\t\t\t,\t\t\t\t-1\t\t\t\t\t\t,\t\t\t\t-2 ):\r\n\t\t\t\ttotal += int(cc_number[i] )\r\n\r\n\t\treturn total % 10 == 0\r\ndef \t\t\t_a ( SCREAMING_SNAKE_CASE ):\r\n\r\n\r\n\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\t\tlowercase__ = f'{credit_card_number} is an invalid credit card number because'\r\n\t\tif not credit_card_number.isdigit():\r\n\t\t\t\tprint(f'{error_message} it has nonnumerical characters.' )\r\n\t\t\t\treturn False\r\n\r\n\t\tif not 13 <= len(SCREAMING_SNAKE_CASE ) <= 16:\r\n\t\t\t\tprint(f'{error_message} of its length.' )\r\n\t\t\t\treturn False\r\n\r\n\t\tif not validate_initial_digits(SCREAMING_SNAKE_CASE ):\r\n\t\t\t\tprint(f'{error_message} of its first two digits.' )\r\n\t\t\t\treturn False\r\n\r\n\t\tif not luhn_validation(SCREAMING_SNAKE_CASE ):\r\n\t\t\t\tprint(f'{error_message} it fails the Luhn check.' )\r\n\t\t\t\treturn False\r\n\r\n\t\tprint(f'{credit_card_number} is a valid credit card number.' )\r\n\t\treturn True\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\timport doctest\r\n\r\n\t\t\tdoctest.testmod()\r\n\t\t\tvalidate_credit_card_number('4111111111111111')\r\n\t\t\tvalidate_credit_card_number('32323')\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":110,"string":"110"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":293,"cells":{"code":{"kind":"string","value":"from timeit import timeit\r\n\r\n__UpperCamelCase\t\t:\tDict \t\t\t\t\t\t=\t\t\t\t\t{\r\n 'MALAYALAM': True,\r\n 'String': False,\r\n 'rotor': True,\r\n 'level': True,\r\n 'A': True,\r\n 'BB': True,\r\n 'ABC': False,\r\n 'amanaplanacanalpanama': True, # \"a man a plan a canal panama\"\r\n}\r\n# Ensure our test data is valid\r\nassert all((key == key[::-1]) is value for key, value in test_data.items())\r\ndef \t\t\t\tA ( _lowercase\t\t\t\t\t\t):\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Any =\t\t\t\t\t\t\t0\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: str =\t\t\t\t\t\t\tlen(_lowercase\t\t\t\t\t\t) - 1\r\n\t\t\t\t\t\twhile start_i < end_i:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif s[start_i] == s[end_i]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart_i += 1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tend_i -= 1\r\n\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn False\r\n\t\t\t\t\t\treturn True\r\ndef \t\t\t\tA ( _lowercase\t\t\t\t\t\t):\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Tuple =\t\t\t\t\t\t\tlen(_lowercase\t\t\t\t\t\t) // 2\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str] =\t\t\t\t\t\t\tlen(_lowercase\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t# We need to traverse till half of the length of string\r\n\t\t\t\t\t\t# as we can get access of the i'th last element from\r\n\t\t\t\t\t\t# i'th index.\r\n\t\t\t\t\t\t# eg: [0,1,2,3,4,5] => 4th index can be accessed\r\n\t\t\t\t\t\t# with the help of 1st index (i==n-i-1)\r\n\t\t\t\t\t\t# where n is length of string\r\n\t\t\t\t\t\treturn all(s[i] == s[n - i - 1] for i in range(_lowercase\t\t\t\t\t\t)\t\t\t\t\t\t)\r\ndef \t\t\t\tA ( _lowercase\t\t\t\t\t\t):\r\n\t\t\t\t\t\tif len(_lowercase\t\t\t\t\t\t) <= 2:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn True\r\n\t\t\t\t\t\tif s[0] == s[len(_lowercase\t\t\t\t\t\t) - 1]:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn is_palindrome_recursive(s[1:-1]\t\t\t\t\t\t)\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn False\r\ndef \t\t\t\tA ( _lowercase\t\t\t\t\t\t):\r\n\t\t\t\t\t\treturn s == s[::-1]\r\ndef \t\t\t\tA ( _lowercase\t\t\t\t\t\t):\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Any =\t\t\t\t\t\t\tf\"\"\"all({name}(key) is value for key, value in test_data.items())\"\"\"\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: str =\t\t\t\t\t\t\tf\"\"\"from __main__ import test_data, {name}\"\"\"\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[Any] =\t\t\t\t\t\t\t500_000\r\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[Any] =\t\t\t\t\t\t\ttimeit(stmt=_lowercase\t\t, setup=_lowercase\t\t, number=_lowercase\t\t\t\t\t\t)\r\n\t\t\t\t\t\tprint(f\"\"\"{name:<35} finished {number:,} runs in {result:.5f} seconds\"\"\"\t\t\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\t\t\t\t\tfor key, value in test_data.items():\r\n\t\t\t\t\t\t\t\t\t\tassert is_palindrome(key) is is_palindrome_recursive(key)\r\n\t\t\t\t\t\t\t\t\t\tassert is_palindrome(key) is is_palindrome_slice(key)\r\n\t\t\t\t\t\t\t\t\t\tprint(f\"\"\"{key:21} {value}\"\"\")\r\n\t\t\t\t\tprint('a man a plan a canal panama')\r\n\r\n\t\t\t\t\t# finished 500,000 runs in 0.46793 seconds\r\n\t\t\t\t\tbenchmark_function('is_palindrome_slice')\r\n\t\t\t\t\t# finished 500,000 runs in 0.85234 seconds\r\n\t\t\t\t\tbenchmark_function('is_palindrome')\r\n\t\t\t\t\t# finished 500,000 runs in 1.32028 seconds\r\n\t\t\t\t\tbenchmark_function('is_palindrome_recursive')\r\n\t\t\t\t\t# finished 500,000 runs in 2.08679 seconds\r\n\t\t\t\t\tbenchmark_function('is_palindrome_traversal')\r\n\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":258,"string":"258"},"style_context":{"kind":"string","value":"import os\r\nfrom typing import List, Optional, Union\r\n\r\nfrom ...tokenization_utils import PreTrainedTokenizer\r\nfrom ...tokenization_utils_base import AddedToken\r\nfrom ...utils import logging\r\n\r\n\r\n__UpperCamelCase\t\t:\tAny \t\t\t\t\t\t=\t\t\t\t\tlogging.get_logger(__name__)\r\n\r\n__UpperCamelCase\t\t:\tTuple \t\t\t\t\t\t=\t\t\t\t\t{'vocab_file': 'vocab.txt'}\r\n\r\n__UpperCamelCase\t\t:\tTuple \t\t\t\t\t\t=\t\t\t\t\t{\r\n 'vocab_file': {\r\n 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt',\r\n 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt',\r\n },\r\n}\r\n\r\n__UpperCamelCase\t\t:\tUnion[str, Any] \t\t\t\t\t\t=\t\t\t\t\t{\r\n 'facebook/esm2_t6_8M_UR50D': 1024,\r\n 'facebook/esm2_t12_35M_UR50D': 1024,\r\n}\r\ndef \t\t\t\tA ( _lowercase\t\t\t\t\t\t):\r\n\t\t\t\t\t\twith open(_lowercase\t\t, '''r'''\t\t\t\t\t\t) as f:\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Optional[int] =\t\t\t\t\t\t\tf.read().splitlines()\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn [l.strip() for l in lines]\r\n\r\n\r\n\r\n\r\n\r\nclass lowercase__\t\t\t\t\t\t( UpperCamelCase_):\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t=\t\tVOCAB_FILES_NAMES\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t=\t\tPRETRAINED_VOCAB_FILES_MAP\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t=\t\tPRETRAINED_POSITIONAL_EMBEDDINGS_SIZES\r\n\t\t\t\t\t\tUpperCamelCase_\t\t\t\t\t=\t\t[\"\"\"input_ids\"\"\", \"\"\"attention_mask\"\"\"]\r\n\r\n\r\n\t\t\t\t\t\tdef __init__(\tself : str ,\t\tUpperCamelCase__ : List[str] ,\t\tUpperCamelCase__ : Tuple=\"\" ,\t\tUpperCamelCase__ : Union[str, Any]=\"\" ,\t\tUpperCamelCase__ : Dict=\"\" ,\t\tUpperCamelCase__ : str=\"\" ,\t\tUpperCamelCase__ : Any=\"\" ,\t\t**UpperCamelCase__ : int ,\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(**UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Union[str, Any] =\t\t\t\t\t\t\tload_vocab_file(UpperCamelCase__\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: int =\t\t\t\t\t\t\tdict(enumerate(self.all_tokens\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[Any] =\t\t\t\t\t\t\t{tok: ind for ind, tok in enumerate(self.all_tokens\t\t\t\t\t\t)}\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Union[str, Any] =\t\t\t\t\t\t\tunk_token\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Any =\t\t\t\t\t\t\tcls_token\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str] =\t\t\t\t\t\t\tpad_token\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str] =\t\t\t\t\t\t\tmask_token\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: Any =\t\t\t\t\t\t\teos_token\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str] =\t\t\t\t\t\t\tself.all_tokens\r\n\t\t\t\t\t\t\t\t\t\t\t\tself._create_trie(self.unique_no_split_tokens\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : Union[str, Any] ,\t\tUpperCamelCase__ : int\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self._id_to_token.get(UpperCamelCase__ ,\t\tself.unk_token\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : Dict ,\t\tUpperCamelCase__ : str\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self._token_to_id.get(UpperCamelCase__ ,\t\tself._token_to_id.get(self.unk_token\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : List[Any] ,\t\tUpperCamelCase__ : Union[str, Any] ,\t\t**UpperCamelCase__ : List[Any]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn text.split()\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : List[str] ,\t\tUpperCamelCase__ : Dict=False\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn len(self._id_to_token\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : Optional[Any]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn {token: i for i, token in enumerate(self.all_tokens\t\t\t\t\t\t)}\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : Union[str, Any] ,\t\tUpperCamelCase__ : str\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self._token_to_id.get(UpperCamelCase__ ,\t\tself._token_to_id.get(self.unk_token\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : List[str] ,\t\tUpperCamelCase__ : int\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self._id_to_token.get(UpperCamelCase__ ,\t\tself.unk_token\t\t\t\t\t\t)\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : str ,\t\tUpperCamelCase__ : List[int] ,\t\tUpperCamelCase__ : Optional[List[int]] = None\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: str =\t\t\t\t\t\t\t[self.cls_token_id]\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str] =\t\t\t\t\t\t\t[self.eos_token_id] # No sep token in ESM vocabulary\r\n\t\t\t\t\t\t\t\t\t\t\t\tif token_ids_a is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif self.eos_token_id is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn cls + token_ids_a\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn cls + token_ids_a + sep\r\n\t\t\t\t\t\t\t\t\t\t\t\telif self.eos_token_id is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!'''\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : Union[str, Any] ,\t\tUpperCamelCase__ : List ,\t\tUpperCamelCase__ : Optional[List] = None ,\t\tUpperCamelCase__ : bool = False\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif already_has_special_tokens:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif token_ids_a is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''You should not supply a second sequence if the provided sequence of '''\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t '''ids is already formatted with special tokens for the model.'''\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn [1 if token in self.all_special_ids else 0 for token in token_ids_a]\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: List[str] =\t\t\t\t\t\t\t[1] + ([0] * len(UpperCamelCase__\t\t\t\t\t\t)) + [1]\r\n\t\t\t\t\t\t\t\t\t\t\t\tif token_ids_a is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tmask += [0] * len(UpperCamelCase__\t\t\t\t\t\t) + [1]\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn mask\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : int ,\t\tUpperCamelCase__ : List[Any] ,\t\tUpperCamelCase__ : List[str]\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE\t\t\t\t\t\t\t: str =\t\t\t\t\t\t\tos.path.join(UpperCamelCase__ ,\t\t(filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt'''\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\twith open(UpperCamelCase__ ,\t\t'''w'''\t\t\t\t\t\t) as f:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tf.write('''\\n'''.join(self.all_tokens\t\t\t\t\t\t)\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn (vocab_file,)\r\n\r\n\r\n\t\t\t\t\t\t@property\r\n\t\t\t\t\t\tdef \t__A\t(\tself : Dict\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.get_vocab_size(with_added_tokens=UpperCamelCase__\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef \t__A\t(\tself : str ,\t\tUpperCamelCase__ : Union[List[str], List[AddedToken]] ,\t\tUpperCamelCase__ : bool = False\t\t\t\t\t\t):\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t'''simple docstring'''\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn super()._add_tokens(UpperCamelCase__ ,\t\tspecial_tokens=UpperCamelCase__\t\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":258,"string":"258"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":294,"cells":{"code":{"kind":"string","value":"from __future__ import annotations\r\n\r\nimport string\r\nfrom itertools import cycle, product\r\nfrom pathlib import Path\r\n\r\n_snake_case\t\t\t\t\t\t\t\t= (\r\n string.ascii_letters + string.digits + string.punctuation + string.whitespace\r\n)\r\n_snake_case\t\t\t\t\t\t\t\t= [ord(letter) for letter in string.ascii_lowercase]\r\n_snake_case\t\t\t\t\t\t\t\t= {ord(char) for char in VALID_CHARS}\r\n\r\n_snake_case\t\t\t\t\t\t\t\t= ['''the''', '''be''', '''to''', '''of''', '''and''', '''in''', '''that''', '''have''']\r\n\r\n\r\n\r\n\r\ndef _UpperCamelCase (\tsnake_case__,\t\t\tsnake_case__\t\t\t\t\t\t\t) -> str | None:\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tUnion[str, Any] \t\t\t= \"\"\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tstr \t\t\t= 42\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tList[Any] \t\t\t= 42\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tOptional[Any] \t\t\t= 42\r\n\r\n\t\t\t\t\t\t\tfor keychar, cipherchar in zip(cycle(UpperCamelCase_\t\t\t\t\t\t\t),\t\t\tUpperCamelCase_\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCAmelCase :\tAny \t\t\t= cipherchar ^ keychar\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif decodedchar not in VALID_INTS:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn None\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdecoded += chr(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\treturn decoded\r\n\r\n\r\n\r\n\r\ndef _UpperCamelCase (\tsnake_case__\t\t\t\t\t\t\t) -> list[str]:\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tOptional[Any] \t\t\t= []\r\n\t\t\t\t\t\t\tfor key in product(UpperCamelCase_,\t\t\trepeat=3\t\t\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCAmelCase :\tint \t\t\t= try_key(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif encoded is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpossibles.append(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\treturn possibles\r\n\r\n\r\n\r\n\r\ndef _UpperCamelCase (\tsnake_case__,\t\t\tsnake_case__\t\t\t\t\t\t\t) -> list[str]:\r\n\t\t\t\t\t\t\treturn [possible for possible in possibles if common_word in possible.lower()]\r\n\r\n\r\n\r\n\r\ndef _UpperCamelCase (\tsnake_case__ = \"p059_cipher.txt\"\t\t\t\t\t\t\t) -> int:\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tDict \t\t\t= 42\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tList[Any] \t\t\t= 42\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tTuple \t\t\t= 42\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tint \t\t\t= 42\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tList[str] \t\t\t= Path(UpperCamelCase_\t\t\t\t\t\t\t).parent.joinpath(UpperCamelCase_\t\t\t\t\t\t\t).read_text(encoding=\"utf-8\"\t\t\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tAny \t\t\t= [int(UpperCamelCase_\t\t\t\t\t\t\t) for number in data.strip().split(\",\"\t\t\t\t\t\t\t)]\r\n\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tList[Any] \t\t\t= filter_valid_chars(UpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\tfor common_word in COMMON_WORDS:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t__UpperCAmelCase :\tUnion[str, Any] \t\t\t= filter_common_word(UpperCamelCase_,\t\t\tUpperCamelCase_\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif len(UpperCamelCase_\t\t\t\t\t\t\t) == 1:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\r\n\t\t\t\t\t\t\t__UpperCAmelCase :\tDict \t\t\t= possibles[0]\r\n\t\t\t\t\t\t\treturn sum(ord(UpperCamelCase_\t\t\t\t\t\t\t) for char in decoded_text\t\t\t\t\t\t\t)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tprint(F'{solution() = }')\r\n\r\n\r\n\r\n\r\n"},"code_codestyle":{"kind":"number","value":157,"string":"157"},"style_context":{"kind":"string","value":"\r\r\r\r\r\r\rimport math\r\rimport numpy as np\rimport qiskit\rfrom qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute\r\r\rdef \t\t\t\t_a ( UpperCamelCase_ : int = 3 ) -> qiskit.result.counts.Counts:\r\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\r\r\r\r\r\r\r\t\t\t\t\t\tif isinstance(UpperCamelCase_\t\t\t, UpperCamelCase_ ):\r\t\t\t\t\t\t\t\t\t\t\t\traise TypeError(\"number of qubits must be a integer.\" )\r\t\t\t\t\t\tif number_of_qubits <= 0:\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"number of qubits must be > 0.\" )\r\t\t\t\t\t\tif math.floor(UpperCamelCase_ ) != number_of_qubits:\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"number of qubits must be exact integer.\" )\r\t\t\t\t\t\tif number_of_qubits > 10:\r\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\"number of qubits too large to simulate(>10).\" )\r\r\t\t\t\t\t\tlowerCAmelCase__ \t\t\t\t\t= QuantumRegister(UpperCamelCase_\t\t\t, \"qr\" )\r\t\t\t\t\t\tlowerCAmelCase__ \t\t\t\t\t= ClassicalRegister(UpperCamelCase_\t\t\t, \"cr\" )\r\r\t\t\t\t\t\tlowerCAmelCase__ \t\t\t\t\t= QuantumCircuit(UpperCamelCase_\t\t\t, UpperCamelCase_ )\r\r\t\t\t\t\t\tlowerCAmelCase__ \t\t\t\t\t= number_of_qubits\r\r\t\t\t\t\t\tfor i in range(UpperCamelCase_ ):\r\t\t\t\t\t\t\t\t\t\t\t\tquantum_circuit.h(number_of_qubits - i - 1 )\r\t\t\t\t\t\t\t\t\t\t\t\tcounter -= 1\r\t\t\t\t\t\t\t\t\t\t\t\tfor j in range(UpperCamelCase_ ):\r\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tquantum_circuit.cp(np.pi / 2 ** (counter - j)\t\t\t, UpperCamelCase_\t\t\t, UpperCamelCase_ )\r\r\t\t\t\t\t\tfor k in range(number_of_qubits // 2 ):\r\t\t\t\t\t\t\t\t\t\t\t\tquantum_circuit.swap(UpperCamelCase_\t\t\t, number_of_qubits - k - 1 )\r\r\t\t\t\t\t\t# measure all the qubits\r\t\t\t\t\t\tquantum_circuit.measure(UpperCamelCase_\t\t\t, UpperCamelCase_ )\r\t\t\t\t\t\t# simulate with 10000 shots\r\t\t\t\t\t\tlowerCAmelCase__ \t\t\t\t\t= Aer.get_backend(\"qasm_simulator\" )\r\t\t\t\t\t\tlowerCAmelCase__ \t\t\t\t\t= execute(UpperCamelCase_\t\t\t, UpperCamelCase_\t\t\t, shots=10_000 )\r\r\t\t\t\t\t\treturn job.result().get_counts(UpperCamelCase_ )\r\r\rif __name__ == \"__main__\":\r\tprint(\r\t F\"Total count for quantum fourier transform state is: \\\n {quantum_fourier_transform(3)}\"\r\t)\r\r\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":340,"string":"340"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":295,"cells":{"code":{"kind":"string","value":"\ndef \t\t\t\t\t\t\t_lowercase\t\t\t\t\t\t\t(\t\t\t\t\tUpperCamelCase_\t\t)\t\t->\t\tbool:\n\t\t\t\t\t'''simple docstring'''\n\n\n\t\t\t\t\tif num < 0:\n\t\t\t\t\t\t\t\t\t\treturn False\n\n\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tnum\n\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t0\n\t\t\t\t\twhile num > 0:\n\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\trev_num * 10 + (num % 10)\n\t\t\t\t\t\t\t\t\t\tnum //= 10\n\n\t\t\t\t\treturn num_copy == rev_num\n\n\nif __name__ == \"__main__\":\n\t\timport doctest\n\n\t\tdoctest.testmod()\n\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":355,"string":"355"},"style_context":{"kind":"string","value":"\nimport shutil\nimport tempfile\nimport unittest\n\nfrom transformers import (\n SPIECE_UNDERLINE,\n AddedToken,\n BatchEncoding,\n NllbTokenizer,\n NllbTokenizerFast,\n is_torch_available,\n)\nfrom transformers.testing_utils import (\n get_tests_dir,\n nested_simplify,\n require_sentencepiece,\n require_tokenizers,\n require_torch,\n)\n\nfrom ...test_tokenization_common import TokenizerTesterMixin\n\n\n__snake_case\t\t\t\t\t\t\t = get_tests_dir(\"\"\"fixtures/test_sentencepiece.model\"\"\")\n\n\nif is_torch_available():\n\t\t\t\tfrom transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right\n\n__snake_case\t\t\t\t\t\t\t = 25_60_47\n__snake_case\t\t\t\t\t\t\t = 25_61_45\n\n\n\n\n@require_sentencepiece\n@require_tokenizers\nclass \t\t\t\t\t\tlowercase__ (\t\t\t\t\t\t_UpperCAmelCase\t\t\t\t\t,\tunittest.TestCase ):\n\tA__ : int \t=NllbTokenizer\n\tA__ : Optional[int] \t=NllbTokenizerFast\n\tA__ : Union[str, Any] \t=True\n\tA__ : Dict \t=True\n\tA__ : Tuple \t={}\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: List[str]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tsuper().setUp()\n\n\t\t\t\t\t\t# We have a SentencePiece fixture for testing\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tNllbTokenizer(UpperCAmelCase_\t, keep_accents=UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\ttokenizer.save_pretrained(self.tmpdirname\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Union[str, Any]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tNllbTokenizer(UpperCAmelCase_\t, keep_accents=UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.tokenize('This is a test'\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertListEqual(UpperCAmelCase_\t, ['▁This', '▁is', '▁a', '▁t', 'est']\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\tself.assertListEqual(\n\t\t\t\t\t\t tokenizer.convert_tokens_to_ids(UpperCAmelCase_\t\t\t\t\t\t\t)\t, [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]\t, )\n\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.tokenize('I was born in 92000, and this is falsé.'\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertListEqual(\n\t\t\t\t\t\t UpperCAmelCase_\t, [\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'I',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'was',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'b',\n\t\t\t\t\t\t 'or',\n\t\t\t\t\t\t 'n',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'in',\n\t\t\t\t\t\t SPIECE_UNDERLINE + '',\n\t\t\t\t\t\t '9',\n\t\t\t\t\t\t '2',\n\t\t\t\t\t\t '0',\n\t\t\t\t\t\t '0',\n\t\t\t\t\t\t '0',\n\t\t\t\t\t\t ',',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'and',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'this',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'is',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'f',\n\t\t\t\t\t\t 'al',\n\t\t\t\t\t\t 's',\n\t\t\t\t\t\t 'é',\n\t\t\t\t\t\t '.',\n\t\t\t\t\t\t ]\t, )\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.convert_tokens_to_ids(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertListEqual(\n\t\t\t\t\t\t UpperCAmelCase_\t, [\n\t\t\t\t\t\t value + tokenizer.fairseq_offset\n\t\t\t\t\t\t for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]\n\t\t\t\t\t\t ]\t, )\n\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.convert_ids_to_tokens(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertListEqual(\n\t\t\t\t\t\t UpperCAmelCase_\t, [\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'I',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'was',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'b',\n\t\t\t\t\t\t 'or',\n\t\t\t\t\t\t 'n',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'in',\n\t\t\t\t\t\t SPIECE_UNDERLINE + '',\n\t\t\t\t\t\t '',\n\t\t\t\t\t\t '2',\n\t\t\t\t\t\t '0',\n\t\t\t\t\t\t '0',\n\t\t\t\t\t\t '0',\n\t\t\t\t\t\t ',',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'and',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'this',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'is',\n\t\t\t\t\t\t SPIECE_UNDERLINE + 'f',\n\t\t\t\t\t\t 'al',\n\t\t\t\t\t\t 's',\n\t\t\t\t\t\t '',\n\t\t\t\t\t\t '.',\n\t\t\t\t\t\t ]\t, )\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t(self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-nllb', {})\n\t\t\t\t\t\tfor tokenizer, pretrained_name, kwargs in self.tokenizers_list:\n\t\t\t\t\t\t\t\t\t\t\twith self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(UpperCAmelCase_\t, **UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer_class.from_pretrained(UpperCAmelCase_\t, **UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttempfile.mkdtemp()\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.save_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_p.save_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Checks it save with the same files + the tokenizer.json file for the fast one\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertSequenceEqual(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Checks everything loads correctly in the same way\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.from_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_p.from_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Check special tokens are set accordingly on Rust and Python\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in tokenizer_pp.special_tokens_map:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(hasattr(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshutil.rmtree(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save tokenizer rust, legacy_format=True\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttempfile.mkdtemp()\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.save_pretrained(UpperCAmelCase_\t, legacy_format=UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_p.save_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Checks it save with the same files\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertSequenceEqual(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Checks everything loads correctly in the same way\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.from_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_p.from_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Check special tokens are set accordingly on Rust and Python\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in tokenizer_pp.special_tokens_map:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(hasattr(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshutil.rmtree(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Save tokenizer rust, legacy_format=False\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttempfile.mkdtemp()\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.save_pretrained(UpperCAmelCase_\t, legacy_format=UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_p.save_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Checks it saved the tokenizer.json file\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Checks everything loads correctly in the same way\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.from_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_p.from_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Check special tokens are set accordingly on Rust and Python\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor key in tokenizer_pp.special_tokens_map:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(hasattr(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tshutil.rmtree(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t@require_torch\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t):\n\t\t\t\t\t\tif not self.test_seqaseq:\n\t\t\t\t\t\t\t\t\t\t\treturn\n\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.get_tokenizers()\n\t\t\t\t\t\tfor tokenizer in tokenizers:\n\t\t\t\t\t\t\t\t\t\t\twith self.subTest(F'{tokenizer.__class__.__name__}'\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Longer text that will definitely require truncation.\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t[\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ' UN Chief Says There Is No Military Solution in Syria',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ' Secretary-General Ban Ki-moon says his response to Russia\\'s stepped up military support for'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ' Syria is that \\'there is no military solution\\' to the nearly five-year conflict and more weapons'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ' will only worsen the violence and misery for millions of people.',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t[\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Şeful ONU declară că nu există o soluţie militară în Siria',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ' Rusiei pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.prepare_seqaseq_batch(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t src_texts=UpperCAmelCase_\t, tgt_texts=UpperCAmelCase_\t, max_length=3\t, max_target_length=10\t, return_tensors='pt'\t, src_lang='eng_Latn'\t, tgt_lang='ron_Latn'\t, )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\texcept NotImplementedError:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(batch.input_ids.shape[1]\t, 3\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(batch.labels.shape[1]\t, 10\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# max_target_length will default to max_length if not specified\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.prepare_seqaseq_batch(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCAmelCase_\t, tgt_texts=UpperCAmelCase_\t, max_length=3\t, return_tensors='pt'\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(batch.input_ids.shape[1]\t, 3\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(batch.labels.shape[1]\t, 3\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.prepare_seqaseq_batch(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t src_texts=UpperCAmelCase_\t, max_length=3\t, max_target_length=10\t, return_tensors='pt'\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(batch_encoder_only.input_ids.shape[1]\t, 3\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(batch_encoder_only.attention_mask.shape[1]\t, 3\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertNotIn('decoder_input_ids'\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t@unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.'\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: List[Any]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tpass\n\n\n\n\n\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tfor tokenizer, pretrained_name, kwargs in self.tokenizers_list:\n\t\t\t\t\t\t\t\t\t\t\twith self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t[AddedToken(''\t, lstrip=UpperCAmelCase_\t\t\t\t\t\t\t)]\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCAmelCase_\t, additional_special_tokens=UpperCAmelCase_\t, **UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.encode('Hey this is a token'\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_r.encode(''\t, add_special_tokens=UpperCAmelCase_\t\t\t\t\t\t\t)[0]\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(special_token_id in r_output\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif self.test_slow_tokenizer:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.rust_tokenizer_class.from_pretrained(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCAmelCase_\t, additional_special_tokens=UpperCAmelCase_\t, **UpperCAmelCase_\t, )\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer_class.from_pretrained(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t UpperCAmelCase_\t, additional_special_tokens=UpperCAmelCase_\t, **UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_p.encode('Hey this is a token'\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer_cr.encode('Hey this is a token'\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertEqual(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(special_token_id in p_output\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.assertTrue(special_token_id in cr_output\t\t\t\t\t\t\t)\n\n\n\n\n\n@require_torch\n@require_sentencepiece\n@require_tokenizers\nclass \t\t\t\t\t\tlowercase__ (\t\t\t\t\t\tunittest.TestCase ):\n\tA__ : List[Any] \t=\"\"\"facebook/nllb-200-distilled-600M\"\"\"\n\tA__ : Tuple \t=[\n\t \"\"\" UN Chief Says There Is No Military Solution in Syria\"\"\",\n\t \"\"\" Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \\\"there is no military solution\\\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.\"\"\",\n\t]\n\tA__ : Optional[Any] \t=[\n\t \"\"\"Şeful ONU declară că nu există o soluţie militară în Siria\"\"\",\n\t \"\"\"Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei\"\"\"\n\t \"\"\" pentru Siria este că \\\"nu există o soluţie militară\\\" la conflictul de aproape cinci ani şi că noi arme nu vor\"\"\"\n\t \"\"\" face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.\"\"\",\n\t]\n\tA__ : Optional[int] \t=[\n\t 2_5_6_0_4_7,\n\t 1_6_2_9_7,\n\t 1_3_4_4_0_8,\n\t 8_1_6_5,\n\t 2_4_8_0_6_6,\n\t 1_4_7_3_4,\n\t 9_5_0,\n\t 1_1_3_5,\n\t 1_0_5_7_2_1,\n\t 3_5_7_3,\n\t 8_3,\n\t 2_7_3_5_2,\n\t 1_0_8,\n\t 4_9_4_8_6,\n\t 2,\n\t]\n\t@classmethod\n\tdef \t\t\t\t\tA_ ( cls\t\t\t\t\t\t\t: Tuple\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tNllbTokenizer.from_pretrained(\n\t\t\t\t\t\t cls.checkpoint_name\t, src_lang='eng_Latn'\t, tgt_lang='ron_Latn'\t\t\t\t\t\t\t)\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t1\n\t\t\t\t\t\treturn cls\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: int\t\t\t\t\t\t\t):\n\t\t\t\t\t\tself.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab']\t, 256001\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn']\t, 256002\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn']\t, 256057\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer.batch_encode_plus(self.src_text\t\t\t\t\t\t\t).input_ids[0]\n\t\t\t\t\t\tself.assertListEqual(self.expected_src_tokens\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t):\n\t\t\t\t\t\tself.assertIn(UpperCAmelCase_\t, self.tokenizer.all_special_ids\t\t\t\t\t\t\t)\n\t\t\t\t\t\t# fmt: off\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t[RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047]\n\t\t\t\t\t\t# fmt: on\n\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer.decode(UpperCAmelCase_\t, skip_special_tokens=UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer.decode(generated_ids[1:]\t, skip_special_tokens=UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertNotIn(self.tokenizer.eos_token\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: str\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t['this is gunna be a long sentence ' * 20]\n\t\t\t\t\t\tassert isinstance(src_text[0]\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\t10\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer(UpperCAmelCase_\t, max_length=UpperCAmelCase_\t, truncation=UpperCAmelCase_\t\t\t\t\t\t\t).input_ids[0]\n\t\t\t\t\t\tself.assertEqual(ids[-1]\t, 2\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(ids[0]\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(len(UpperCAmelCase_\t\t\t\t\t\t\t)\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Optional[Any]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tself.assertListEqual(self.tokenizer.convert_tokens_to_ids(['', 'ar_AR']\t\t\t\t\t\t\t)\t, [256203, 3]\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Dict\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttempfile.mkdtemp()\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer.fairseq_tokens_to_ids\n\t\t\t\t\t\tself.tokenizer.save_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tNllbTokenizer.from_pretrained(UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertDictEqual(new_tok.fairseq_tokens_to_ids\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t@require_torch\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer(\n\t\t\t\t\t\t self.src_text\t, text_target=self.tgt_text\t, padding=UpperCAmelCase_\t, truncation=UpperCAmelCase_\t, max_length=len(self.expected_src_tokens\t\t\t\t\t\t\t)\t, return_tensors='pt'\t, )\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tshift_tokens_right(\n\t\t\t\t\t\t batch['labels']\t, self.tokenizer.pad_token_id\t, self.tokenizer.lang_code_to_id['ron_Latn']\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\tself.assertIsInstance(UpperCAmelCase_\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\tself.assertEqual((2, 15)\t, batch.input_ids.shape\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual((2, 15)\t, batch.attention_mask.shape\t\t\t\t\t\t\t)\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tbatch.input_ids.tolist()[0]\n\t\t\t\t\t\tself.assertListEqual(self.expected_src_tokens\t, UpperCAmelCase_\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(UpperCAmelCase_\t, batch.decoder_input_ids[0, 0]\t\t\t\t\t\t\t) # EOS\n\t\t\t\t\t\t# Test that special tokens are reset\n\t\t\t\t\t\tself.assertEqual(self.tokenizer.prefix_tokens\t, [EN_CODE]\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(self.tokenizer.suffix_tokens\t, [self.tokenizer.eos_token_id]\t\t\t\t\t\t\t)\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: str\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer(self.src_text\t, padding=UpperCAmelCase_\t, truncation=UpperCAmelCase_\t, max_length=3\t, return_tensors='pt'\t\t\t\t\t\t\t)\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer(\n\t\t\t\t\t\t text_target=self.tgt_text\t, padding=UpperCAmelCase_\t, truncation=UpperCAmelCase_\t, max_length=10\t, return_tensors='pt'\t\t\t\t\t\t\t)\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\ttargets['input_ids']\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tshift_tokens_right(\n\t\t\t\t\t\t UpperCAmelCase_\t, self.tokenizer.pad_token_id\t, decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang]\t, )\n\n\t\t\t\t\t\tself.assertEqual(batch.input_ids.shape[1]\t, 3\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(batch.decoder_input_ids.shape[1]\t, 10\t\t\t\t\t\t\t)\n\t@require_torch\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: List[str]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer._build_translation_inputs(\n\t\t\t\t\t\t 'A test'\t, return_tensors='pt'\t, src_lang='eng_Latn'\t, tgt_lang='fra_Latn'\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\tself.assertEqual(\n\t\t\t\t\t\t nested_simplify(UpperCAmelCase_\t\t\t\t\t\t\t)\t, {\n\t\t\t\t\t\t # A, test, EOS, en_XX\n\t\t\t\t\t\t 'input_ids': [[256047, 70, 7356, 2]],\n\t\t\t\t\t\t 'attention_mask': [[1, 1, 1, 1]],\n\t\t\t\t\t\t # ar_AR\n\t\t\t\t\t\t 'forced_bos_token_id': 256057,\n\t\t\t\t\t\t }\t, )\n\n\n\n\n\n\t@require_torch\n\tdef \t\t\t\t\tA_ ( self\t\t\t\t\t\t\t: Optional[int]\t\t\t\t\t\t\t):\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tTrue\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer(\n\t\t\t\t\t\t 'UN Chief says there is no military solution in Syria'\t, src_lang='eng_Latn'\t, tgt_lang='fra_Latn'\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(\n\t\t\t\t\t\t inputs.input_ids\t, [16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047]\t\t\t\t\t\t\t)\n\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tFalse\n\t\t\t\t\t\tSCREAMING_SNAKE_CASE__\t\t\t\t\t\t\t\t\t\t\t\t\t=\t\t\tself.tokenizer(\n\t\t\t\t\t\t 'UN Chief says there is no military solution in Syria'\t, src_lang='eng_Latn'\t, tgt_lang='fra_Latn'\t\t\t\t\t\t\t)\n\t\t\t\t\t\tself.assertEqual(\n\t\t\t\t\t\t inputs.input_ids\t, [256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2]\t\t\t\t\t\t\t)\n\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":169,"string":"169"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":296,"cells":{"code":{"kind":"string","value":"\r\n\r\n\r\n\r\n\r\n\r\n\r\nfrom transformers import DistilBertTokenizer, DistilBertTokenizerFast\r\nfrom transformers.testing_utils import require_tokenizers, slow\r\n\r\nfrom ..bert.test_tokenization_bert import BertTokenizationTest\r\n\r\n\r\n\r\n\r\n\r\n@require_tokenizers\r\nclass __lowerCamelCase ( snake_case__):\r\n\r\n\r\n\r\n\r\n\r\n\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tUpperCamelCase__\t\t\t\t\t\t\t\t= DistilBertTokenizer\r\n\tUpperCamelCase__\t\t\t\t\t\t\t\t= DistilBertTokenizerFast\r\n\tUpperCamelCase__\t\t\t\t\t\t\t\t= True\r\n\r\n\t@slow\r\n\tdef UpperCamelCase (\t\t\t\t\t\t\tself ):\r\n\t\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t\t_UpperCAmelCase\t\t\t\t\t\t\t\t\t=\t\t\tDistilBertTokenizer.from_pretrained('distilbert-base-uncased' )\r\n\r\n\t\t\t\t\t\t\t_UpperCAmelCase\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.encode('sequence builders' , add_special_tokens=UpperCAmelCase )\r\n\t\t\t\t\t\t\t_UpperCAmelCase\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.encode('multi-sequence build' , add_special_tokens=UpperCAmelCase )\r\n\r\n\t\t\t\t\t\t\t_UpperCAmelCase\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.build_inputs_with_special_tokens(UpperCAmelCase )\r\n\t\t\t\t\t\t\t_UpperCAmelCase\t\t\t\t\t\t\t\t\t=\t\t\ttokenizer.build_inputs_with_special_tokens(UpperCAmelCase , UpperCAmelCase )\r\n\r\n\t\t\t\t\t\t\tassert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]\r\n\t\t\t\t\t\t\tassert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [\r\n\t\t\t\t\t\t\t tokenizer.sep_token_id\r\n\t\t\t\t\t\t\t]\r\n"},"code_codestyle":{"kind":"number","value":39,"string":"39"},"style_context":{"kind":"string","value":"\r\n\r\n\r\n\r\n\"\"\"simple docstring\"\"\"\r\n\r\n\r\nimport warnings\r\nfrom typing import List, Optional, Union\r\n\r\nfrom ...processing_utils import ProcessorMixin\r\nfrom ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy\r\nfrom ...utils import TensorType\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass A_\t\t\t( SCREAMING_SNAKE_CASE_\t\t\t\t):\r\n\r\n\r\n\r\n\t\t\t\t\t\t\"\"\"simple docstring\"\"\"\r\n\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t=\t\t\t\t\t\t\t[\"\"\"image_processor\"\"\", \"\"\"tokenizer\"\"\"]\r\n\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t=\t\t\t\t\t\t\t\"\"\"LayoutLMv2ImageProcessor\"\"\"\r\n\t\t\t\t\t\t__UpperCamelCase\t\t\t\t\t\t=\t\t\t\t\t\t\t(\"\"\"LayoutXLMTokenizer\"\"\", \"\"\"LayoutXLMTokenizerFast\"\"\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef __init__(\t\t\t\t\tself :Any , lowercase_ :int=None , lowercase_ :Union[str, Any]=None , **lowercase_ :Optional[Any]\t\t\t\t\t)\t\t\t\t->\t\t\tDict:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif \"feature_extractor\" in kwargs:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twarnings.warn(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ' instead.' , lowercase_ , )\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = kwargs.pop('feature_extractor'\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = image_processor if image_processor is not None else feature_extractor\r\n\t\t\t\t\t\t\t\t\t\t\t\tif image_processor is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('You need to specify an `image_processor`.'\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif tokenizer is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('You need to specify a `tokenizer`.'\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tsuper().__init__(lowercase_ , lowercase_\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef __call__(\t\t\t\t\tself :str , lowercase_ :Optional[int] , lowercase_ :Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowercase_ :Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , lowercase_ :Union[List[List[int]], List[List[List[int]]]] = None , lowercase_ :Optional[Union[List[int], List[List[int]]]] = None , lowercase_ :bool = True , lowercase_ :Union[bool, str, PaddingStrategy] = False , lowercase_ :Union[bool, str, TruncationStrategy] = None , lowercase_ :Optional[int] = None , lowercase_ :int = 0 , lowercase_ :Optional[int] = None , lowercase_ :Optional[bool] = None , lowercase_ :Optional[bool] = None , lowercase_ :bool = False , lowercase_ :bool = False , lowercase_ :bool = False , lowercase_ :bool = False , lowercase_ :bool = True , lowercase_ :Optional[Union[str, TensorType]] = None , **lowercase_ :Any , )\t\t\t\t->\t\t\tBatchEncoding:\r\n\t\t\t\t\t\t\t\t\t\t\t\t# verify input\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.image_processor.apply_ocr and (boxes is not None):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'You cannot provide bounding boxes '\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'if you initialized the image processor with apply_ocr set to True.'\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif self.image_processor.apply_ocr and (word_labels is not None):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.'\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif return_overflowing_tokens is True and return_offsets_mapping is False:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError('You cannot return overflowing tokens without returning the offsets mapping.'\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t# first, apply the image processor\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = self.image_processor(images=lowercase_ , return_tensors=lowercase_\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t# second, apply the tokenizer\r\n\t\t\t\t\t\t\t\t\t\t\t\tif text is not None and self.image_processor.apply_ocr and text_pair is None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif isinstance(lowercase_ , lowercase_\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = [text] # add batch dimension (as the image processor always adds a batch dimension)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = features['words']\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = self.tokenizer(\r\n\t\t\t\t\t\t\t\t\t\t\t\t text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_token_type_ids=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , )\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t# add pixel values\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = features.pop('pixel_values'\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif return_overflowing_tokens is True:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = self.get_overflowing_images(lowercase_ , encoded_inputs['overflow_to_sample_mapping']\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = images\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn encoded_inputs\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef \tUpperCAmelCase__ (\t\t\t\t\tself :Dict , lowercase_ :List[Any] , lowercase_ :Any\t\t\t\t\t)\t\t\t\t->\t\t\tOptional[Any]:\r\n\t\t\t\t\t\t\t\t\t\t\t\t# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image\r\n\t\t\t\t\t\t\t\t\t\t\t\tUpperCAmelCase = []\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor sample_idx in overflow_to_sample_mapping:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\timages_with_overflow.append(images[sample_idx]\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\tif len(lowercase_\t\t\t\t\t) != len(lowercase_\t\t\t\t\t):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\traise ValueError(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t f\"\"\" {len(lowercase_\t\t\t\t\t)} and {len(lowercase_\t\t\t\t\t)}\"\"\"\t\t\t\t\t)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn images_with_overflow\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef \tUpperCAmelCase__ (\t\t\t\t\tself :Any , *lowercase_ :int , **lowercase_ :Tuple\t\t\t\t\t)\t\t\t\t->\t\t\tTuple:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.tokenizer.batch_decode(*lowercase_ , **lowercase_\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\tdef \tUpperCAmelCase__ (\t\t\t\t\tself :Any , *lowercase_ :List[Any] , **lowercase_ :Optional[int]\t\t\t\t\t)\t\t\t\t->\t\t\tOptional[Any]:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.tokenizer.decode(*lowercase_ , **lowercase_\t\t\t\t\t)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@property\r\n\t\t\t\t\t\tdef \tUpperCAmelCase__ (\t\t\t\t\tself :int\t\t\t\t\t)\t\t\t\t->\t\t\tOptional[int]:\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn [\"input_ids\", \"bbox\", \"attention_mask\", \"image\"]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@property\r\n\t\t\t\t\t\tdef \tUpperCAmelCase__ (\t\t\t\t\tself :int\t\t\t\t\t)\t\t\t\t->\t\t\tDict:\r\n\t\t\t\t\t\t\t\t\t\t\t\twarnings.warn(\r\n\t\t\t\t\t\t\t\t\t\t\t\t '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , lowercase_ , )\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.image_processor_class\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\t\t\t\t@property\r\n\t\t\t\t\t\tdef \tUpperCAmelCase__ (\t\t\t\t\tself :Union[str, Any]\t\t\t\t\t)\t\t\t\t->\t\t\tOptional[int]:\r\n\t\t\t\t\t\t\t\t\t\t\t\twarnings.warn(\r\n\t\t\t\t\t\t\t\t\t\t\t\t '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , lowercase_ , )\r\n\t\t\t\t\t\t\t\t\t\t\t\treturn self.image_processor\r\n\r\n\r\n\r\n\r\n\r\n"},"style_context_codestyle":{"kind":"number","value":78,"string":"78"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":297,"cells":{"code":{"kind":"string","value":"\n\n\nfrom typing import TYPE_CHECKING\n\nfrom ...utils import (\n OptionalDependencyNotAvailable,\n _LazyModule,\n is_tf_available,\n is_torch_available,\n is_vision_available,\n)\n\n\n__a\t\t\t\t\t\t\t= {\n '''configuration_blip''': [\n '''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',\n '''BlipConfig''',\n '''BlipTextConfig''',\n '''BlipVisionConfig''',\n ],\n '''processing_blip''': ['''BlipProcessor'''],\n}\n\ntry:\n if not is_vision_available():\n raise OptionalDependencyNotAvailable()\nexcept OptionalDependencyNotAvailable:\n pass\nelse:\n __a\t\t\t\t\t\t\t= ['''BlipImageProcessor''']\n\n\ntry:\n if not is_torch_available():\n raise OptionalDependencyNotAvailable()\nexcept OptionalDependencyNotAvailable:\n pass\nelse:\n __a\t\t\t\t\t\t\t= [\n '''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',\n '''BlipModel''',\n '''BlipPreTrainedModel''',\n '''BlipForConditionalGeneration''',\n '''BlipForQuestionAnswering''',\n '''BlipVisionModel''',\n '''BlipTextModel''',\n '''BlipForImageTextRetrieval''',\n ]\n\ntry:\n if not is_tf_available():\n raise OptionalDependencyNotAvailable()\nexcept OptionalDependencyNotAvailable:\n pass\nelse:\n __a\t\t\t\t\t\t\t= [\n '''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',\n '''TFBlipModel''',\n '''TFBlipPreTrainedModel''',\n '''TFBlipForConditionalGeneration''',\n '''TFBlipForQuestionAnswering''',\n '''TFBlipVisionModel''',\n '''TFBlipTextModel''',\n '''TFBlipForImageTextRetrieval''',\n ]\n\nif TYPE_CHECKING:\n from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig\n from .processing_blip import BlipProcessor\n\n try:\n if not is_vision_available():\n raise OptionalDependencyNotAvailable()\n except OptionalDependencyNotAvailable:\n pass\n else:\n from .image_processing_blip import BlipImageProcessor\n\n try:\n if not is_torch_available():\n raise OptionalDependencyNotAvailable()\n except OptionalDependencyNotAvailable:\n pass\n else:\n from .modeling_blip import (\n BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,\n BlipForConditionalGeneration,\n BlipForImageTextRetrieval,\n BlipForQuestionAnswering,\n BlipModel,\n BlipPreTrainedModel,\n BlipTextModel,\n BlipVisionModel,\n )\n\n try:\n if not is_tf_available():\n raise OptionalDependencyNotAvailable()\n except OptionalDependencyNotAvailable:\n pass\n else:\n from .modeling_tf_blip import (\n TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,\n TFBlipForConditionalGeneration,\n TFBlipForImageTextRetrieval,\n TFBlipForQuestionAnswering,\n TFBlipModel,\n TFBlipPreTrainedModel,\n TFBlipTextModel,\n TFBlipVisionModel,\n )\n\nelse:\n import sys\n\n __a\t\t\t\t\t\t\t= _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)\n\n"},"code_codestyle":{"kind":"number","value":364,"string":"364"},"style_context":{"kind":"string","value":"\n\n\nfrom maths.prime_factors import prime_factors\n\n\n\n\ndef __lowercase\t\t( _UpperCamelCase ) ->int:\n\n\n\n\n\n\n\n \"\"\"simple docstring\"\"\"\n\n if not isinstance(_UpperCamelCase, _UpperCamelCase ):\n lowercase :\t\t\t\tList[str] \t\t\t\t=\t\t\t\t\t\tf\"\"\"Input value of [number={number}] must be an integer\"\"\"\n raise TypeError(_UpperCamelCase )\n if number < 1:\n raise ValueError('''Input must be a positive integer''' )\n return -1 if len(prime_factors(_UpperCamelCase ) ) % 2 else 1\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n\n"},"style_context_codestyle":{"kind":"number","value":173,"string":"173"},"label":{"kind":"number","value":0,"string":"0"}}},{"rowIdx":298,"cells":{"code":{"kind":"string","value":"\r\rfrom __future__ import annotations\r\rimport time\rfrom math import sqrt\r\r# 1 for manhattan, 0 for euclidean\r__A : List[str] =\t0\r\r__A : List[str] =\t[\r [0, 0, 0, 0, 0, 0, 0],\r [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles\r [0, 0, 0, 0, 0, 0, 0],\r [0, 0, 1, 0, 0, 0, 0],\r [1, 0, 1, 0, 0, 0, 0],\r [0, 0, 0, 0, 0, 0, 0],\r [0, 0, 0, 0, 1, 0, 0],\r]\r\r__A : Union[str, Any] =\t[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right\r\r__A : Tuple =\ttuple[int, int]\r\r\r\r\r\r\rclass __A :\r\r\r\r\r\r\r def __init__(\t\tself\t:\t\t\tList[Any]\t\t\t, UpperCAmelCase_\t:\t\t\tint\t\t\t, UpperCAmelCase_\t:\t\t\tint\t\t\t, UpperCAmelCase_\t:\t\t\tint\t\t\t, UpperCAmelCase_\t:\t\t\tint\t\t\t, UpperCAmelCase_\t:\t\t\tint\t\t\t, UpperCAmelCase_\t:\t\t\tNode | None\t\t\t, ):\r lowerCAmelCase :\tUnion[str, Any]\t\t\t\t=\t\t\t\t\tpos_x\r lowerCAmelCase :\tDict\t\t\t\t=\t\t\t\t\tpos_y\r lowerCAmelCase :\tDict\t\t\t\t=\t\t\t\t\t(pos_y, pos_x)\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tgoal_x\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tgoal_y\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tg_cost\r lowerCAmelCase :\tstr\t\t\t\t=\t\t\t\t\tparent\r lowerCAmelCase :\tstr\t\t\t\t=\t\t\t\t\tself.calculate_heuristic()\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tself.g_cost + self.h_cost\r\r\r\r\r\r\r def \t\tlowercase__ (\t\tself\t:\t\t\tList[Any]\t\t\t):\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tself.pos_x - self.goal_x\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tself.pos_y - self.goal_y\r if HEURISTIC == 1:\r return abs(UpperCAmelCase_\t\t\t) + abs(UpperCAmelCase_\t\t\t)\r else:\r return sqrt(dy**2 + dx**2\t\t\t)\r\r\r\r\r\r\r def __lt__(\t\tself\t:\t\t\tTuple\t\t\t, UpperCAmelCase_\t:\t\t\tNode\t\t\t):\r return self.f_cost < other.f_cost\r\r\r\r\r\r\rclass __A :\r\r\r\r\r\r\r def __init__(\t\tself\t:\t\t\tTuple\t\t\t, UpperCAmelCase_\t:\t\t\tTPosition\t\t\t, UpperCAmelCase_\t:\t\t\tTPosition\t\t\t):\r lowerCAmelCase :\tOptional[Any]\t\t\t\t=\t\t\t\t\tNode(start[1]\t\t\t, start[0]\t\t\t, goal[1]\t\t\t, goal[0]\t\t\t, 0\t\t\t, UpperCAmelCase_\t\t\t)\r lowerCAmelCase :\tDict\t\t\t\t=\t\t\t\t\tNode(goal[1]\t\t\t, goal[0]\t\t\t, goal[1]\t\t\t, goal[0]\t\t\t, 99999\t\t\t, UpperCAmelCase_\t\t\t)\r\r lowerCAmelCase :\tAny\t\t\t\t=\t\t\t\t\t[self.start]\r lowerCAmelCase :\tlist[Node]\t\t\t\t=\t\t\t\t\t[]\r\r lowerCAmelCase :\tTuple\t\t\t\t=\t\t\t\t\tFalse\r\r\r\r\r\r\r def \t\tlowercase__ (\t\tself\t:\t\t\tAny\t\t\t):\r while self.open_nodes:\r # Open Nodes are sorted using __lt__\r self.open_nodes.sort()\r lowerCAmelCase :\tUnion[str, Any]\t\t\t\t=\t\t\t\t\tself.open_nodes.pop(0\t\t\t)\r\r if current_node.pos == self.target.pos:\r return self.retrace_path(UpperCAmelCase_\t\t\t)\r\r self.closed_nodes.append(UpperCAmelCase_\t\t\t)\r lowerCAmelCase :\tDict\t\t\t\t=\t\t\t\t\tself.get_successors(UpperCAmelCase_\t\t\t)\r\r for child_node in successors:\r if child_node in self.closed_nodes:\r continue\r\r if child_node not in self.open_nodes:\r self.open_nodes.append(UpperCAmelCase_\t\t\t)\r else:\r # retrieve the best current path\r lowerCAmelCase :\tstr\t\t\t\t=\t\t\t\t\tself.open_nodes.pop(self.open_nodes.index(UpperCAmelCase_\t\t\t)\t\t\t)\r\r if child_node.g_cost < better_node.g_cost:\r self.open_nodes.append(UpperCAmelCase_\t\t\t)\r else:\r self.open_nodes.append(UpperCAmelCase_\t\t\t)\r\r return [self.start.pos]\r\r\r\r\r\r\r def \t\tlowercase__ (\t\tself\t:\t\t\tOptional[int]\t\t\t, UpperCAmelCase_\t:\t\t\tNode\t\t\t):\r lowerCAmelCase :\tOptional[Any]\t\t\t\t=\t\t\t\t\t[]\r for action in delta:\r lowerCAmelCase :\tUnion[str, Any]\t\t\t\t=\t\t\t\t\tparent.pos_x + action[1]\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tparent.pos_y + action[0]\r if not (0 <= pos_x <= len(grid[0]\t\t\t) - 1 and 0 <= pos_y <= len(UpperCAmelCase_\t\t\t) - 1):\r continue\r\r if grid[pos_y][pos_x] != 0:\r continue\r\r successors.append(\r Node(\r UpperCAmelCase_\t\t\t, UpperCAmelCase_\t\t\t, self.target.pos_y\t\t\t, self.target.pos_x\t\t\t, parent.g_cost + 1\t\t\t, UpperCAmelCase_\t\t\t, )\t\t\t)\r return successors\r\r\r\r\r\r\r def \t\tlowercase__ (\t\tself\t:\t\t\tDict\t\t\t, UpperCAmelCase_\t:\t\t\tNode | None\t\t\t):\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tnode\r lowerCAmelCase :\tstr\t\t\t\t=\t\t\t\t\t[]\r while current_node is not None:\r path.append((current_node.pos_y, current_node.pos_x)\t\t\t)\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tcurrent_node.parent\r path.reverse()\r return path\r\r\r\r\r\r\rclass __A :\r\r\r\r\r\r\r def __init__(\t\tself\t:\t\t\tint\t\t\t, UpperCAmelCase_\t:\t\t\tTPosition\t\t\t, UpperCAmelCase_\t:\t\t\tTPosition\t\t\t):\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tAStar(UpperCAmelCase_\t\t\t, UpperCAmelCase_\t\t\t)\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tAStar(UpperCAmelCase_\t\t\t, UpperCAmelCase_\t\t\t)\r lowerCAmelCase :\tTuple\t\t\t\t=\t\t\t\t\tFalse\r\r\r\r\r\r\r def \t\tlowercase__ (\t\tself\t:\t\t\tUnion[str, Any]\t\t\t):\r while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes:\r self.fwd_astar.open_nodes.sort()\r self.bwd_astar.open_nodes.sort()\r lowerCAmelCase :\tOptional[int]\t\t\t\t=\t\t\t\t\tself.fwd_astar.open_nodes.pop(0\t\t\t)\r lowerCAmelCase :\tAny\t\t\t\t=\t\t\t\t\tself.bwd_astar.open_nodes.pop(0\t\t\t)\r\r if current_bwd_node.pos == current_fwd_node.pos:\r return self.retrace_bidirectional_path(\r UpperCAmelCase_\t\t\t, UpperCAmelCase_\t\t\t)\r\r self.fwd_astar.closed_nodes.append(UpperCAmelCase_\t\t\t)\r self.bwd_astar.closed_nodes.append(UpperCAmelCase_\t\t\t)\r\r lowerCAmelCase :\tstr\t\t\t\t=\t\t\t\t\tcurrent_bwd_node\r lowerCAmelCase :\tList[Any]\t\t\t\t=\t\t\t\t\tcurrent_fwd_node\r\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\t{\r self.fwd_astar: self.fwd_astar.get_successors(UpperCAmelCase_\t\t\t),\r self.bwd_astar: self.bwd_astar.get_successors(UpperCAmelCase_\t\t\t),\r }\r\r for astar in [self.fwd_astar, self.bwd_astar]:\r for child_node in successors[astar]:\r if child_node in astar.closed_nodes:\r continue\r\r if child_node not in astar.open_nodes:\r astar.open_nodes.append(UpperCAmelCase_\t\t\t)\r else:\r # retrieve the best current path\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tastar.open_nodes.pop(\r astar.open_nodes.index(UpperCAmelCase_\t\t\t)\t\t\t)\r\r if child_node.g_cost < better_node.g_cost:\r astar.open_nodes.append(UpperCAmelCase_\t\t\t)\r else:\r astar.open_nodes.append(UpperCAmelCase_\t\t\t)\r\r return [self.fwd_astar.start.pos]\r\r\r\r\r\r\r def \t\tlowercase__ (\t\tself\t:\t\t\tUnion[str, Any]\t\t\t, UpperCAmelCase_\t:\t\t\tNode\t\t\t, UpperCAmelCase_\t:\t\t\tNode\t\t\t):\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tself.fwd_astar.retrace_path(UpperCAmelCase_\t\t\t)\r lowerCAmelCase :\tOptional[Any]\t\t\t\t=\t\t\t\t\tself.bwd_astar.retrace_path(UpperCAmelCase_\t\t\t)\r bwd_path.pop()\r bwd_path.reverse()\r lowerCAmelCase :\tAny\t\t\t\t=\t\t\t\t\tfwd_path + bwd_path\r return path\r\r\rif __name__ == \"__main__\":\r # all coordinates are given in format [y,x]\r __A : Optional[int] =\t(0, 0)\r __A : int =\t(len(grid) - 1, len(grid[0]) - 1)\r for elem in grid:\r print(elem)\r\r __A : Optional[Any] =\ttime.time()\r __A : List[Any] =\tAStar(init, goal)\r __A : List[str] =\ta_star.search()\r __A : Union[str, Any] =\ttime.time() - start_time\r print(F'AStar execution time = {end_time:f} seconds')\r\r __A : Union[str, Any] =\ttime.time()\r __A : Dict =\tBidirectionalAStar(init, goal)\r __A : List[Any] =\ttime.time() - bd_start_time\r print(F'BidirectionalAStar execution time = {bd_end_time:f} seconds')\r\r\r\r\r\r"},"code_codestyle":{"kind":"number","value":138,"string":"138"},"style_context":{"kind":"string","value":"\r\rfrom ...configuration_utils import PretrainedConfig\rfrom ...utils import logging\r\r\r__A : Dict =\tlogging.get_logger(__name__)\r\r__A : List[Any] =\t{'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''}\r\r\r\r\r\r\rclass __A (\t\t\t\t\t\t\tlowerCAmelCase ):\r lowerCAmelCase_\t\t\t\t\t\t\t:\t\t\t\t\t\tstr\t\t\t\t\t\t =\t\t\t\t\t\t\t\"ctrl\"\r lowerCAmelCase_\t\t\t\t\t\t\t:\t\t\t\t\t\tOptional[Any]\t\t\t\t\t\t =\t\t\t\t\t\t\t[\"past_key_values\"]\r lowerCAmelCase_\t\t\t\t\t\t\t:\t\t\t\t\t\tDict\t\t\t\t\t\t =\t\t\t\t\t\t\t{\r \"max_position_embeddings\": \"n_positions\",\r \"hidden_size\": \"n_embd\",\r \"num_attention_heads\": \"n_head\",\r \"num_hidden_layers\": \"n_layer\",\r }\r\r\r\r\r\r\r def __init__(\t\tself\t:\t\t\tAny\t\t\t, UpperCAmelCase_\t:\t\t\tint=246534\t\t\t, UpperCAmelCase_\t:\t\t\tOptional[Any]=256\t\t\t, UpperCAmelCase_\t:\t\t\tAny=1280\t\t\t, UpperCAmelCase_\t:\t\t\tint=8192\t\t\t, UpperCAmelCase_\t:\t\t\tint=48\t\t\t, UpperCAmelCase_\t:\t\t\tOptional[Any]=16\t\t\t, UpperCAmelCase_\t:\t\t\tDict=0.1\t\t\t, UpperCAmelCase_\t:\t\t\tAny=0.1\t\t\t, UpperCAmelCase_\t:\t\t\tList[str]=1E-6\t\t\t, UpperCAmelCase_\t:\t\t\tstr=0.02\t\t\t, UpperCAmelCase_\t:\t\t\tOptional[Any]=True\t\t\t, **UpperCAmelCase_\t:\t\t\tint\t\t\t, ):\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tvocab_size\r lowerCAmelCase :\tint\t\t\t\t=\t\t\t\t\tn_positions\r lowerCAmelCase :\tOptional[Any]\t\t\t\t=\t\t\t\t\tn_embd\r lowerCAmelCase :\tOptional[Any]\t\t\t\t=\t\t\t\t\tn_layer\r lowerCAmelCase :\tList[str]\t\t\t\t=\t\t\t\t\tn_head\r lowerCAmelCase :\tUnion[str, Any]\t\t\t\t=\t\t\t\t\tdff\r lowerCAmelCase :\tDict\t\t\t\t=\t\t\t\t\tresid_pdrop\r lowerCAmelCase :\tList[Any]\t\t\t\t=\t\t\t\t\tembd_pdrop\r lowerCAmelCase :\tList[Any]\t\t\t\t=\t\t\t\t\tlayer_norm_epsilon\r lowerCAmelCase :\tDict\t\t\t\t=\t\t\t\t\tinitializer_range\r\r lowerCAmelCase :\tUnion[str, Any]\t\t\t\t=\t\t\t\t\tuse_cache\r\r super().__init__(**UpperCAmelCase_\t\t\t)\r\r\r\r\r\r"},"style_context_codestyle":{"kind":"number","value":138,"string":"138"},"label":{"kind":"number","value":1,"string":"1"}}},{"rowIdx":299,"cells":{"code":{"kind":"string","value":"\n\n\"\"\"simple docstring\"\"\"\n\n\n\n\n\nfrom __future__ import annotations\n\nimport requests\n\ndef __SCREAMING_SNAKE_CASE (\t\t\t\tA_\t\t\t):\n\tlowerCAmelCase__ :\t\t\t\t\t\tDict = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty'\n\treturn requests.get(A_\t\t\t).json()\n\ndef __SCREAMING_SNAKE_CASE (\t\t\t\tA_ = 10\t\t\t):\n\tlowerCAmelCase__ :\t\t\t\t\t\tint = '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'''\n\tlowerCAmelCase__ :\t\t\t\t\t\tOptional[int] = requests.get(A_\t\t\t).json()[:max_stories]\n\treturn [get_hackernews_story(A_\t\t\t) for story_id in story_ids]\n\ndef __SCREAMING_SNAKE_CASE (\t\t\t\tA_ = 10\t\t\t):\n\tlowerCAmelCase__ :\t\t\t\t\t\tTuple = hackernews_top_stories(A_\t\t\t)\n\treturn \"\\n\".join('''* [{title}]({url})'''.format(**A_\t\t\t) for story in stories\t\t\t)\n\n\nif __name__ == \"__main__\":\n\t\t\t\t\t\t\tprint(hackernews_top_stories_as_markdown())\n\n\n\n\n"},"code_codestyle":{"kind":"number","value":74,"string":"74"},"style_context":{"kind":"string","value":"\n\n\"\"\"simple docstring\"\"\"\n\n\n\n\n\nfrom ...utils import (\n OptionalDependencyNotAvailable,\n is_torch_available,\n is_transformers_available,\n is_transformers_version,\n)\n\n\ntry:\n\t\t\t\t\t\t\tif not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise OptionalDependencyNotAvailable()\nexcept OptionalDependencyNotAvailable:\n\t\t\t\t\t\t\tfrom ...utils.dummy_torch_and_transformers_objects import (\n\t\t\t\t\t\t\t VersatileDiffusionDualGuidedPipeline,\n\t\t\t\t\t\t\t VersatileDiffusionImageVariationPipeline,\n\t\t\t\t\t\t\t VersatileDiffusionPipeline,\n\t\t\t\t\t\t\t VersatileDiffusionTextToImagePipeline,\n\t\t\t\t\t\t\t)\nelse:\n\t\t\t\t\t\t\tfrom .modeling_text_unet import UNetFlatConditionModel\n\t\t\t\t\t\t\tfrom .pipeline_versatile_diffusion import VersatileDiffusionPipeline\n\t\t\t\t\t\t\tfrom .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline\n\t\t\t\t\t\t\tfrom .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline\n\t\t\t\t\t\t\tfrom .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline\n\n\n\n\n"},"style_context_codestyle":{"kind":"number","value":74,"string":"74"},"label":{"kind":"number","value":1,"string":"1"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":2,"numItemsPerPage":100,"numTotalItems":153992,"offset":200,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NTQ1MDk2Nywic3ViIjoiL2RhdGFzZXRzL2luZmluaXR5b2ZzcGFjZS9weXRob25fY29kZXN0eWxlcy1taXhlZDEtNTAwIiwiZXhwIjoxNzU1NDU0NTY3LCJpc3MiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvIn0.p0TF_3TI0unMLybyO_eKSIxfJhMHl3b9PYAH3wrob31PMnQzJjXiuh09HvaSdRhWUqbUFLr3m4_ryYrLyqdSCA","displayUrls":true},"discussionsStats":{"closed":0,"open":1,"total":1},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
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_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
is_valid_image,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
lowercase = logging.get_logger(__name__)
def __UpperCAmelCase ( a_):
if isinstance(a_ , (list, tuple)) and isinstance(videos[0] , (list, tuple)) and is_valid_image(videos[0][0]):
return videos
elif isinstance(a_ , (list, tuple)) and is_valid_image(videos[0]):
return [videos]
elif is_valid_image(a_):
return [[videos]]
raise ValueError(f'''Could not make batched video from {videos}''')
class UpperCamelCase_ ( UpperCamelCase__ ):
'''simple docstring'''
lowerCAmelCase = ["""pixel_values"""]
def __init__( self , a = True , a = None , a = PILImageResampling.BILINEAR , a = True , a = None , a = True , a = 1 / 2_55 , a = True , a = None , a = None , **a , ) -> None:
super().__init__(**lowerCAmelCase__ )
snake_case_ = size if size is not None else {"shortest_edge": 2_24}
snake_case_ = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ )
snake_case_ = crop_size if crop_size is not None else {"height": 2_24, "width": 2_24}
snake_case_ = get_size_dict(lowerCAmelCase__ , param_name='crop_size' )
snake_case_ = do_resize
snake_case_ = size
snake_case_ = do_center_crop
snake_case_ = crop_size
snake_case_ = resample
snake_case_ = do_rescale
snake_case_ = rescale_factor
snake_case_ = do_normalize
snake_case_ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
snake_case_ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _UpperCamelCase ( self , a , a , a = PILImageResampling.BILINEAR , a = None , **a , ) -> np.ndarray:
snake_case_ = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ )
if "shortest_edge" in size:
snake_case_ = get_resize_output_image_size(lowerCAmelCase__ , size['shortest_edge'] , default_to_square=lowerCAmelCase__ )
elif "height" in size and "width" in size:
snake_case_ = (size["height"], size["width"])
else:
raise ValueError(F'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}''' )
return resize(lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , a , a , a = None , **a , ) -> np.ndarray:
snake_case_ = get_size_dict(lowerCAmelCase__ )
if "height" not in size or "width" not in size:
raise ValueError(F'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}''' )
return center_crop(lowerCAmelCase__ , size=(size['height'], size['width']) , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , a , a , a = None , **a , ) -> int:
return rescale(lowerCAmelCase__ , scale=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , a , a , a , a = None , **a , ) -> np.ndarray:
return normalize(lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ , data_format=lowerCAmelCase__ , **lowerCAmelCase__ )
def _UpperCamelCase ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , ) -> np.ndarray:
if do_resize and size is None or resample is None:
raise ValueError('Size and resample must be specified if do_resize is True.' )
if do_center_crop and crop_size is None:
raise ValueError('Crop size must be specified if do_center_crop is True.' )
if do_rescale and rescale_factor is None:
raise ValueError('Rescale factor must be specified if do_rescale is True.' )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('Image mean and std must be specified if do_normalize is True.' )
# All transformations expect numpy arrays.
snake_case_ = to_numpy_array(lowerCAmelCase__ )
if do_resize:
snake_case_ = self.resize(image=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ )
if do_center_crop:
snake_case_ = self.center_crop(lowerCAmelCase__ , size=lowerCAmelCase__ )
if do_rescale:
snake_case_ = self.rescale(image=lowerCAmelCase__ , scale=lowerCAmelCase__ )
if do_normalize:
snake_case_ = self.normalize(image=lowerCAmelCase__ , mean=lowerCAmelCase__ , std=lowerCAmelCase__ )
snake_case_ = to_channel_dimension_format(lowerCAmelCase__ , lowerCAmelCase__ )
return image
def _UpperCamelCase ( self , a , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = None , a = ChannelDimension.FIRST , **a , ) -> PIL.Image.Image:
snake_case_ = do_resize if do_resize is not None else self.do_resize
snake_case_ = resample if resample is not None else self.resample
snake_case_ = do_center_crop if do_center_crop is not None else self.do_center_crop
snake_case_ = do_rescale if do_rescale is not None else self.do_rescale
snake_case_ = rescale_factor if rescale_factor is not None else self.rescale_factor
snake_case_ = do_normalize if do_normalize is not None else self.do_normalize
snake_case_ = image_mean if image_mean is not None else self.image_mean
snake_case_ = image_std if image_std is not None else self.image_std
snake_case_ = size if size is not None else self.size
snake_case_ = get_size_dict(lowerCAmelCase__ , default_to_square=lowerCAmelCase__ )
snake_case_ = crop_size if crop_size is not None else self.crop_size
snake_case_ = get_size_dict(lowerCAmelCase__ , param_name='crop_size' )
if not valid_images(lowerCAmelCase__ ):
raise ValueError(
'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
'torch.Tensor, tf.Tensor or jax.ndarray.' )
snake_case_ = make_batched(lowerCAmelCase__ )
snake_case_ = [
[
self._preprocess_image(
image=lowerCAmelCase__ , do_resize=lowerCAmelCase__ , size=lowerCAmelCase__ , resample=lowerCAmelCase__ , do_center_crop=lowerCAmelCase__ , crop_size=lowerCAmelCase__ , do_rescale=lowerCAmelCase__ , rescale_factor=lowerCAmelCase__ , do_normalize=lowerCAmelCase__ , image_mean=lowerCAmelCase__ , image_std=lowerCAmelCase__ , data_format=lowerCAmelCase__ , )
for img in video
]
for video in videos
]
snake_case_ = {"pixel_values": videos}
return BatchFeature(data=lowerCAmelCase__ , tensor_type=lowerCAmelCase__ )
from collections.abc import Sequence
def a__ ( A__, A__ = False ):
if not arr:
return 0
SCREAMING_SNAKE_CASE_ : str = 0 if allow_empty_subarrays else float('-inf' )
SCREAMING_SNAKE_CASE_ : Tuple = 0.0
for num in arr:
SCREAMING_SNAKE_CASE_ : int = max(0 if allow_empty_subarrays else num, curr_sum + num )
SCREAMING_SNAKE_CASE_ : List[Any] = max(A__, A__ )
return max_sum
if __name__ == "__main__":
from doctest import testmod
testmod()
lowerCAmelCase__ : Union[str, Any] =[-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(F"""{max_subarray_sum(nums) = }""")
162
1
"""simple docstring"""
import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List
from ..utils import logging
lowerCAmelCase_ = logging.get_logger(__name__)
def __UpperCAmelCase ( __lowerCamelCase=None , __lowerCamelCase=None ) -> Union[str, Any]:
return field(default_factory=lambda: default , metadata=__lowerCamelCase )
@dataclass
class __A :
'''simple docstring'''
lowerCAmelCase : List[str] = list_field(
default=[] ,metadata={
"help": (
"Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version"
" of all available models"
)
} ,)
lowerCAmelCase : List[int] = list_field(
default=[8] ,metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} )
lowerCAmelCase : List[int] = list_field(
default=[8, 3_2, 1_2_8, 5_1_2] ,metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} ,)
lowerCAmelCase : bool = field(
default=A_ ,metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} ,)
lowerCAmelCase : bool = field(
default=A_ ,metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} ,)
lowerCAmelCase : bool = field(
default=A_ ,metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} )
lowerCAmelCase : bool = field(default=A_ ,metadata={"help": "Use FP16 to accelerate inference."} )
lowerCAmelCase : bool = field(default=A_ ,metadata={"help": "Benchmark training of model"} )
lowerCAmelCase : bool = field(default=A_ ,metadata={"help": "Verbose memory tracing"} )
lowerCAmelCase : bool = field(
default=A_ ,metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} ,)
lowerCAmelCase : bool = field(
default=A_ ,metadata={
"help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory"
} ,)
lowerCAmelCase : bool = field(default=A_ ,metadata={"help": "Trace memory line by line"} )
lowerCAmelCase : bool = field(default=A_ ,metadata={"help": "Save result to a CSV file"} )
lowerCAmelCase : bool = field(default=A_ ,metadata={"help": "Save all print statements in a log file"} )
lowerCAmelCase : bool = field(default=A_ ,metadata={"help": "Whether to print environment information"} )
lowerCAmelCase : bool = field(
default=A_ ,metadata={
"help": (
"Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use"
" multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled"
" for debugging / testing and on TPU."
)
} ,)
lowerCAmelCase : str = field(
default=F"inference_time_{round(time() )}.csv" ,metadata={"help": "CSV filename used if saving time results to csv."} ,)
lowerCAmelCase : str = field(
default=F"inference_memory_{round(time() )}.csv" ,metadata={"help": "CSV filename used if saving memory results to csv."} ,)
lowerCAmelCase : str = field(
default=F"train_time_{round(time() )}.csv" ,metadata={"help": "CSV filename used if saving time results to csv for training."} ,)
lowerCAmelCase : str = field(
default=F"train_memory_{round(time() )}.csv" ,metadata={"help": "CSV filename used if saving memory results to csv for training."} ,)
lowerCAmelCase : str = field(
default=F"env_info_{round(time() )}.csv" ,metadata={"help": "CSV filename used if saving environment information."} ,)
lowerCAmelCase : str = field(
default=F"log_{round(time() )}.csv" ,metadata={"help": "Log filename used if print statements are saved in log."} ,)
lowerCAmelCase : int = field(default=3 ,metadata={"help": "Times an experiment will be run."} )
lowerCAmelCase : bool = field(
default=A_ ,metadata={
"help": (
"Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain"
" model weights."
)
} ,)
def UpperCAmelCase ( self : Dict ) -> int:
"""simple docstring"""
warnings.warn(
f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils"""
''' are deprecated in general and it is advised to use external Benchmarking libraries '''
''' to benchmark Transformer models.''' ,_snake_case ,)
def UpperCAmelCase ( self : Dict ) -> str:
"""simple docstring"""
return json.dumps(dataclasses.asdict(self ) ,indent=2 )
@property
def UpperCAmelCase ( self : int ) -> List[str]:
"""simple docstring"""
if len(self.models ) <= 0:
raise ValueError(
'''Please make sure you provide at least one model name / model identifier, *e.g.* `--models'''
''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' )
return self.models
@property
def UpperCAmelCase ( self : Optional[int] ) -> str:
"""simple docstring"""
if not self.multi_process:
return False
elif self.is_tpu:
logger.info('''Multiprocessing is currently not possible on TPU.''' )
return False
else:
return True
'''simple docstring'''
def __UpperCAmelCase ( a_: int, a_: int ):
if a < 0 or b < 0:
raise ValueError("the value of both inputs must be positive" )
_UpperCAmelCase : List[str] = str(bin(a_ ) )[2:] # remove the leading "0b"
_UpperCAmelCase : Any = str(bin(a_ ) )[2:] # remove the leading "0b"
_UpperCAmelCase : Dict = max(len(a_ ), len(a_ ) )
return "0b" + "".join(
str(int(char_a == "1" and char_b == "1" ) )
for char_a, char_b in zip(a_binary.zfill(a_ ), b_binary.zfill(a_ ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
17
0
import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union
# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...image_processing_utils import ImageProcessingMixin
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
CONFIG_MAPPING_NAMES,
AutoConfig,
model_type_to_module_name,
replace_list_option_in_docstrings,
)
UpperCamelCase = logging.get_logger(__name__)
UpperCamelCase = OrderedDict(
[
('''align''', '''EfficientNetImageProcessor'''),
('''beit''', '''BeitImageProcessor'''),
('''bit''', '''BitImageProcessor'''),
('''blip''', '''BlipImageProcessor'''),
('''blip-2''', '''BlipImageProcessor'''),
('''bridgetower''', '''BridgeTowerImageProcessor'''),
('''chinese_clip''', '''ChineseCLIPImageProcessor'''),
('''clip''', '''CLIPImageProcessor'''),
('''clipseg''', '''ViTImageProcessor'''),
('''conditional_detr''', '''ConditionalDetrImageProcessor'''),
('''convnext''', '''ConvNextImageProcessor'''),
('''convnextv2''', '''ConvNextImageProcessor'''),
('''cvt''', '''ConvNextImageProcessor'''),
('''data2vec-vision''', '''BeitImageProcessor'''),
('''deformable_detr''', '''DeformableDetrImageProcessor'''),
('''deit''', '''DeiTImageProcessor'''),
('''deta''', '''DetaImageProcessor'''),
('''detr''', '''DetrImageProcessor'''),
('''dinat''', '''ViTImageProcessor'''),
('''donut-swin''', '''DonutImageProcessor'''),
('''dpt''', '''DPTImageProcessor'''),
('''efficientformer''', '''EfficientFormerImageProcessor'''),
('''efficientnet''', '''EfficientNetImageProcessor'''),
('''flava''', '''FlavaImageProcessor'''),
('''focalnet''', '''BitImageProcessor'''),
('''git''', '''CLIPImageProcessor'''),
('''glpn''', '''GLPNImageProcessor'''),
('''groupvit''', '''CLIPImageProcessor'''),
('''imagegpt''', '''ImageGPTImageProcessor'''),
('''instructblip''', '''BlipImageProcessor'''),
('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''),
('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''),
('''levit''', '''LevitImageProcessor'''),
('''mask2former''', '''Mask2FormerImageProcessor'''),
('''maskformer''', '''MaskFormerImageProcessor'''),
('''mgp-str''', '''ViTImageProcessor'''),
('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''),
('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''),
('''mobilevit''', '''MobileViTImageProcessor'''),
('''mobilevit''', '''MobileViTImageProcessor'''),
('''mobilevitv2''', '''MobileViTImageProcessor'''),
('''nat''', '''ViTImageProcessor'''),
('''oneformer''', '''OneFormerImageProcessor'''),
('''owlvit''', '''OwlViTImageProcessor'''),
('''perceiver''', '''PerceiverImageProcessor'''),
('''pix2struct''', '''Pix2StructImageProcessor'''),
('''poolformer''', '''PoolFormerImageProcessor'''),
('''regnet''', '''ConvNextImageProcessor'''),
('''resnet''', '''ConvNextImageProcessor'''),
('''sam''', '''SamImageProcessor'''),
('''segformer''', '''SegformerImageProcessor'''),
('''swiftformer''', '''ViTImageProcessor'''),
('''swin''', '''ViTImageProcessor'''),
('''swin2sr''', '''Swin2SRImageProcessor'''),
('''swinv2''', '''ViTImageProcessor'''),
('''table-transformer''', '''DetrImageProcessor'''),
('''timesformer''', '''VideoMAEImageProcessor'''),
('''tvlt''', '''TvltImageProcessor'''),
('''upernet''', '''SegformerImageProcessor'''),
('''van''', '''ConvNextImageProcessor'''),
('''videomae''', '''VideoMAEImageProcessor'''),
('''vilt''', '''ViltImageProcessor'''),
('''vit''', '''ViTImageProcessor'''),
('''vit_hybrid''', '''ViTHybridImageProcessor'''),
('''vit_mae''', '''ViTImageProcessor'''),
('''vit_msn''', '''ViTImageProcessor'''),
('''xclip''', '''CLIPImageProcessor'''),
('''yolos''', '''YolosImageProcessor'''),
]
)
UpperCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)
def __lowerCamelCase ( snake_case__ ) -> int:
"""simple docstring"""
for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
if class_name in extractors:
_SCREAMING_SNAKE_CASE = model_type_to_module_name(_a )
_SCREAMING_SNAKE_CASE = importlib.import_module(F'.{module_name}' ,"""transformers.models""" )
try:
return getattr(_a ,_a )
except AttributeError:
continue
for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
if getattr(_a ,"""__name__""" ,_a ) == class_name:
return extractor
# We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
# init and we return the proper dummy to get an appropriate error message.
_SCREAMING_SNAKE_CASE = importlib.import_module("""transformers""" )
if hasattr(_a ,_a ):
return getattr(_a ,_a )
return None
def __lowerCamelCase ( snake_case__ ,snake_case__ = None ,snake_case__ = False ,snake_case__ = False ,snake_case__ = None ,snake_case__ = None ,snake_case__ = None ,snake_case__ = False ,**snake_case__ ,) -> Union[str, Any]:
"""simple docstring"""
_SCREAMING_SNAKE_CASE = get_file_from_repo(
_a ,_a ,cache_dir=_a ,force_download=_a ,resume_download=_a ,proxies=_a ,use_auth_token=_a ,revision=_a ,local_files_only=_a ,)
if resolved_config_file is None:
logger.info(
"""Could not locate the image processor configuration file, will try to use the model config instead.""" )
return {}
with open(_a ,encoding="""utf-8""" ) as reader:
return json.load(_a )
class __UpperCAmelCase :
def __init__( self: Optional[int] ):
'''simple docstring'''
raise EnvironmentError(
"""AutoImageProcessor is designed to be instantiated """
"""using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.""" )
@classmethod
@replace_list_option_in_docstrings(UpperCAmelCase_ )
def UpperCamelCase ( cls: Optional[int] , UpperCAmelCase_: List[str] , **UpperCAmelCase_: List[Any] ):
'''simple docstring'''
_SCREAMING_SNAKE_CASE = kwargs.pop("""config""" , UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE = kwargs.pop("""trust_remote_code""" , UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE = True
_SCREAMING_SNAKE_CASE = ImageProcessingMixin.get_image_processor_dict(UpperCAmelCase_ , **UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE = config_dict.get("""image_processor_type""" , UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE = None
if "AutoImageProcessor" in config_dict.get("""auto_map""" , {} ):
_SCREAMING_SNAKE_CASE = config_dict["auto_map"]["AutoImageProcessor"]
# If we still don't have the image processor class, check if we're loading from a previous feature extractor config
# and if so, infer the image processor class from there.
if image_processor_class is None and image_processor_auto_map is None:
_SCREAMING_SNAKE_CASE = config_dict.pop("""feature_extractor_type""" , UpperCAmelCase_ )
if feature_extractor_class is not None:
logger.warning(
"""Could not find image processor class in the image processor config or the model config. Loading"""
""" based on pattern matching with the model's feature extractor configuration.""" )
_SCREAMING_SNAKE_CASE = feature_extractor_class.replace("""FeatureExtractor""" , """ImageProcessor""" )
if "AutoFeatureExtractor" in config_dict.get("""auto_map""" , {} ):
_SCREAMING_SNAKE_CASE = config_dict["auto_map"]["AutoFeatureExtractor"]
_SCREAMING_SNAKE_CASE = feature_extractor_auto_map.replace("""FeatureExtractor""" , """ImageProcessor""" )
logger.warning(
"""Could not find image processor auto map in the image processor config or the model config."""
""" Loading based on pattern matching with the model's feature extractor configuration.""" )
# If we don't find the image processor class in the image processor config, let's try the model config.
if image_processor_class is None and image_processor_auto_map is None:
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ):
_SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_ )
# It could be in `config.image_processor_type``
_SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase_ , """image_processor_type""" , UpperCAmelCase_ )
if hasattr(UpperCAmelCase_ , """auto_map""" ) and "AutoImageProcessor" in config.auto_map:
_SCREAMING_SNAKE_CASE = config.auto_map["AutoImageProcessor"]
if image_processor_class is not None:
_SCREAMING_SNAKE_CASE = image_processor_class_from_name(UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE = image_processor_auto_map is not None
_SCREAMING_SNAKE_CASE = image_processor_class is not None or type(UpperCAmelCase_ ) in IMAGE_PROCESSOR_MAPPING
_SCREAMING_SNAKE_CASE = resolve_trust_remote_code(
UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
if has_remote_code and trust_remote_code:
_SCREAMING_SNAKE_CASE = get_class_from_dynamic_module(
UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
_SCREAMING_SNAKE_CASE = kwargs.pop("""code_revision""" , UpperCAmelCase_ )
if os.path.isdir(UpperCAmelCase_ ):
image_processor_class.register_for_auto_class()
return image_processor_class.from_dict(UpperCAmelCase_ , **UpperCAmelCase_ )
elif image_processor_class is not None:
return image_processor_class.from_dict(UpperCAmelCase_ , **UpperCAmelCase_ )
# Last try: we use the IMAGE_PROCESSOR_MAPPING.
elif type(UpperCAmelCase_ ) in IMAGE_PROCESSOR_MAPPING:
_SCREAMING_SNAKE_CASE = IMAGE_PROCESSOR_MAPPING[type(UpperCAmelCase_ )]
return image_processor_class.from_dict(UpperCAmelCase_ , **UpperCAmelCase_ )
raise ValueError(
F'Unrecognized image processor in {pretrained_model_name_or_path}. Should have a '
F'`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following '
F'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}' )
@staticmethod
def UpperCamelCase ( UpperCAmelCase_: Dict , UpperCAmelCase_: List[str] ):
'''simple docstring'''
IMAGE_PROCESSOR_MAPPING.register(UpperCAmelCase_ , UpperCAmelCase_ )
import cva
import numpy as np
class a__ :
def __init__( self : Any,_A : float,_A : int ):
"""simple docstring"""
if k in (0.04, 0.06):
SCREAMING_SNAKE_CASE_ : Union[str, Any] = k
SCREAMING_SNAKE_CASE_ : str = window_size
else:
raise ValueError("invalid k value" )
def __str__( self : Union[str, Any] ):
"""simple docstring"""
return str(self.k )
def __UpperCamelCase ( self : Optional[int],_A : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = cva.imread(_A,0 )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : int = img.shape
SCREAMING_SNAKE_CASE_ : list[list[int]] = []
SCREAMING_SNAKE_CASE_ : Optional[Any] = img.copy()
SCREAMING_SNAKE_CASE_ : Optional[Any] = cva.cvtColor(_A,cva.COLOR_GRAY2RGB )
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[Any] = np.gradient(_A )
SCREAMING_SNAKE_CASE_ : str = dx**2
SCREAMING_SNAKE_CASE_ : Optional[Any] = dy**2
SCREAMING_SNAKE_CASE_ : Optional[Any] = dx * dy
SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.04
SCREAMING_SNAKE_CASE_ : str = self.window_size // 2
for y in range(_A,h - offset ):
for x in range(_A,w - offset ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
SCREAMING_SNAKE_CASE_ : int = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
SCREAMING_SNAKE_CASE_ : Optional[int] = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
SCREAMING_SNAKE_CASE_ : int = (wxx * wyy) - (wxy**2)
SCREAMING_SNAKE_CASE_ : Optional[int] = wxx + wyy
SCREAMING_SNAKE_CASE_ : List[Any] = det - k * (trace**2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r] )
color_img.itemset((y, x, 0),0 )
color_img.itemset((y, x, 1),0 )
color_img.itemset((y, x, 2),255 )
return color_img, corner_list
if __name__ == "__main__":
__lowerCamelCase : Optional[int] = HarrisCorner(0.04, 3)
__lowerCamelCase , __lowerCamelCase : List[Any] = edge_detect.detect('''path_to_image''')
cva.imwrite('''detect.png''', color_img)
18
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import require_keras_nlp, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_keras_nlp_available():
from transformers.models.gpta import TFGPTaTokenizer
__UpperCamelCase : Optional[Any] = ['gpt2']
__UpperCamelCase : str = 'gpt2'
if is_tf_available():
class lowercase__ ( tf.Module):
def __init__( self : Optional[Any] , UpperCamelCase__ : Union[str, Any] ):
'''simple docstring'''
super().__init__()
SCREAMING_SNAKE_CASE : Dict = tokenizer
SCREAMING_SNAKE_CASE : int = AutoConfig.from_pretrained(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Dict = TFGPTaLMHeadModel.from_config(UpperCamelCase__ )
@tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) )
def __A ( self : str , UpperCamelCase__ : int ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Optional[Any] = tokenized['''input_ids'''].to_tensor()
SCREAMING_SNAKE_CASE : Any = tf.cast(input_ids_dense > 0 , tf.intaa )
# input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])
SCREAMING_SNAKE_CASE : List[Any] = self.model(input_ids=UpperCamelCase__ , attention_mask=UpperCamelCase__ )['''logits''']
return outputs
@require_tf
@require_keras_nlp
class lowercase__ ( unittest.TestCase):
def __A ( self : int ):
'''simple docstring'''
super().setUp()
SCREAMING_SNAKE_CASE : Optional[Any] = [GPTaTokenizer.from_pretrained(UpperCamelCase__ ) for checkpoint in (TOKENIZER_CHECKPOINTS)]
SCREAMING_SNAKE_CASE : List[str] = [TFGPTaTokenizer.from_pretrained(UpperCamelCase__ ) for checkpoint in TOKENIZER_CHECKPOINTS]
assert len(self.tokenizers ) == len(self.tf_tokenizers )
SCREAMING_SNAKE_CASE : Tuple = [
'''This is a straightforward English test sentence.''',
'''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''',
'''Now we\'re going to add some Chinese: 一 二 三 一二三''',
'''And some much more rare Chinese: 齉 堃 齉堃''',
'''Je vais aussi écrire en français pour tester les accents''',
'''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
]
SCREAMING_SNAKE_CASE : Dict = list(zip(self.test_sentences , self.test_sentences[::-1] ) )
def __A ( self : str ):
'''simple docstring'''
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ):
for test_inputs in self.test_sentences:
SCREAMING_SNAKE_CASE : Dict = tokenizer([test_inputs] , return_tensors='''tf''' )
SCREAMING_SNAKE_CASE : Any = tf_tokenizer([test_inputs] )
for key in python_outputs.keys():
# convert them to numpy to avoid messing with ragged tensors
SCREAMING_SNAKE_CASE : int = python_outputs[key].numpy()
SCREAMING_SNAKE_CASE : int = tf_outputs[key].numpy()
self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) )
self.assertTrue(tf.reduce_all(tf.cast(UpperCamelCase__ , tf.intaa ) == tf_outputs_values ) )
@slow
def __A ( self : Optional[Any] ):
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
SCREAMING_SNAKE_CASE : Optional[int] = tf.function(UpperCamelCase__ )
for test_inputs in self.test_sentences:
SCREAMING_SNAKE_CASE : Optional[int] = tf.constant(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : List[str] = compiled_tokenizer(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = tf_tokenizer(UpperCamelCase__ )
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) )
@slow
def __A ( self : Optional[int] ):
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
SCREAMING_SNAKE_CASE : str = ModelToSave(tokenizer=UpperCamelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = tf.convert_to_tensor([self.test_sentences[0]] )
SCREAMING_SNAKE_CASE : Union[str, Any] = model.serving(UpperCamelCase__ ) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
SCREAMING_SNAKE_CASE : List[str] = Path(UpperCamelCase__ ) / '''saved.model'''
tf.saved_model.save(UpperCamelCase__ , UpperCamelCase__ , signatures={'''serving_default''': model.serving} )
SCREAMING_SNAKE_CASE : str = tf.saved_model.load(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : int = loaded_model.signatures['''serving_default'''](UpperCamelCase__ )['''output_0''']
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertTrue(tf.reduce_all(out == loaded_output ) )
@slow
def __A ( self : List[str] ):
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
SCREAMING_SNAKE_CASE : List[Any] = tf.convert_to_tensor([self.test_sentences[0]] )
SCREAMING_SNAKE_CASE : Tuple = tf_tokenizer(UpperCamelCase__ ) # Build model with some sample inputs
SCREAMING_SNAKE_CASE : Union[str, Any] = tf_tokenizer.get_config()
SCREAMING_SNAKE_CASE : Optional[Any] = TFGPTaTokenizer.from_config(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : str = model_from_config(UpperCamelCase__ )
for key in from_config_output.keys():
self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) )
@slow
def __A ( self : Optional[int] ):
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
# for the test to run
SCREAMING_SNAKE_CASE : Tuple = 12_3123
for max_length in [3, 5, 1024]:
SCREAMING_SNAKE_CASE : Dict = tf.convert_to_tensor([self.test_sentences[0]] )
SCREAMING_SNAKE_CASE : Tuple = tf_tokenizer(UpperCamelCase__ , max_length=UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Tuple = out['''input_ids'''].numpy().shape[1]
assert out_length == max_length
182
0
"""simple docstring"""
from __future__ import annotations
from decimal import Decimal
from numpy import array
def _snake_case ( lowerCamelCase__ : list[list[float]] ) -> list[list[float]]:
lowerCamelCase_ : List[str] =Decimal
# Check if the provided matrix has 2 rows and 2 columns
# since this implementation only works for 2x2 matrices
if len(lowerCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2:
# Calculate the determinant of the matrix
lowerCamelCase_ : Any =float(
d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) )
if determinant == 0:
raise ValueError("This matrix has no inverse." )
# Creates a copy of the matrix with swapped positions of the elements
lowerCamelCase_ : str =[[0.0, 0.0], [0.0, 0.0]]
lowerCamelCase_ , lowerCamelCase_ : Optional[Any] =matrix[1][1], matrix[0][0]
lowerCamelCase_ , lowerCamelCase_ : int =-matrix[1][0], -matrix[0][1]
# Calculate the inverse of the matrix
return [
[(float(d(lowerCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix
]
elif (
len(lowerCamelCase__ ) == 3
and len(matrix[0] ) == 3
and len(matrix[1] ) == 3
and len(matrix[2] ) == 3
):
# Calculate the determinant of the matrix using Sarrus rule
lowerCamelCase_ : int =float(
(
(d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] ))
+ (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] ))
+ (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] ))
)
- (
(d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] ))
+ (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] ))
+ (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] ))
) )
if determinant == 0:
raise ValueError("This matrix has no inverse." )
# Creating cofactor matrix
lowerCamelCase_ : Optional[Any] =[
[d(0.0 ), d(0.0 ), d(0.0 )],
[d(0.0 ), d(0.0 ), d(0.0 )],
[d(0.0 ), d(0.0 ), d(0.0 )],
]
lowerCamelCase_ : Union[str, Any] =(d(matrix[1][1] ) * d(matrix[2][2] )) - (
d(matrix[1][2] ) * d(matrix[2][1] )
)
lowerCamelCase_ : Any =-(
(d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] ))
)
lowerCamelCase_ : List[str] =(d(matrix[1][0] ) * d(matrix[2][1] )) - (
d(matrix[1][1] ) * d(matrix[2][0] )
)
lowerCamelCase_ : int =-(
(d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] ))
)
lowerCamelCase_ : Any =(d(matrix[0][0] ) * d(matrix[2][2] )) - (
d(matrix[0][2] ) * d(matrix[2][0] )
)
lowerCamelCase_ : str =-(
(d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] ))
)
lowerCamelCase_ : List[str] =(d(matrix[0][1] ) * d(matrix[1][2] )) - (
d(matrix[0][2] ) * d(matrix[1][1] )
)
lowerCamelCase_ : Optional[Any] =-(
(d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] ))
)
lowerCamelCase_ : List[str] =(d(matrix[0][0] ) * d(matrix[1][1] )) - (
d(matrix[0][1] ) * d(matrix[1][0] )
)
# Transpose the cofactor matrix (Adjoint matrix)
lowerCamelCase_ : Optional[int] =array(lowerCamelCase__ )
for i in range(3 ):
for j in range(3 ):
lowerCamelCase_ : Optional[int] =cofactor_matrix[j][i]
# Inverse of the matrix using the formula (1/determinant) * adjoint matrix
lowerCamelCase_ : Tuple =array(lowerCamelCase__ )
for i in range(3 ):
for j in range(3 ):
inverse_matrix[i][j] /= d(lowerCamelCase__ )
# Calculate the inverse of the matrix
return [[float(d(lowerCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix]
raise ValueError("Please provide a matrix of size 2x2 or 3x3." )
209
"""simple docstring"""
def _snake_case ( lowerCamelCase__ : Optional[Any] ) -> Optional[int]:
if not head:
return True
# split the list to two parts
lowerCamelCase_ , lowerCamelCase_ : Union[str, Any] =head.next, head
while fast and fast.next:
lowerCamelCase_ : Optional[Any] =fast.next.next
lowerCamelCase_ : str =slow.next
lowerCamelCase_ : Tuple =slow.next
lowerCamelCase_ : Any =None # Don't forget here! But forget still works!
# reverse the second part
lowerCamelCase_ : List[str] =None
while second:
lowerCamelCase_ : Any =second.next
lowerCamelCase_ : Union[str, Any] =node
lowerCamelCase_ : Union[str, Any] =second
lowerCamelCase_ : Optional[Any] =nxt
# compare two parts
# second part has the same or one less node
while node:
if node.val != head.val:
return False
lowerCamelCase_ : List[str] =node.next
lowerCamelCase_ : Optional[Any] =head.next
return True
def _snake_case ( lowerCamelCase__ : str ) -> Optional[int]:
if not head or not head.next:
return True
# 1. Get the midpoint (slow)
lowerCamelCase_ : List[str] =head
while fast and fast.next:
lowerCamelCase_ , lowerCamelCase_ : Union[str, Any] =fast.next.next, slow.next
# 2. Push the second half into the stack
lowerCamelCase_ : List[Any] =[slow.val]
while slow.next:
lowerCamelCase_ : List[Any] =slow.next
stack.append(slow.val )
# 3. Comparison
while stack:
if stack.pop() != cur.val:
return False
lowerCamelCase_ : Union[str, Any] =cur.next
return True
def _snake_case ( lowerCamelCase__ : Dict ) -> Optional[Any]:
if not head or not head.next:
return True
lowerCamelCase_ : Union[str, Any] ={}
lowerCamelCase_ : List[Any] =0
while head:
if head.val in d:
d[head.val].append(lowerCamelCase__ )
else:
lowerCamelCase_ : List[str] =[pos]
lowerCamelCase_ : Optional[int] =head.next
pos += 1
lowerCamelCase_ : Union[str, Any] =pos - 1
lowerCamelCase_ : Optional[int] =0
for v in d.values():
if len(lowerCamelCase__ ) % 2 != 0:
middle += 1
else:
lowerCamelCase_ : Optional[Any] =0
for i in range(0 , len(lowerCamelCase__ ) ):
if v[i] + v[len(lowerCamelCase__ ) - 1 - step] != checksum:
return False
step += 1
if middle > 1:
return False
return True
209
1
"""simple docstring"""
def lowercase ( A_ , A_ )-> float:
'''simple docstring'''
if mass < 0:
raise ValueError("The mass of a body cannot be negative" )
return 0.5 * mass * abs(A_ ) * abs(A_ )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
40
'''simple docstring'''
from scipy.stats import spearmanr
import datasets
__lowerCAmelCase = '\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n'
__lowerCAmelCase = '\nArgs:\n predictions (`List[float]`): Predicted labels, as returned by a model.\n references (`List[float]`): Ground truth labels.\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n only the spearmanr score. Defaults to `False`.\nReturns:\n spearmanr (`float`): Spearman correlation coefficient.\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n Example 1:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n >>> print(results)\n {\'spearmanr\': -0.7}\n\n Example 2:\n >>> spearmanr_metric = datasets.load_metric("spearmanr")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n ... predictions=[10, 9, 2.5, 6, 4],\n ... return_pvalue=True)\n >>> print(results[\'spearmanr\'])\n -0.7\n >>> print(round(results[\'spearmanr_pvalue\'], 2))\n 0.19\n'
__lowerCAmelCase = r'\\n@book{kokoska2000crc,\n title={CRC standard probability and statistics tables and formulae},\n author={Kokoska, Stephen and Zwillinger, Daniel},\n year={2000},\n publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\n journal = {Nature Methods},\n year = {2020},\n volume = {17},\n pages = {261--272},\n adsurl = {https://rdcu.be/b08Wh},\n doi = {10.1038/s41592-019-0686-2},\n}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _lowerCAmelCase ( datasets.Metric ):
'''simple docstring'''
def lowercase (self ) -> Optional[Any]:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Value("""float""" ),
"""references""": datasets.Value("""float""" ),
} ) , reference_urls=["""https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html"""] , )
def lowercase (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=False ) -> Optional[Any]:
_snake_case = spearmanr(UpperCAmelCase , UpperCAmelCase )
if return_pvalue:
return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
else:
return {"spearmanr": results[0]}
341
0
"""simple docstring"""
def SCREAMING_SNAKE_CASE_ ( snake_case : int , snake_case : int , snake_case : Tuple=False )-> List[Any]:
if isinstance(snake_case , snake_case ) and isinstance(snake_case , snake_case ):
_lowerCamelCase = len(set_a.intersection(snake_case ) )
if alternative_union:
_lowerCamelCase = len(snake_case ) + len(snake_case )
else:
_lowerCamelCase = len(set_a.union(snake_case ) )
return intersection / union
if isinstance(snake_case , (list, tuple) ) and isinstance(snake_case , (list, tuple) ):
_lowerCamelCase = [element for element in set_a if element in set_b]
if alternative_union:
_lowerCamelCase = len(snake_case ) + len(snake_case )
return len(snake_case ) / union
else:
_lowerCamelCase = set_a + [element for element in set_b if element not in set_a]
return len(snake_case ) / len(snake_case )
return len(snake_case ) / len(snake_case )
return None
if __name__ == "__main__":
A_ : Dict ={"""a""", """b""", """c""", """d""", """e"""}
A_ : List[str] ={"""c""", """d""", """e""", """f""", """h""", """i"""}
print(jaccard_similarity(set_a, set_b))
"""simple docstring"""
def lowercase__ ( snake_case_ :list , snake_case_ :list , snake_case_ :int ):
if len(snake_case_ ) != len(snake_case_ ):
raise ValueError('''The length of profit and weight must be same.''' )
if max_weight <= 0:
raise ValueError('''max_weight must greater than zero.''' )
if any(p < 0 for p in profit ):
raise ValueError('''Profit can not be negative.''' )
if any(w < 0 for w in weight ):
raise ValueError('''Weight can not be negative.''' )
# List created to store profit gained for the 1kg in case of each weight
# respectively. Calculate and append profit/weight for each element.
__UpperCAmelCase = [p / w for p, w in zip(snake_case_ , snake_case_ )]
# Creating a copy of the list and sorting profit/weight in ascending order
__UpperCAmelCase = sorted(snake_case_ )
# declaring useful variables
__UpperCAmelCase = len(snake_case_ )
__UpperCAmelCase = 0
__UpperCAmelCase = 0
__UpperCAmelCase = 0
# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
while limit <= max_weight and i < length:
# flag value for encountered greatest element in sorted_profit_by_weight
__UpperCAmelCase = sorted_profit_by_weight[length - i - 1]
__UpperCAmelCase = profit_by_weight.index(snake_case_ )
__UpperCAmelCase = -1
# check if the weight encountered is less than the total weight
# encountered before.
if max_weight - limit >= weight[index]:
limit += weight[index]
# Adding profit gained for the given weight 1 ===
# weight[index]/weight[index]
gain += 1 * profit[index]
else:
# Since the weight encountered is greater than limit, therefore take the
# required number of remaining kgs and calculate profit for it.
# weight remaining / weight[index]
gain += (max_weight - limit) / weight[index] * profit[index]
break
i += 1
return gain
if __name__ == "__main__":
print(
'Input profits, weights, and then max_weight (all positive ints) separated by '
'spaces.'
)
_lowercase : str = [int(x) for x in input('Input profits separated by spaces: ').split()]
_lowercase : str = [int(x) for x in input('Input weights separated by spaces: ').split()]
_lowercase : Any = int(input('Max weight allowed: '))
# Function Call
calc_profit(profit, weight, max_weight)
332
from typing import Optional
import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
BaseModelOutputWithNoAttention,
BaseModelOutputWithPoolingAndNoAttention,
ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
# General docstring
SCREAMING_SNAKE_CASE__ = """RegNetConfig"""
# Base docstring
SCREAMING_SNAKE_CASE__ = """facebook/regnet-y-040"""
SCREAMING_SNAKE_CASE__ = [1, 1088, 7, 7]
# Image classification docstring
SCREAMING_SNAKE_CASE__ = """facebook/regnet-y-040"""
SCREAMING_SNAKE_CASE__ = """tabby, tabby cat"""
SCREAMING_SNAKE_CASE__ = [
"""facebook/regnet-y-040""",
# See all regnet models at https://huggingface.co/models?filter=regnet
]
class A__ ( nn.Module ):
def __init__( self : str , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 3 , _UpperCAmelCase : int = 1 , _UpperCAmelCase : int = 1 , _UpperCAmelCase : Optional[str] = "relu" , ) -> Optional[Any]:
"""simple docstring"""
super().__init__()
__lowercase = nn.Convad(
_UpperCAmelCase , _UpperCAmelCase , kernel_size=_UpperCAmelCase , stride=_UpperCAmelCase , padding=kernel_size // 2 , groups=_UpperCAmelCase , bias=_UpperCAmelCase , )
__lowercase = nn.BatchNormad(_UpperCAmelCase )
__lowercase = ACTaFN[activation] if activation is not None else nn.Identity()
def a__ ( self : Tuple , _UpperCAmelCase : List[str] ) -> str:
"""simple docstring"""
__lowercase = self.convolution(_UpperCAmelCase )
__lowercase = self.normalization(_UpperCAmelCase )
__lowercase = self.activation(_UpperCAmelCase )
return hidden_state
class A__ ( nn.Module ):
def __init__( self : Union[str, Any] , _UpperCAmelCase : RegNetConfig ) -> Any:
"""simple docstring"""
super().__init__()
__lowercase = RegNetConvLayer(
config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act )
__lowercase = config.num_channels
def a__ ( self : Optional[Any] , _UpperCAmelCase : Any ) -> Union[str, Any]:
"""simple docstring"""
__lowercase = pixel_values.shape[1]
if num_channels != self.num_channels:
raise ValueError(
'Make sure that the channel dimension of the pixel values match with the one set in the configuration.' )
__lowercase = self.embedder(_UpperCAmelCase )
return hidden_state
class A__ ( nn.Module ):
def __init__( self : List[str] , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 2 ) -> Optional[int]:
"""simple docstring"""
super().__init__()
__lowercase = nn.Convad(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , stride=_UpperCAmelCase , bias=_UpperCAmelCase )
__lowercase = nn.BatchNormad(_UpperCAmelCase )
def a__ ( self : int , _UpperCAmelCase : Tensor ) -> Tensor:
"""simple docstring"""
__lowercase = self.convolution(_UpperCAmelCase )
__lowercase = self.normalization(_UpperCAmelCase )
return hidden_state
class A__ ( nn.Module ):
def __init__( self : int , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> str:
"""simple docstring"""
super().__init__()
__lowercase = nn.AdaptiveAvgPoolad((1, 1) )
__lowercase = nn.Sequential(
nn.Convad(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 ) , nn.ReLU() , nn.Convad(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 ) , nn.Sigmoid() , )
def a__ ( self : str , _UpperCAmelCase : Dict ) -> str:
"""simple docstring"""
__lowercase = self.pooler(_UpperCAmelCase )
__lowercase = self.attention(_UpperCAmelCase )
__lowercase = hidden_state * attention
return hidden_state
class A__ ( nn.Module ):
def __init__( self : Optional[int] , _UpperCAmelCase : RegNetConfig , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 1 ) -> Tuple:
"""simple docstring"""
super().__init__()
__lowercase = in_channels != out_channels or stride != 1
__lowercase = max(1 , out_channels // config.groups_width )
__lowercase = (
RegNetShortCut(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase ) if should_apply_shortcut else nn.Identity()
)
__lowercase = nn.Sequential(
RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase , groups=_UpperCAmelCase , activation=config.hidden_act ) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=_UpperCAmelCase ) , )
__lowercase = ACTaFN[config.hidden_act]
def a__ ( self : List[str] , _UpperCAmelCase : Tuple ) -> List[Any]:
"""simple docstring"""
__lowercase = hidden_state
__lowercase = self.layer(_UpperCAmelCase )
__lowercase = self.shortcut(_UpperCAmelCase )
hidden_state += residual
__lowercase = self.activation(_UpperCAmelCase )
return hidden_state
class A__ ( nn.Module ):
def __init__( self : Union[str, Any] , _UpperCAmelCase : RegNetConfig , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 1 ) -> Optional[Any]:
"""simple docstring"""
super().__init__()
__lowercase = in_channels != out_channels or stride != 1
__lowercase = max(1 , out_channels // config.groups_width )
__lowercase = (
RegNetShortCut(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase ) if should_apply_shortcut else nn.Identity()
)
__lowercase = nn.Sequential(
RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase , groups=_UpperCAmelCase , activation=config.hidden_act ) , RegNetSELayer(_UpperCAmelCase , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(_UpperCAmelCase , _UpperCAmelCase , kernel_size=1 , activation=_UpperCAmelCase ) , )
__lowercase = ACTaFN[config.hidden_act]
def a__ ( self : Tuple , _UpperCAmelCase : Any ) -> List[str]:
"""simple docstring"""
__lowercase = hidden_state
__lowercase = self.layer(_UpperCAmelCase )
__lowercase = self.shortcut(_UpperCAmelCase )
hidden_state += residual
__lowercase = self.activation(_UpperCAmelCase )
return hidden_state
class A__ ( nn.Module ):
def __init__( self : List[Any] , _UpperCAmelCase : RegNetConfig , _UpperCAmelCase : int , _UpperCAmelCase : int , _UpperCAmelCase : int = 2 , _UpperCAmelCase : int = 2 , ) -> Dict:
"""simple docstring"""
super().__init__()
__lowercase = RegNetXLayer if config.layer_type == 'x' else RegNetYLayer
__lowercase = nn.Sequential(
# downsampling is done in the first layer with stride of 2
layer(
_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , stride=_UpperCAmelCase , ) , *[layer(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) for _ in range(depth - 1 )] , )
def a__ ( self : Any , _UpperCAmelCase : str ) -> int:
"""simple docstring"""
__lowercase = self.layers(_UpperCAmelCase )
return hidden_state
class A__ ( nn.Module ):
def __init__( self : Any , _UpperCAmelCase : RegNetConfig ) -> int:
"""simple docstring"""
super().__init__()
__lowercase = nn.ModuleList([] )
# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
self.stages.append(
RegNetStage(
_UpperCAmelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) )
__lowercase = zip(config.hidden_sizes , config.hidden_sizes[1:] )
for (in_channels, out_channels), depth in zip(_UpperCAmelCase , config.depths[1:] ):
self.stages.append(RegNetStage(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , depth=_UpperCAmelCase ) )
def a__ ( self : int , _UpperCAmelCase : Tensor , _UpperCAmelCase : bool = False , _UpperCAmelCase : bool = True ) -> BaseModelOutputWithNoAttention:
"""simple docstring"""
__lowercase = () if output_hidden_states else None
for stage_module in self.stages:
if output_hidden_states:
__lowercase = hidden_states + (hidden_state,)
__lowercase = stage_module(_UpperCAmelCase )
if output_hidden_states:
__lowercase = hidden_states + (hidden_state,)
if not return_dict:
return tuple(v for v in [hidden_state, hidden_states] if v is not None )
return BaseModelOutputWithNoAttention(last_hidden_state=_UpperCAmelCase , hidden_states=_UpperCAmelCase )
class A__ ( lowerCAmelCase__ ):
lowerCAmelCase__ : Optional[Any] = RegNetConfig
lowerCAmelCase__ : Optional[int] = "regnet"
lowerCAmelCase__ : Dict = "pixel_values"
lowerCAmelCase__ : List[str] = True
def a__ ( self : Any , _UpperCAmelCase : Any ) -> Dict:
"""simple docstring"""
if isinstance(_UpperCAmelCase , nn.Convad ):
nn.init.kaiming_normal_(module.weight , mode='fan_out' , nonlinearity='relu' )
elif isinstance(_UpperCAmelCase , (nn.BatchNormad, nn.GroupNorm) ):
nn.init.constant_(module.weight , 1 )
nn.init.constant_(module.bias , 0 )
def a__ ( self : Any , _UpperCAmelCase : Any , _UpperCAmelCase : Optional[Any]=False ) -> Dict:
"""simple docstring"""
if isinstance(_UpperCAmelCase , _UpperCAmelCase ):
__lowercase = value
SCREAMING_SNAKE_CASE__ = r"""
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.
Parameters:
config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
SCREAMING_SNAKE_CASE__ = r"""
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
[`ConvNextImageProcessor.__call__`] for details.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
"The bare RegNet model outputting raw features without any specific head on top." , lowerCAmelCase__ , )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class A__ ( lowerCAmelCase__ ):
def __init__( self : List[Any] , _UpperCAmelCase : Any ) -> str:
"""simple docstring"""
super().__init__(_UpperCAmelCase )
__lowercase = config
__lowercase = RegNetEmbeddings(_UpperCAmelCase )
__lowercase = RegNetEncoder(_UpperCAmelCase )
__lowercase = nn.AdaptiveAvgPoolad((1, 1) )
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(_UpperCAmelCase )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC , output_type=_UpperCAmelCase , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
def a__ ( self : Tuple , _UpperCAmelCase : Tensor , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[bool] = None ) -> BaseModelOutputWithPoolingAndNoAttention:
"""simple docstring"""
__lowercase = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
__lowercase = return_dict if return_dict is not None else self.config.use_return_dict
__lowercase = self.embedder(_UpperCAmelCase )
__lowercase = self.encoder(
_UpperCAmelCase , output_hidden_states=_UpperCAmelCase , return_dict=_UpperCAmelCase )
__lowercase = encoder_outputs[0]
__lowercase = self.pooler(_UpperCAmelCase )
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=_UpperCAmelCase , pooler_output=_UpperCAmelCase , hidden_states=encoder_outputs.hidden_states , )
@add_start_docstrings(
"\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , lowerCAmelCase__ , )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class A__ ( lowerCAmelCase__ ):
def __init__( self : str , _UpperCAmelCase : List[Any] ) -> Tuple:
"""simple docstring"""
super().__init__(_UpperCAmelCase )
__lowercase = config.num_labels
__lowercase = RegNetModel(_UpperCAmelCase )
# classification head
__lowercase = nn.Sequential(
nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , )
# initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(_UpperCAmelCase )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=_UpperCAmelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
def a__ ( self : List[Any] , _UpperCAmelCase : Optional[torch.FloatTensor] = None , _UpperCAmelCase : Optional[torch.LongTensor] = None , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[bool] = None , ) -> ImageClassifierOutputWithNoAttention:
"""simple docstring"""
__lowercase = return_dict if return_dict is not None else self.config.use_return_dict
__lowercase = self.regnet(_UpperCAmelCase , output_hidden_states=_UpperCAmelCase , return_dict=_UpperCAmelCase )
__lowercase = outputs.pooler_output if return_dict else outputs[1]
__lowercase = self.classifier(_UpperCAmelCase )
__lowercase = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
__lowercase = 'regression'
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
__lowercase = 'single_label_classification'
else:
__lowercase = 'multi_label_classification'
if self.config.problem_type == "regression":
__lowercase = MSELoss()
if self.num_labels == 1:
__lowercase = loss_fct(logits.squeeze() , labels.squeeze() )
else:
__lowercase = loss_fct(_UpperCAmelCase , _UpperCAmelCase )
elif self.config.problem_type == "single_label_classification":
__lowercase = CrossEntropyLoss()
__lowercase = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
__lowercase = BCEWithLogitsLoss()
__lowercase = loss_fct(_UpperCAmelCase , _UpperCAmelCase )
if not return_dict:
__lowercase = (logits,) + outputs[2:]
return (loss,) + output if loss is not None else output
return ImageClassifierOutputWithNoAttention(loss=_UpperCAmelCase , logits=_UpperCAmelCase , hidden_states=outputs.hidden_states )
from itertools import count
def UpperCamelCase ( _a = 5_0 ) -> int:
'''simple docstring'''
lowercase_ :Dict = [1] * min_block_length
for n in count(_a ):
fill_count_functions.append(1 )
for block_length in range(_a , n + 1 ):
for block_start in range(n - block_length ):
fill_count_functions[n] += fill_count_functions[
n - block_start - block_length - 1
]
fill_count_functions[n] += 1
if fill_count_functions[n] > 1_0_0_0_0_0_0:
break
return n
if __name__ == "__main__":
print(f"{solution() = }")
252
0
import inspect
from typing import List, Optional, Tuple, Union
import numpy as np
import PIL
import torch
import torch.utils.checkpoint
from ...models import UNetaDModel, VQModel
from ...schedulers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
def __lowerCamelCase ( UpperCAmelCase_ : Dict ):
"""simple docstring"""
a , a :Tuple = image.size
a , a :Optional[Any] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
a :str = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] )
a :Union[str, Any] = np.array(UpperCAmelCase_ ).astype(np.floataa ) / 255.0
a :Tuple = image[None].transpose(0 , 3 , 1 , 2 )
a :str = torch.from_numpy(UpperCAmelCase_ )
return 2.0 * image - 1.0
class _snake_case ( _snake_case ):
def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ):
super().__init__()
self.register_modules(vqvae=_lowerCamelCase , unet=_lowerCamelCase , scheduler=_lowerCamelCase )
@torch.no_grad()
def __call__( self , _lowerCamelCase = None , _lowerCamelCase = 1 , _lowerCamelCase = 100 , _lowerCamelCase = 0.0 , _lowerCamelCase = None , _lowerCamelCase = "pil" , _lowerCamelCase = True , ):
if isinstance(_lowerCamelCase , PIL.Image.Image ):
a :List[str] = 1
elif isinstance(_lowerCamelCase , torch.Tensor ):
a :int = image.shape[0]
else:
raise ValueError(F'''`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(_lowerCamelCase )}''' )
if isinstance(_lowerCamelCase , PIL.Image.Image ):
a :Dict = preprocess(_lowerCamelCase )
a , a :Optional[int] = image.shape[-2:]
# in_channels should be 6: 3 for latents, 3 for low resolution image
a :Dict = (batch_size, self.unet.config.in_channels // 2, height, width)
a :int = next(self.unet.parameters() ).dtype
a :Tuple = randn_tensor(_lowerCamelCase , generator=_lowerCamelCase , device=self.device , dtype=_lowerCamelCase )
a :Optional[Any] = image.to(device=self.device , dtype=_lowerCamelCase )
# set timesteps and move to the correct device
self.scheduler.set_timesteps(_lowerCamelCase , device=self.device )
a :Optional[int] = self.scheduler.timesteps
# scale the initial noise by the standard deviation required by the scheduler
a :Tuple = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
a :Any = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() )
a :Tuple = {}
if accepts_eta:
a :Optional[int] = eta
for t in self.progress_bar(_lowerCamelCase ):
# concat latents and low resolution image in the channel dimension.
a :Tuple = torch.cat([latents, image] , dim=1 )
a :int = self.scheduler.scale_model_input(_lowerCamelCase , _lowerCamelCase )
# predict the noise residual
a :Union[str, Any] = self.unet(_lowerCamelCase , _lowerCamelCase ).sample
# compute the previous noisy sample x_t -> x_t-1
a :Optional[Any] = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample
# decode the image latents with the VQVAE
a :Optional[int] = self.vqvae.decode(_lowerCamelCase ).sample
a :Optional[Any] = torch.clamp(_lowerCamelCase , -1.0 , 1.0 )
a :List[Any] = image / 2 + 0.5
a :Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy()
if output_type == "pil":
a :int = self.numpy_to_pil(_lowerCamelCase )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=_lowerCamelCase )
94
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
snake_case : Dict = logging.get_logger(__name__)
snake_case : Tuple = '''▁'''
snake_case : Any = {'''vocab_file''': '''sentencepiece.bpe.model'''}
snake_case : Tuple = {
'''vocab_file''': {
'''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''',
'''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''',
'''xlm-roberta-large-finetuned-conll02-dutch''': (
'''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model'''
),
'''xlm-roberta-large-finetuned-conll02-spanish''': (
'''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model'''
),
'''xlm-roberta-large-finetuned-conll03-english''': (
'''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model'''
),
'''xlm-roberta-large-finetuned-conll03-german''': (
'''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model'''
),
}
}
snake_case : int = {
'''xlm-roberta-base''': 5_12,
'''xlm-roberta-large''': 5_12,
'''xlm-roberta-large-finetuned-conll02-dutch''': 5_12,
'''xlm-roberta-large-finetuned-conll02-spanish''': 5_12,
'''xlm-roberta-large-finetuned-conll03-english''': 5_12,
'''xlm-roberta-large-finetuned-conll03-german''': 5_12,
}
class _snake_case ( _snake_case ):
SCREAMING_SNAKE_CASE__ = VOCAB_FILES_NAMES
SCREAMING_SNAKE_CASE__ = PRETRAINED_VOCAB_FILES_MAP
SCREAMING_SNAKE_CASE__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
SCREAMING_SNAKE_CASE__ = ['input_ids', 'attention_mask']
def __init__( self , _lowerCamelCase , _lowerCamelCase="<s>" , _lowerCamelCase="</s>" , _lowerCamelCase="</s>" , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase = None , **_lowerCamelCase , ):
# Mask token behave like a normal word, i.e. include the space before it
a :Optional[int] = AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token
a :int = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , cls_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , )
a :Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(_lowerCamelCase ) )
a :str = vocab_file
# Original fairseq vocab and spm vocab must be "aligned":
# Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
# fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
# spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
# Mimic fairseq token-to-id alignment for the first 4 token
a :Tuple = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}
# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
a :List[str] = 1
a :Dict = len(self.sp_model ) + self.fairseq_offset
a :List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def __getstate__( self ):
a :List[str] = self.__dict__.copy()
a :Optional[int] = None
a :int = self.sp_model.serialized_model_proto()
return state
def __setstate__( self , _lowerCamelCase ):
a :Union[str, Any] = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
a :Union[str, Any] = {}
a :Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ):
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
a :List[Any] = [self.cls_token_id]
a :Dict = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ):
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase )
if token_ids_a is None:
return [1] + ([0] * len(_lowerCamelCase )) + [1]
return [1] + ([0] * len(_lowerCamelCase )) + [1, 1] + ([0] * len(_lowerCamelCase )) + [1]
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ):
a :int = [self.sep_token_id]
a :int = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def SCREAMING_SNAKE_CASE__ ( self ):
return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token
def SCREAMING_SNAKE_CASE__ ( self ):
a :Any = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ):
return self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase )
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ):
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
a :Optional[Any] = self.sp_model.PieceToId(_lowerCamelCase )
# Need to return unknown token if the SP model returned 0
return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ):
if index in self.fairseq_ids_to_tokens:
return self.fairseq_ids_to_tokens[index]
return self.sp_model.IdToPiece(index - self.fairseq_offset )
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase ):
a :Tuple = ''''''.join(_lowerCamelCase ).replace(_lowerCamelCase , ''' ''' ).strip()
return out_string
def SCREAMING_SNAKE_CASE__ ( self , _lowerCamelCase , _lowerCamelCase = None ):
if not os.path.isdir(_lowerCamelCase ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
a :int = os.path.join(
_lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , _lowerCamelCase )
elif not os.path.isfile(self.vocab_file ):
with open(_lowerCamelCase , '''wb''' ) as fi:
a :List[Any] = self.sp_model.serialized_model_proto()
fi.write(_lowerCamelCase )
return (out_vocab_file,)
94
1
def _lowerCAmelCase ( ):
for n in range(1 , 1000000 ):
yield n * (n + 1) // 2
def _lowerCAmelCase ( lowercase_ ):
UpperCAmelCase = 1
UpperCAmelCase = 2
while i * i <= n:
UpperCAmelCase = 0
while n % i == 0:
n //= i
multiplicity += 1
divisors_count *= multiplicity + 1
i += 1
if n > 1:
divisors_count *= 2
return divisors_count
def _lowerCAmelCase ( ):
return next(i for i in triangle_number_generator() if count_divisors(lowercase_ ) > 500 )
if __name__ == "__main__":
print(solution())
366
"""simple docstring"""
import contextlib
import copy
import random
from typing import Any, Dict, Iterable, Optional, Union
import numpy as np
import torch
from .utils import deprecate, is_transformers_available
if is_transformers_available():
import transformers
def _lowerCAmelCase ( lowercase_ ):
random.seed(lowercase_ )
np.random.seed(lowercase_ )
torch.manual_seed(lowercase_ )
torch.cuda.manual_seed_all(lowercase_ )
# ^^ safe to call this function even if cuda is not available
class A_ :
"""simple docstring"""
def __init__( self :Any , lowercase_ :Iterable[torch.nn.Parameter] , lowercase_ :float = 0.9999 , lowercase_ :float = 0.0 , lowercase_ :int = 0 , lowercase_ :bool = False , lowercase_ :Union[float, int] = 1.0 , lowercase_ :Union[float, int] = 2 / 3 , lowercase_ :Optional[Any] = None , lowercase_ :Dict[str, Any] = None , **lowercase_ :Dict , ) -> Optional[int]:
if isinstance(lowercase_ , torch.nn.Module ):
UpperCAmelCase = (
'Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. '
'Please pass the parameters of the module instead.'
)
deprecate(
'passing a `torch.nn.Module` to `ExponentialMovingAverage`' , '1.0.0' , lowercase_ , standard_warn=lowercase_ , )
UpperCAmelCase = parameters.parameters()
# set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility
UpperCAmelCase = True
if kwargs.get('max_value' , lowercase_ ) is not None:
UpperCAmelCase = 'The `max_value` argument is deprecated. Please use `decay` instead.'
deprecate('max_value' , '1.0.0' , lowercase_ , standard_warn=lowercase_ )
UpperCAmelCase = kwargs['max_value']
if kwargs.get('min_value' , lowercase_ ) is not None:
UpperCAmelCase = 'The `min_value` argument is deprecated. Please use `min_decay` instead.'
deprecate('min_value' , '1.0.0' , lowercase_ , standard_warn=lowercase_ )
UpperCAmelCase = kwargs['min_value']
UpperCAmelCase = list(lowercase_ )
UpperCAmelCase = [p.clone().detach() for p in parameters]
if kwargs.get('device' , lowercase_ ) is not None:
UpperCAmelCase = 'The `device` argument is deprecated. Please use `to` instead.'
deprecate('device' , '1.0.0' , lowercase_ , standard_warn=lowercase_ )
self.to(device=kwargs['device'] )
UpperCAmelCase = None
UpperCAmelCase = decay
UpperCAmelCase = min_decay
UpperCAmelCase = update_after_step
UpperCAmelCase = use_ema_warmup
UpperCAmelCase = inv_gamma
UpperCAmelCase = power
UpperCAmelCase = 0
UpperCAmelCase = None # set in `step()`
UpperCAmelCase = model_cls
UpperCAmelCase = model_config
@classmethod
def UpperCAmelCase__ ( cls :int , lowercase_ :Union[str, Any] , lowercase_ :Any ) -> "EMAModel":
UpperCAmelCase , UpperCAmelCase = model_cls.load_config(lowercase_ , return_unused_kwargs=lowercase_ )
UpperCAmelCase = model_cls.from_pretrained(lowercase_ )
UpperCAmelCase = cls(model.parameters() , model_cls=lowercase_ , model_config=model.config )
ema_model.load_state_dict(lowercase_ )
return ema_model
def UpperCAmelCase__ ( self :List[Any] , lowercase_ :List[str] ) -> int:
if self.model_cls is None:
raise ValueError('`save_pretrained` can only be used if `model_cls` was defined at __init__.' )
if self.model_config is None:
raise ValueError('`save_pretrained` can only be used if `model_config` was defined at __init__.' )
UpperCAmelCase = self.model_cls.from_config(self.model_config )
UpperCAmelCase = self.state_dict()
state_dict.pop('shadow_params' , lowercase_ )
model.register_to_config(**lowercase_ )
self.copy_to(model.parameters() )
model.save_pretrained(lowercase_ )
def UpperCAmelCase__ ( self :Optional[int] , lowercase_ :int ) -> float:
UpperCAmelCase = max(0 , optimization_step - self.update_after_step - 1 )
if step <= 0:
return 0.0
if self.use_ema_warmup:
UpperCAmelCase = 1 - (1 + step / self.inv_gamma) ** -self.power
else:
UpperCAmelCase = (1 + step) / (10 + step)
UpperCAmelCase = min(lowercase_ , self.decay )
# make sure decay is not smaller than min_decay
UpperCAmelCase = max(lowercase_ , self.min_decay )
return cur_decay_value
@torch.no_grad()
def UpperCAmelCase__ ( self :List[Any] , lowercase_ :Iterable[torch.nn.Parameter] ) -> Optional[int]:
if isinstance(lowercase_ , torch.nn.Module ):
UpperCAmelCase = (
'Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. '
'Please pass the parameters of the module instead.'
)
deprecate(
'passing a `torch.nn.Module` to `ExponentialMovingAverage.step`' , '1.0.0' , lowercase_ , standard_warn=lowercase_ , )
UpperCAmelCase = parameters.parameters()
UpperCAmelCase = list(lowercase_ )
self.optimization_step += 1
# Compute the decay factor for the exponential moving average.
UpperCAmelCase = self.get_decay(self.optimization_step )
UpperCAmelCase = decay
UpperCAmelCase = 1 - decay
UpperCAmelCase = contextlib.nullcontext
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
import deepspeed
for s_param, param in zip(self.shadow_params , lowercase_ ):
if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
UpperCAmelCase = deepspeed.zero.GatheredParameters(lowercase_ , modifier_rank=lowercase_ )
with context_manager():
if param.requires_grad:
s_param.sub_(one_minus_decay * (s_param - param) )
else:
s_param.copy_(lowercase_ )
def UpperCAmelCase__ ( self :Tuple , lowercase_ :Iterable[torch.nn.Parameter] ) -> None:
UpperCAmelCase = list(lowercase_ )
for s_param, param in zip(self.shadow_params , lowercase_ ):
param.data.copy_(s_param.to(param.device ).data )
def UpperCAmelCase__ ( self :Dict , lowercase_ :Tuple=None , lowercase_ :Union[str, Any]=None ) -> None:
UpperCAmelCase = [
p.to(device=lowercase_ , dtype=lowercase_ ) if p.is_floating_point() else p.to(device=lowercase_ )
for p in self.shadow_params
]
def UpperCAmelCase__ ( self :Union[str, Any] ) -> dict:
return {
"decay": self.decay,
"min_decay": self.min_decay,
"optimization_step": self.optimization_step,
"update_after_step": self.update_after_step,
"use_ema_warmup": self.use_ema_warmup,
"inv_gamma": self.inv_gamma,
"power": self.power,
"shadow_params": self.shadow_params,
}
def UpperCAmelCase__ ( self :Optional[int] , lowercase_ :Iterable[torch.nn.Parameter] ) -> None:
UpperCAmelCase = [param.detach().cpu().clone() for param in parameters]
def UpperCAmelCase__ ( self :Optional[Any] , lowercase_ :Iterable[torch.nn.Parameter] ) -> None:
if self.temp_stored_params is None:
raise RuntimeError('This ExponentialMovingAverage has no `store()`ed weights ' 'to `restore()`' )
for c_param, param in zip(self.temp_stored_params , lowercase_ ):
param.data.copy_(c_param.data )
# Better memory-wise.
UpperCAmelCase = None
def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :dict ) -> None:
UpperCAmelCase = copy.deepcopy(lowercase_ )
UpperCAmelCase = state_dict.get('decay' , self.decay )
if self.decay < 0.0 or self.decay > 1.0:
raise ValueError('Decay must be between 0 and 1' )
UpperCAmelCase = state_dict.get('min_decay' , self.min_decay )
if not isinstance(self.min_decay , lowercase_ ):
raise ValueError('Invalid min_decay' )
UpperCAmelCase = state_dict.get('optimization_step' , self.optimization_step )
if not isinstance(self.optimization_step , lowercase_ ):
raise ValueError('Invalid optimization_step' )
UpperCAmelCase = state_dict.get('update_after_step' , self.update_after_step )
if not isinstance(self.update_after_step , lowercase_ ):
raise ValueError('Invalid update_after_step' )
UpperCAmelCase = state_dict.get('use_ema_warmup' , self.use_ema_warmup )
if not isinstance(self.use_ema_warmup , lowercase_ ):
raise ValueError('Invalid use_ema_warmup' )
UpperCAmelCase = state_dict.get('inv_gamma' , self.inv_gamma )
if not isinstance(self.inv_gamma , (float, int) ):
raise ValueError('Invalid inv_gamma' )
UpperCAmelCase = state_dict.get('power' , self.power )
if not isinstance(self.power , (float, int) ):
raise ValueError('Invalid power' )
UpperCAmelCase = state_dict.get('shadow_params' , lowercase_ )
if shadow_params is not None:
UpperCAmelCase = shadow_params
if not isinstance(self.shadow_params , lowercase_ ):
raise ValueError('shadow_params must be a list' )
if not all(isinstance(lowercase_ , torch.Tensor ) for p in self.shadow_params ):
raise ValueError('shadow_params must all be Tensors' )
181
0
'''simple docstring'''
import json
import pathlib
import unittest
import numpy as np
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, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import YolosImageProcessor
class a__( unittest.TestCase ):
def __init__( self : int , __snake_case : str , __snake_case : Dict=7 , __snake_case : int=3 , __snake_case : int=30 , __snake_case : Dict=4_00 , __snake_case : Optional[Any]=True , __snake_case : List[str]=None , __snake_case : Union[str, Any]=True , __snake_case : List[Any]=[0.5, 0.5, 0.5] , __snake_case : Union[str, Any]=[0.5, 0.5, 0.5] , __snake_case : List[Any]=True , __snake_case : List[Any]=1 / 2_55 , __snake_case : Any=True , ):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
a : Tuple = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33}
a : str = parent
a : Any = batch_size
a : Any = num_channels
a : Optional[Any] = min_resolution
a : Tuple = max_resolution
a : str = do_resize
a : List[str] = size
a : List[str] = do_normalize
a : List[Any] = image_mean
a : Tuple = image_std
a : Optional[Any] = do_rescale
a : Any = rescale_factor
a : int = do_pad
def lowercase_ ( self : Optional[Any] ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def lowercase_ ( self : List[str] , __snake_case : str , __snake_case : Tuple=False ):
if not batched:
a : List[Any] = image_inputs[0]
if isinstance(__snake_case , Image.Image ):
a , a : Dict = image.size
else:
a , a : Union[str, Any] = image.shape[1], image.shape[2]
if w < h:
a : Optional[Any] = int(self.size['shortest_edge'] * h / w )
a : Optional[int] = self.size['shortest_edge']
elif w > h:
a : List[str] = self.size['shortest_edge']
a : Tuple = int(self.size['shortest_edge'] * w / h )
else:
a : Any = self.size['shortest_edge']
a : str = self.size['shortest_edge']
else:
a : str = []
for image in image_inputs:
a , a : int = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
a : Tuple = max(__snake_case , key=lambda __snake_case : item[0] )[0]
a : Tuple = max(__snake_case , key=lambda __snake_case : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class a__( lowerCamelCase__ , unittest.TestCase ):
lowercase__ = YolosImageProcessor if is_vision_available() else None
def lowercase_ ( self : Optional[Any] ):
a : Dict = YolosImageProcessingTester(self )
@property
def lowercase_ ( self : Dict ):
return self.image_processor_tester.prepare_image_processor_dict()
def lowercase_ ( self : List[str] ):
a : str = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__snake_case , 'image_mean' ) )
self.assertTrue(hasattr(__snake_case , 'image_std' ) )
self.assertTrue(hasattr(__snake_case , 'do_normalize' ) )
self.assertTrue(hasattr(__snake_case , 'do_resize' ) )
self.assertTrue(hasattr(__snake_case , 'size' ) )
def lowercase_ ( self : Dict ):
a : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} )
self.assertEqual(image_processor.do_pad , __snake_case )
a : str = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__snake_case )
self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} )
self.assertEqual(image_processor.do_pad , __snake_case )
def lowercase_ ( self : List[str] ):
pass
def lowercase_ ( self : List[Any] ):
# Initialize image_processing
a : Union[str, Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case )
for image in image_inputs:
self.assertIsInstance(__snake_case , Image.Image )
# Test not batched input
a : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
a , a : Optional[int] = self.image_processor_tester.get_expected_values(__snake_case )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
a , a : Union[str, Any] = self.image_processor_tester.get_expected_values(__snake_case , batched=__snake_case )
a : Dict = image_processing(__snake_case , return_tensors='pt' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def lowercase_ ( self : Any ):
# Initialize image_processing
a : Any = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
a : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , numpify=__snake_case )
for image in image_inputs:
self.assertIsInstance(__snake_case , np.ndarray )
# Test not batched input
a : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
a , a : Any = self.image_processor_tester.get_expected_values(__snake_case )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
a : str = image_processing(__snake_case , return_tensors='pt' ).pixel_values
a , a : Tuple = self.image_processor_tester.get_expected_values(__snake_case , batched=__snake_case )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def lowercase_ ( self : Optional[int] ):
# Initialize image_processing
a : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
a : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case )
for image in image_inputs:
self.assertIsInstance(__snake_case , torch.Tensor )
# Test not batched input
a : List[str] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values
a , a : List[str] = self.image_processor_tester.get_expected_values(__snake_case )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
a : Optional[int] = image_processing(__snake_case , return_tensors='pt' ).pixel_values
a , a : Any = self.image_processor_tester.get_expected_values(__snake_case , batched=__snake_case )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def lowercase_ ( self : Optional[int] ):
# Initialize image_processings
a : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
a : Tuple = self.image_processing_class(do_resize=__snake_case , do_normalize=__snake_case , do_rescale=__snake_case )
# create random PyTorch tensors
a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case )
for image in image_inputs:
self.assertIsInstance(__snake_case , torch.Tensor )
# Test whether the method "pad" and calling the image processor return the same tensors
a : str = image_processing_a.pad(__snake_case , return_tensors='pt' )
a : Optional[Any] = image_processing_a(__snake_case , return_tensors='pt' )
self.assertTrue(
torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) )
@slow
def lowercase_ ( self : Union[str, Any] ):
# prepare image and target
a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f:
a : int = json.loads(f.read() )
a : Tuple = {'image_id': 3_97_69, 'annotations': target}
# encode them
a : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' )
a : Optional[Any] = image_processing(images=__snake_case , annotations=__snake_case , return_tensors='pt' )
# verify pixel values
a : Dict = torch.Size([1, 3, 8_00, 10_66] )
self.assertEqual(encoding['pixel_values'].shape , __snake_case )
a : Optional[int] = torch.tensor([0.2796, 0.3138, 0.3481] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __snake_case , atol=1e-4 ) )
# verify area
a : Union[str, Any] = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __snake_case ) )
# verify boxes
a : Optional[Any] = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __snake_case )
a : Any = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __snake_case , atol=1e-3 ) )
# verify image_id
a : Any = torch.tensor([3_97_69] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __snake_case ) )
# verify is_crowd
a : List[str] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __snake_case ) )
# verify class_labels
a : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __snake_case ) )
# verify orig_size
a : Any = torch.tensor([4_80, 6_40] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __snake_case ) )
# verify size
a : List[str] = torch.tensor([8_00, 10_66] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __snake_case ) )
@slow
def lowercase_ ( self : List[str] ):
# prepare image, target and masks_path
a : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f:
a : List[str] = json.loads(f.read() )
a : Union[str, Any] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target}
a : List[str] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' )
# encode them
a : Union[str, Any] = YolosImageProcessor(format='coco_panoptic' )
a : int = image_processing(images=__snake_case , annotations=__snake_case , masks_path=__snake_case , return_tensors='pt' )
# verify pixel values
a : int = torch.Size([1, 3, 8_00, 10_66] )
self.assertEqual(encoding['pixel_values'].shape , __snake_case )
a : Optional[Any] = torch.tensor([0.2796, 0.3138, 0.3481] )
self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __snake_case , atol=1e-4 ) )
# verify area
a : List[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] )
self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __snake_case ) )
# verify boxes
a : List[Any] = torch.Size([6, 4] )
self.assertEqual(encoding['labels'][0]['boxes'].shape , __snake_case )
a : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] )
self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __snake_case , atol=1e-3 ) )
# verify image_id
a : str = torch.tensor([3_97_69] )
self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __snake_case ) )
# verify is_crowd
a : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __snake_case ) )
# verify class_labels
a : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] )
self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __snake_case ) )
# verify masks
a : Dict = 82_28_73
self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __snake_case )
# verify orig_size
a : int = torch.tensor([4_80, 6_40] )
self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __snake_case ) )
# verify size
a : Optional[int] = torch.tensor([8_00, 10_66] )
self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __snake_case ) )
297
'''simple docstring'''
from __future__ import annotations
from math import pi, sqrt
def lowerCamelCase__ ( _A , _A ):
if inductance <= 0:
raise ValueError('Inductance cannot be 0 or negative' )
elif capacitance <= 0:
raise ValueError('Capacitance cannot be 0 or negative' )
else:
return (
"Resonant frequency",
float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ),
)
if __name__ == "__main__":
import doctest
doctest.testmod()
297
1
def _A ( lowerCAmelCase_ : int ):
"""simple docstring"""
return str(lowerCAmelCase_ ) == str(lowerCAmelCase_ )[::-1]
def _A ( lowerCAmelCase_ : int ):
"""simple docstring"""
return int(lowerCAmelCase_ ) + int(str(lowerCAmelCase_ )[::-1] )
def _A ( lowerCAmelCase_ : int = 1_0000 ):
"""simple docstring"""
lowerCAmelCase__ = []
for num in range(1 , lowerCAmelCase_ ):
lowerCAmelCase__ = 0
lowerCAmelCase__ = num
while iterations < 50:
lowerCAmelCase__ = sum_reverse(lowerCAmelCase_ )
iterations += 1
if is_palindrome(lowerCAmelCase_ ):
break
else:
lychrel_nums.append(lowerCAmelCase_ )
return len(lowerCAmelCase_ )
if __name__ == "__main__":
print(F"""{solution() = }""")
370
from math import pi, sqrt
def _A ( lowerCAmelCase_ : float ):
"""simple docstring"""
if num <= 0:
raise ValueError("math domain error" )
if num > 171.5:
raise OverflowError("math range error" )
elif num - int(lowerCAmelCase_ ) not in (0, 0.5):
raise NotImplementedError("num must be an integer or a half-integer" )
elif num == 0.5:
return sqrt(lowerCAmelCase_ )
else:
return 1.0 if num == 1 else (num - 1) * gamma(num - 1 )
def _A ( ):
"""simple docstring"""
assert gamma(0.5 ) == sqrt(lowerCAmelCase_ )
assert gamma(1 ) == 1.0
assert gamma(2 ) == 1.0
if __name__ == "__main__":
from doctest import testmod
testmod()
UpperCamelCase = 1.0
while num:
UpperCamelCase = float(input('Gamma of: '))
print(F"""gamma({num}) = {gamma(num)}""")
print('\nEnter 0 to exit...')
221
0
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 _lowercase ( unittest.TestCase ):
'''simple docstring'''
def __magic_name__( self :int ) -> Dict:
__SCREAMING_SNAKE_CASE : Dict = 0
def __magic_name__( self :Dict ) -> Any:
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' )
self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ )
def __magic_name__( self :List[Any] ) -> Optional[int]:
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Tuple = Path(lowerCAmelCase__ ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : List[Any] = Path(lowerCAmelCase__ ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(lowerCAmelCase__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(lowerCAmelCase__ , '''w''' ) )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(lowerCAmelCase__ )
self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ )
def __magic_name__( self :Any ) -> str:
# Ensure we can load the image processor from the feature extractor config
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : str = Path(lowerCAmelCase__ ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : Optional[Any] = Path(lowerCAmelCase__ ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(lowerCAmelCase__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(lowerCAmelCase__ , '''w''' ) )
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained(lowerCAmelCase__ )
self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ )
def __magic_name__( self :int ) -> Union[str, Any]:
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : List[str] = CLIPConfig()
# Create a dummy config file with image_proceesor_type
__SCREAMING_SNAKE_CASE : Tuple = Path(lowerCAmelCase__ ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : List[Any] = Path(lowerCAmelCase__ ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(lowerCAmelCase__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(lowerCAmelCase__ , '''w''' ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
__SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained(lowerCAmelCase__ ).to_dict()
config_dict.pop('''image_processor_type''' )
__SCREAMING_SNAKE_CASE : Dict = CLIPImageProcessor(**lowerCAmelCase__ )
# save in new folder
model_config.save_pretrained(lowerCAmelCase__ )
config.save_pretrained(lowerCAmelCase__ )
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(lowerCAmelCase__ )
# make sure private variable is not incorrectly saved
__SCREAMING_SNAKE_CASE : List[str] = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ )
def __magic_name__( self :str ) -> Optional[Any]:
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Tuple = Path(lowerCAmelCase__ ) / '''preprocessor_config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(lowerCAmelCase__ , '''w''' ) , )
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(lowerCAmelCase__ )
self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ )
def __magic_name__( self :int ) -> Union[str, Any]:
with self.assertRaisesRegex(
lowerCAmelCase__ , '''clip-base is not a local folder and is not a valid model identifier''' ):
__SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained('''clip-base''' )
def __magic_name__( self :Dict ) -> Dict:
with self.assertRaisesRegex(
lowerCAmelCase__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
__SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(lowerCAmelCase__ , revision='''aaaaaa''' )
def __magic_name__( self :Tuple ) -> List[str]:
with self.assertRaisesRegex(
lowerCAmelCase__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' )
def __magic_name__( self :Optional[Any] ) -> str:
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(lowerCAmelCase__ ):
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(lowerCAmelCase__ ):
__SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=lowerCAmelCase__ )
__SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=lowerCAmelCase__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(lowerCAmelCase__ )
__SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained(lowerCAmelCase__ , trust_remote_code=lowerCAmelCase__ )
self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' )
def __magic_name__( self :Dict ) -> Tuple:
try:
AutoConfig.register('''custom''' , lowerCAmelCase__ )
AutoImageProcessor.register(lowerCAmelCase__ , lowerCAmelCase__ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(lowerCAmelCase__ ):
AutoImageProcessor.register(lowerCAmelCase__ , lowerCAmelCase__ )
with tempfile.TemporaryDirectory() as tmpdirname:
__SCREAMING_SNAKE_CASE : Dict = Path(lowerCAmelCase__ ) / '''preprocessor_config.json'''
__SCREAMING_SNAKE_CASE : List[Any] = Path(lowerCAmelCase__ ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(lowerCAmelCase__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(lowerCAmelCase__ , '''w''' ) )
__SCREAMING_SNAKE_CASE : List[str] = CustomImageProcessor.from_pretrained(lowerCAmelCase__ )
# 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(lowerCAmelCase__ )
__SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained(lowerCAmelCase__ )
self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ )
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 __magic_name__( self :List[Any] ) -> int:
class _lowercase ( A__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Optional[Any] = True
try:
AutoConfig.register('''custom''' , lowerCAmelCase__ )
AutoImageProcessor.register(lowerCAmelCase__ , lowerCAmelCase__ )
# If remote code is not set, the default is to use local
__SCREAMING_SNAKE_CASE : str = 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.
__SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=lowerCAmelCase__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
__SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=lowerCAmelCase__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(not hasattr(lowerCAmelCase__ , '''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]
9
'''simple docstring'''
import argparse
import json
import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from transformers import (
VideoMAEConfig,
VideoMAEForPreTraining,
VideoMAEForVideoClassification,
VideoMAEImageProcessor,
)
def a ( lowerCamelCase__ ):
'''simple docstring'''
A_ : Optional[int] = VideoMAEConfig()
set_architecture_configs(lowerCamelCase__ , lowerCamelCase__ )
if "finetuned" not in model_name:
A_ : Dict = False
if "finetuned" in model_name:
A_ : List[Any] = """huggingface/label-files"""
if "kinetics" in model_name:
A_ : Dict = 4_00
A_ : List[str] = """kinetics400-id2label.json"""
elif "ssv2" in model_name:
A_ : Tuple = 1_74
A_ : str = """something-something-v2-id2label.json"""
else:
raise ValueError("""Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned.""" )
A_ : Dict = json.load(open(hf_hub_download(lowerCamelCase__ , lowerCamelCase__ , repo_type="""dataset""" ) , """r""" ) )
A_ : List[str] = {int(lowerCamelCase__ ): v for k, v in idalabel.items()}
A_ : Optional[Any] = idalabel
A_ : Union[str, Any] = {v: k for k, v in idalabel.items()}
return config
def a ( lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
if "small" in model_name:
A_ : int = 3_84
A_ : Union[str, Any] = 15_36
A_ : List[str] = 12
A_ : Optional[int] = 16
A_ : Any = 12
A_ : int = 3
A_ : Optional[Any] = 1_92
A_ : Union[str, Any] = 7_68
elif "large" in model_name:
A_ : List[Any] = 10_24
A_ : Optional[Any] = 40_96
A_ : Optional[Any] = 24
A_ : List[str] = 16
A_ : Any = 12
A_ : str = 8
A_ : str = 5_12
A_ : int = 20_48
elif "huge" in model_name:
A_ : Optional[Any] = 12_80
A_ : str = 51_20
A_ : str = 32
A_ : int = 16
A_ : Any = 12
A_ : Union[str, Any] = 8
A_ : Dict = 6_40
A_ : Optional[Any] = 25_60
elif "base" not in model_name:
raise ValueError("""Model name should include either \"small\", \"base\", \"large\", or \"huge\"""" )
def a ( lowerCamelCase__ ):
'''simple docstring'''
if "encoder." in name:
A_ : List[Any] = name.replace("""encoder.""" , """""" )
if "cls_token" in name:
A_ : List[str] = name.replace("""cls_token""" , """videomae.embeddings.cls_token""" )
if "decoder_pos_embed" in name:
A_ : Tuple = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" )
if "pos_embed" in name and "decoder" not in name:
A_ : int = name.replace("""pos_embed""" , """videomae.embeddings.position_embeddings""" )
if "patch_embed.proj" in name:
A_ : Optional[Any] = name.replace("""patch_embed.proj""" , """videomae.embeddings.patch_embeddings.projection""" )
if "patch_embed.norm" in name:
A_ : Dict = name.replace("""patch_embed.norm""" , """videomae.embeddings.norm""" )
if "decoder.blocks" in name:
A_ : List[str] = name.replace("""decoder.blocks""" , """decoder.decoder_layers""" )
if "blocks" in name:
A_ : List[str] = name.replace("""blocks""" , """videomae.encoder.layer""" )
if "attn.proj" in name:
A_ : str = name.replace("""attn.proj""" , """attention.output.dense""" )
if "attn" in name and "bias" not in name:
A_ : str = name.replace("""attn""" , """attention.self""" )
if "attn" in name:
A_ : Union[str, Any] = name.replace("""attn""" , """attention.attention""" )
if "norm1" in name:
A_ : Any = name.replace("""norm1""" , """layernorm_before""" )
if "norm2" in name:
A_ : List[str] = name.replace("""norm2""" , """layernorm_after""" )
if "mlp.fc1" in name:
A_ : Dict = name.replace("""mlp.fc1""" , """intermediate.dense""" )
if "mlp.fc2" in name:
A_ : List[str] = name.replace("""mlp.fc2""" , """output.dense""" )
if "decoder_embed" in name:
A_ : Optional[Any] = name.replace("""decoder_embed""" , """decoder.decoder_embed""" )
if "decoder_norm" in name:
A_ : Tuple = name.replace("""decoder_norm""" , """decoder.decoder_norm""" )
if "decoder_pred" in name:
A_ : Tuple = name.replace("""decoder_pred""" , """decoder.decoder_pred""" )
if "norm.weight" in name and "decoder" not in name and "fc" not in name:
A_ : Dict = name.replace("""norm.weight""" , """videomae.layernorm.weight""" )
if "norm.bias" in name and "decoder" not in name and "fc" not in name:
A_ : List[str] = name.replace("""norm.bias""" , """videomae.layernorm.bias""" )
if "head" in name and "decoder" not in name:
A_ : Optional[Any] = name.replace("""head""" , """classifier""" )
return name
def a ( lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
for key in orig_state_dict.copy().keys():
A_ : str = orig_state_dict.pop(lowerCamelCase__ )
if key.startswith("""encoder.""" ):
A_ : Tuple = key.replace("""encoder.""" , """""" )
if "qkv" in key:
A_ : Optional[int] = key.split(""".""" )
if key.startswith("""decoder.blocks""" ):
A_ : Union[str, Any] = config.decoder_hidden_size
A_ : Any = int(key_split[2] )
A_ : int = """decoder.decoder_layers."""
if "weight" in key:
A_ : Optional[Any] = val[:dim, :]
A_ : Any = val[dim : dim * 2, :]
A_ : Dict = val[-dim:, :]
else:
A_ : List[Any] = config.hidden_size
A_ : List[Any] = int(key_split[1] )
A_ : int = """videomae.encoder.layer."""
if "weight" in key:
A_ : Any = val[:dim, :]
A_ : Union[str, Any] = val[dim : dim * 2, :]
A_ : List[str] = val[-dim:, :]
else:
A_ : Union[str, Any] = val
return orig_state_dict
def a ( ):
'''simple docstring'''
A_ : List[Any] = hf_hub_download(
repo_id="""hf-internal-testing/spaghetti-video""" , filename="""eating_spaghetti.npy""" , repo_type="""dataset""" )
A_ : Optional[Any] = np.load(lowerCamelCase__ )
return list(lowerCamelCase__ )
def a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ):
'''simple docstring'''
A_ : Any = get_videomae_config(lowerCamelCase__ )
if "finetuned" in model_name:
A_ : List[str] = VideoMAEForVideoClassification(lowerCamelCase__ )
else:
A_ : Optional[Any] = VideoMAEForPreTraining(lowerCamelCase__ )
# download original checkpoint, hosted on Google Drive
A_ : Optional[Any] = """pytorch_model.bin"""
gdown.cached_download(lowerCamelCase__ , lowerCamelCase__ , quiet=lowerCamelCase__ )
A_ : Any = torch.load(lowerCamelCase__ , map_location="""cpu""" )
if "model" in files:
A_ : Any = files["""model"""]
else:
A_ : Dict = files["""module"""]
A_ : Any = convert_state_dict(lowerCamelCase__ , lowerCamelCase__ )
model.load_state_dict(lowerCamelCase__ )
model.eval()
# verify model on basic input
A_ : int = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] )
A_ : Union[str, Any] = prepare_video()
A_ : str = image_processor(lowerCamelCase__ , return_tensors="""pt""" )
if "finetuned" not in model_name:
A_ : List[str] = hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""" , filename="""bool_masked_pos.pt""" )
A_ : Optional[Any] = torch.load(lowerCamelCase__ )
A_ : Dict = model(**lowerCamelCase__ )
A_ : List[Any] = outputs.logits
A_ : Any = [
"""videomae-small-finetuned-kinetics""",
"""videomae-small-finetuned-ssv2""",
# Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)
"""videomae-base-short""",
"""videomae-base-short-finetuned-kinetics""",
"""videomae-base""",
"""videomae-base-finetuned-kinetics""",
"""videomae-large""",
"""videomae-large-finetuned-kinetics""",
"""videomae-huge-finetuned-kinetics""",
# Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)
"""videomae-base-short-ssv2""",
"""videomae-base-short-finetuned-ssv2""",
"""videomae-base-ssv2""",
"""videomae-base-finetuned-ssv2""",
]
# NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
if model_name == "videomae-small-finetuned-kinetics":
A_ : str = torch.Size([1, 4_00] )
A_ : Optional[Any] = torch.tensor([-0.9_291, -0.4_061, -0.9_307] )
elif model_name == "videomae-small-finetuned-ssv2":
A_ : str = torch.Size([1, 1_74] )
A_ : Union[str, Any] = torch.tensor([0.2_671, -0.4_689, -0.8_235] )
elif model_name == "videomae-base":
A_ : Tuple = torch.Size([1, 14_08, 15_36] )
A_ : List[str] = torch.tensor([[0.7_739, 0.7_968, 0.7_089], [0.6_701, 0.7_487, 0.6_209], [0.4_287, 0.5_158, 0.4_773]] )
elif model_name == "videomae-base-short":
A_ : Dict = torch.Size([1, 14_08, 15_36] )
A_ : List[str] = torch.tensor([[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]] )
# we verified the loss both for normalized and unnormalized targets for this one
A_ : List[Any] = torch.tensor([0.5_142] ) if config.norm_pix_loss else torch.tensor([0.6_469] )
elif model_name == "videomae-large":
A_ : str = torch.Size([1, 14_08, 15_36] )
A_ : Dict = torch.tensor([[0.7_149, 0.7_997, 0.6_966], [0.6_768, 0.7_869, 0.6_948], [0.5_139, 0.6_221, 0.5_605]] )
elif model_name == "videomae-large-finetuned-kinetics":
A_ : int = torch.Size([1, 4_00] )
A_ : Optional[Any] = torch.tensor([0.0_771, 0.0_011, -0.3_625] )
elif model_name == "videomae-huge-finetuned-kinetics":
A_ : Union[str, Any] = torch.Size([1, 4_00] )
A_ : Optional[int] = torch.tensor([0.2_433, 0.1_632, -0.4_894] )
elif model_name == "videomae-base-short-finetuned-kinetics":
A_ : List[Any] = torch.Size([1, 4_00] )
A_ : Optional[Any] = torch.tensor([0.6_588, 0.0_990, -0.2_493] )
elif model_name == "videomae-base-finetuned-kinetics":
A_ : Union[str, Any] = torch.Size([1, 4_00] )
A_ : Tuple = torch.tensor([0.3_669, -0.0_688, -0.2_421] )
elif model_name == "videomae-base-short-ssv2":
A_ : Optional[Any] = torch.Size([1, 14_08, 15_36] )
A_ : List[Any] = torch.tensor([[0.4_712, 0.5_296, 0.5_786], [0.2_278, 0.2_729, 0.4_026], [0.0_352, 0.0_730, 0.2_506]] )
elif model_name == "videomae-base-short-finetuned-ssv2":
A_ : Any = torch.Size([1, 1_74] )
A_ : Any = torch.tensor([-0.0_537, -0.1_539, -0.3_266] )
elif model_name == "videomae-base-ssv2":
A_ : Dict = torch.Size([1, 14_08, 15_36] )
A_ : Dict = torch.tensor([[0.8_131, 0.8_727, 0.8_546], [0.7_366, 0.9_377, 0.8_870], [0.5_935, 0.8_874, 0.8_564]] )
elif model_name == "videomae-base-finetuned-ssv2":
A_ : Any = torch.Size([1, 1_74] )
A_ : str = torch.tensor([0.1_961, -0.8_337, -0.6_389] )
else:
raise ValueError(f'Model name not supported. Should be one of {model_names}' )
# verify logits
assert logits.shape == expected_shape
if "finetuned" in model_name:
assert torch.allclose(logits[0, :3] , lowerCamelCase__ , atol=1E-4 )
else:
print("""Logits:""" , logits[0, :3, :3] )
assert torch.allclose(logits[0, :3, :3] , lowerCamelCase__ , atol=1E-4 )
print("""Logits ok!""" )
# verify loss, if applicable
if model_name == "videomae-base-short":
A_ : Optional[int] = outputs.loss
assert torch.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-4 )
print("""Loss ok!""" )
if pytorch_dump_folder_path is not None:
print(f'Saving model and image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(lowerCamelCase__ )
model.save_pretrained(lowerCamelCase__ )
if push_to_hub:
print("""Pushing to the hub...""" )
model.push_to_hub(lowerCamelCase__ , organization="""nielsr""" )
if __name__ == "__main__":
lowerCamelCase :Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--checkpoint_url''',
default='''https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&export=download&confirm=t&uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4''',
type=str,
help=(
'''URL of the original PyTorch checkpoint (on Google Drive) you\'d like to convert. Should be a direct'''
''' download link.'''
),
)
parser.add_argument(
'''--pytorch_dump_folder_path''',
default='''/Users/nielsrogge/Documents/VideoMAE/Test''',
type=str,
help='''Path to the output PyTorch model directory.''',
)
parser.add_argument('''--model_name''', default='''videomae-base''', type=str, help='''Name of the model.''')
parser.add_argument(
'''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.'''
)
lowerCamelCase :Union[str, Any] = parser.parse_args()
convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
__A = 6_5521
def __a ( lowerCAmelCase_ : str ) -> int:
'''simple docstring'''
UpperCAmelCase_= 1
UpperCAmelCase_= 0
for plain_chr in plain_text:
UpperCAmelCase_= (a + ord(lowerCAmelCase_ )) % MOD_ADLER
UpperCAmelCase_= (b + a) % MOD_ADLER
return (b << 16) | a
277
1
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 UpperCAmelCase_( a__ , a__ ):
"""simple docstring"""
try:
with open(_lowerCamelCase , '''rb''' ) as flax_state_f:
SCREAMING_SNAKE_CASE : Dict = from_bytes(_lowerCamelCase , flax_state_f.read() )
except UnpicklingError as e:
try:
with open(_lowerCamelCase ) 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(_lowerCamelCase , _lowerCamelCase )
def UpperCAmelCase_( 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
SCREAMING_SNAKE_CASE : Dict = flatten_dict(jax.tree_util.tree_map(lambda a__ : x.dtype == jnp.bfloataa , _lowerCamelCase ) ).values()
if any(_lowerCamelCase ):
# 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.''' )
SCREAMING_SNAKE_CASE : Optional[int] = jax.tree_util.tree_map(
lambda a__ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , _lowerCamelCase )
SCREAMING_SNAKE_CASE : Dict = ""
SCREAMING_SNAKE_CASE : str = flatten_dict(_lowerCamelCase , sep='''.''' )
SCREAMING_SNAKE_CASE : Optional[int] = pt_model.state_dict()
# keep track of unexpected & missing keys
SCREAMING_SNAKE_CASE : Any = []
SCREAMING_SNAKE_CASE : Optional[int] = set(pt_model_dict.keys() )
for flax_key_tuple, flax_tensor in flax_state_dict.items():
SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple.split('''.''' )
if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4:
SCREAMING_SNAKE_CASE : List[str] = flax_key_tuple_array[:-1] + ["weight"]
SCREAMING_SNAKE_CASE : Any = jnp.transpose(_lowerCamelCase , (3, 2, 0, 1) )
elif flax_key_tuple_array[-1] == "kernel":
SCREAMING_SNAKE_CASE : int = flax_key_tuple_array[:-1] + ["weight"]
SCREAMING_SNAKE_CASE : Dict = flax_tensor.T
elif flax_key_tuple_array[-1] == "scale":
SCREAMING_SNAKE_CASE : Optional[Any] = flax_key_tuple_array[:-1] + ["weight"]
if "time_embedding" not in flax_key_tuple_array:
for i, flax_key_tuple_string in enumerate(_lowerCamelCase ):
SCREAMING_SNAKE_CASE : str = (
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''' )
)
SCREAMING_SNAKE_CASE : List[Any] = ".".join(_lowerCamelCase )
if flax_key in pt_model_dict:
if flax_tensor.shape != pt_model_dict[flax_key].shape:
raise ValueError(
F"""Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected """
F"""to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.""" )
else:
# add weight to pytorch dict
SCREAMING_SNAKE_CASE : int = np.asarray(_lowerCamelCase ) if not isinstance(_lowerCamelCase , np.ndarray ) else flax_tensor
SCREAMING_SNAKE_CASE : List[str] = torch.from_numpy(_lowerCamelCase )
# remove from missing keys
missing_keys.remove(_lowerCamelCase )
else:
# weight is not expected by PyTorch model
unexpected_keys.append(_lowerCamelCase )
pt_model.load_state_dict(_lowerCamelCase )
# re-transform missing_keys to list
SCREAMING_SNAKE_CASE : str = list(_lowerCamelCase )
if len(_lowerCamelCase ) > 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(_lowerCamelCase ) > 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
313
"""simple docstring"""
import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from requests.exceptions import HTTPError
from transformers.utils import (
CONFIG_NAME,
FLAX_WEIGHTS_NAME,
TF2_WEIGHTS_NAME,
TRANSFORMERS_CACHE,
WEIGHTS_NAME,
cached_file,
get_file_from_repo,
has_file,
)
__A = '''hf-internal-testing/tiny-random-bert'''
__A = os.path.join(TRANSFORMERS_CACHE, '''models--hf-internal-testing--tiny-random-bert''')
__A = '''9b8c223d42b2188cb49d29af482996f9d0f3e5a6'''
class _snake_case ( unittest.TestCase ):
def lowerCamelCase__ ( self : Any ):
__lowerCamelCase : Dict = cached_file(UpperCAmelCase , UpperCAmelCase )
# Should have downloaded the file in here
self.assertTrue(os.path.isdir(UpperCAmelCase ) )
# Cache should contain at least those three subfolders:
for subfolder in ["blobs", "refs", "snapshots"]:
self.assertTrue(os.path.isdir(os.path.join(UpperCAmelCase , UpperCAmelCase ) ) )
with open(os.path.join(UpperCAmelCase , "refs" , "main" ) ) as f:
__lowerCamelCase : Dict = f.read()
self.assertEqual(UpperCAmelCase , os.path.join(UpperCAmelCase , "snapshots" , UpperCAmelCase , UpperCAmelCase ) )
self.assertTrue(os.path.isfile(UpperCAmelCase ) )
# File is cached at the same place the second time.
__lowerCamelCase : Tuple = cached_file(UpperCAmelCase , UpperCAmelCase )
self.assertEqual(UpperCAmelCase , UpperCAmelCase )
# Using a specific revision to test the full commit hash.
__lowerCamelCase : List[str] = cached_file(UpperCAmelCase , UpperCAmelCase , revision="9b8c223" )
self.assertEqual(UpperCAmelCase , os.path.join(UpperCAmelCase , "snapshots" , UpperCAmelCase , UpperCAmelCase ) )
def lowerCamelCase__ ( self : List[str] ):
with self.assertRaisesRegex(UpperCAmelCase , "is not a valid model identifier" ):
__lowerCamelCase : Optional[Any] = cached_file("tiny-random-bert" , UpperCAmelCase )
with self.assertRaisesRegex(UpperCAmelCase , "is not a valid git identifier" ):
__lowerCamelCase : Dict = cached_file(UpperCAmelCase , UpperCAmelCase , revision="aaaa" )
with self.assertRaisesRegex(UpperCAmelCase , "does not appear to have a file named" ):
__lowerCamelCase : List[Any] = cached_file(UpperCAmelCase , "conf" )
def lowerCamelCase__ ( self : str ):
with self.assertRaisesRegex(UpperCAmelCase , "does not appear to have a file named" ):
__lowerCamelCase : Any = cached_file(UpperCAmelCase , "conf" )
with open(os.path.join(UpperCAmelCase , "refs" , "main" ) ) as f:
__lowerCamelCase : List[str] = f.read()
self.assertTrue(os.path.isfile(os.path.join(UpperCAmelCase , ".no_exist" , UpperCAmelCase , "conf" ) ) )
__lowerCamelCase : List[str] = cached_file(UpperCAmelCase , "conf" , _raise_exceptions_for_missing_entries=UpperCAmelCase )
self.assertIsNone(UpperCAmelCase )
__lowerCamelCase : Optional[Any] = cached_file(UpperCAmelCase , "conf" , local_files_only=UpperCAmelCase , _raise_exceptions_for_missing_entries=UpperCAmelCase )
self.assertIsNone(UpperCAmelCase )
__lowerCamelCase : str = mock.Mock()
__lowerCamelCase : Union[str, Any] = 500
__lowerCamelCase : Tuple = {}
__lowerCamelCase : Dict = HTTPError
__lowerCamelCase : Any = {}
# Under the mock environment we get a 500 error when trying to reach the tokenizer.
with mock.patch("requests.Session.request" , return_value=UpperCAmelCase ) as mock_head:
__lowerCamelCase : Any = cached_file(UpperCAmelCase , "conf" , _raise_exceptions_for_connection_errors=UpperCAmelCase )
self.assertIsNone(UpperCAmelCase )
# This check we did call the fake head request
mock_head.assert_called()
def lowerCamelCase__ ( self : str ):
self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase ) )
self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase ) )
self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , UpperCAmelCase ) )
def lowerCamelCase__ ( self : Any ):
# `get_file_from_repo` returns None if the file does not exist
self.assertIsNone(get_file_from_repo("bert-base-cased" , "ahah.txt" ) )
# The function raises if the repository does not exist.
with self.assertRaisesRegex(UpperCAmelCase , "is not a valid model identifier" ):
get_file_from_repo("bert-base-case" , UpperCAmelCase )
# The function raises if the revision does not exist.
with self.assertRaisesRegex(UpperCAmelCase , "is not a valid git identifier" ):
get_file_from_repo("bert-base-cased" , UpperCAmelCase , revision="ahaha" )
__lowerCamelCase : str = get_file_from_repo("bert-base-cased" , UpperCAmelCase )
# The name is the cached name which is not very easy to test, so instead we load the content.
__lowerCamelCase : Tuple = json.loads(open(UpperCAmelCase , "r" ).read() )
self.assertEqual(config["hidden_size"] , 768 )
def lowerCamelCase__ ( self : Any ):
with tempfile.TemporaryDirectory() as tmp_dir:
__lowerCamelCase : Union[str, Any] = Path(UpperCAmelCase ) / "a.txt"
filename.touch()
self.assertEqual(get_file_from_repo(UpperCAmelCase , "a.txt" ) , str(UpperCAmelCase ) )
self.assertIsNone(get_file_from_repo(UpperCAmelCase , "b.txt" ) )
135
0
'''simple docstring'''
def _lowerCAmelCase ( _UpperCamelCase : Optional[Any] = 10_00 ) -> int:
"""simple docstring"""
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =1, 1
_SCREAMING_SNAKE_CASE =2
while True:
_SCREAMING_SNAKE_CASE =0
_SCREAMING_SNAKE_CASE =fa + fa
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =fa, f
index += 1
for _ in str(a__ ):
i += 1
if i == n:
break
return index
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
361
'''simple docstring'''
def _lowerCAmelCase ( _UpperCamelCase : float , _UpperCamelCase : float ) -> float:
"""simple docstring"""
if mass < 0:
raise ValueError('The mass of a body cannot be negative' )
return 0.5 * mass * abs(_UpperCamelCase ) * abs(_UpperCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
114
0
"""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 ( lowerCAmelCase__ : Dict[str, torch.Tensor] ) -> List[Any]:
__a = []
__a = []
__a = []
for rt in rc.restypes:
__a = 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] )
__a = {name: i for i, name in enumerate(snake_case__ )}
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 )
__a = torch.tensor(
snake_case__ , dtype=torch.intaa , device=protein['''aatype'''].device , )
__a = torch.tensor(
snake_case__ , dtype=torch.intaa , device=protein['''aatype'''].device , )
__a = torch.tensor(
snake_case__ , dtype=torch.floataa , device=protein['''aatype'''].device , )
__a = 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
__a = restype_atomaa_to_atomaa[protein_aatype]
__a = restype_atomaa_mask[protein_aatype]
__a = residx_atomaa_mask
__a = residx_atomaa_to_atomaa.long()
# create the gather indices for mapping back
__a = restype_atomaa_to_atomaa[protein_aatype]
__a = residx_atomaa_to_atomaa.long()
# create the corresponding mask
__a = torch.zeros([21, 37] , dtype=torch.floataa , device=protein['''aatype'''].device )
for restype, restype_letter in enumerate(rc.restypes ):
__a = rc.restype_atoa[restype_letter]
__a = rc.residue_atoms[restype_name]
for atom_name in atom_names:
__a = rc.atom_order[atom_name]
__a = 1
__a = restype_atomaa_mask[protein_aatype]
__a = residx_atomaa_mask
return protein
def lowercase ( lowerCAmelCase__ : Dict[str, torch.Tensor] ) -> Any:
__a = tree_map(lambda lowerCAmelCase__ : torch.tensor(snake_case__ , device=batch['''aatype'''].device ) , snake_case__ , np.ndarray )
__a = tensor_tree_map(lambda lowerCAmelCase__ : np.array(snake_case__ ) , make_atomaa_masks(snake_case__ ) )
return out
45
import os
def a ( ):
'''simple docstring'''
lowercase_ = os.path.join(os.path.dirname(snake_case__ ) , '''num.txt''' )
with open(snake_case__ ) as file_hand:
return str(sum(int(snake_case__ ) for line in file_hand ) )[:10]
if __name__ == "__main__":
print(solution())
from __future__ import annotations
from math import pi, sqrt
def _snake_case ( lowerCAmelCase : float , lowerCAmelCase : float ):
"""simple docstring"""
if inductance <= 0:
raise ValueError("Inductance cannot be 0 or negative" )
elif capacitance <= 0:
raise ValueError("Capacitance cannot be 0 or negative" )
else:
return (
"Resonant frequency",
float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ),
)
if __name__ == "__main__":
import doctest
doctest.testmod()
18
0
from __future__ import annotations
import numpy as np
def lowerCAmelCase_ ( snake_case_ ):
_A , _A : Any = np.shape(snake_case_ )
if rows != columns:
_A : Optional[Any] = (
"""'table' has to be of square shaped array but got a """
f'''{rows}x{columns} array:\n{table}'''
)
raise ValueError(snake_case_ )
_A : List[Any] = np.zeros((rows, columns) )
_A : Optional[int] = np.zeros((rows, columns) )
for i in range(snake_case_ ):
for j in range(snake_case_ ):
_A : Tuple = sum(lower[i][k] * upper[k][j] for k in range(snake_case_ ) )
if upper[j][j] == 0:
raise ArithmeticError("""No LU decomposition exists""" )
_A : Tuple = (table[i][j] - total) / upper[j][j]
_A : Optional[int] = 1
for j in range(snake_case_,snake_case_ ):
_A : Optional[int] = sum(lower[i][k] * upper[k][j] for k in range(snake_case_ ) )
_A : Optional[Any] = table[i][j] - total
return lower, upper
if __name__ == "__main__":
import doctest
doctest.testmod()
343
from __future__ import annotations
from collections.abc import Generator
import requests
from bsa import BeautifulSoup
_snake_case = "https://www.indeed.co.in/jobs?q=mobile+app+development&l="
def lowerCAmelCase_ ( snake_case_ = "mumbai" ):
_A : Optional[Any] = BeautifulSoup(requests.get(url + location ).content,"""html.parser""" )
# This attribute finds out all the specifics listed in a job
for job in soup.find_all("""div""",attrs={"""data-tn-component""": """organicJob"""} ):
_A : Tuple = job.find("""a""",attrs={"""data-tn-element""": """jobTitle"""} ).text.strip()
_A : Optional[int] = job.find("""span""",{"""class""": """company"""} ).text.strip()
yield job_title, company_name
if __name__ == "__main__":
for i, job in enumerate(fetch_jobs("Bangalore"), 1):
print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
343
1
import inspect
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_config_docstrings.py
lowerCAmelCase__ :str = '''src/transformers'''
# This is to make sure the transformers module imported is the one in the repo.
lowerCAmelCase__ :Dict = direct_transformers_import(PATH_TO_TRANSFORMERS)
lowerCAmelCase__ :Dict = transformers.models.auto.configuration_auto.CONFIG_MAPPING
# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
lowerCAmelCase__ :int = re.compile(R'''\[(.+?)\]\((https://huggingface\.co/.+?)\)''')
lowerCAmelCase__ :Optional[int] = {
'''DecisionTransformerConfig''',
'''EncoderDecoderConfig''',
'''MusicgenConfig''',
'''RagConfig''',
'''SpeechEncoderDecoderConfig''',
'''TimmBackboneConfig''',
'''VisionEncoderDecoderConfig''',
'''VisionTextDualEncoderConfig''',
'''LlamaConfig''',
}
def lowerCAmelCase__ ( a__: Optional[int] ) -> Optional[int]:
'''simple docstring'''
_UpperCAmelCase = None
# source code of `config_class`
_UpperCAmelCase = inspect.getsource(lowercase__ )
_UpperCAmelCase = _re_checkpoint.findall(lowercase__ )
# Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
# For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
for ckpt_name, ckpt_link in checkpoints:
# allow the link to end with `/`
if ckpt_link.endswith('/' ):
_UpperCAmelCase = ckpt_link[:-1]
# verify the checkpoint name corresponds to the checkpoint link
_UpperCAmelCase = F'''https://huggingface.co/{ckpt_name}'''
if ckpt_link == ckpt_link_from_name:
_UpperCAmelCase = ckpt_name
break
return checkpoint
def lowerCAmelCase__ ( ) -> str:
'''simple docstring'''
_UpperCAmelCase = []
for config_class in list(CONFIG_MAPPING.values() ):
# Skip deprecated models
if "models.deprecated" in config_class.__module__:
continue
_UpperCAmelCase = get_checkpoint_from_config_class(lowercase__ )
_UpperCAmelCase = config_class.__name__
if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
configs_without_checkpoint.append(lowercase__ )
if len(lowercase__ ) > 0:
_UpperCAmelCase = "\n".join(sorted(lowercase__ ) )
raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' )
if __name__ == "__main__":
check_config_docstrings_have_checkpoints()
"""simple docstring"""
import collections
import importlib.util
import os
import re
from pathlib import Path
__snake_case = '''src/transformers'''
# Matches is_xxx_available()
__snake_case = re.compile(r'''is\_([a-z_]*)_available()''')
# Catches a one-line _import_struct = {xxx}
__snake_case = re.compile(r'''^_import_structure\s+=\s+\{([^\}]+)\}''')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
__snake_case = re.compile(r'''\s+"\S*":\s+\[([^\]]*)\]''')
# Catches a line if not is_foo_available
__snake_case = re.compile(r'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''')
# Catches a line _import_struct["bla"].append("foo")
__snake_case = re.compile(r'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''')
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
__snake_case = re.compile(r'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''')
# Catches a line with an object between quotes and a comma: "MyModel",
__snake_case = re.compile('''^\s+"([^"]+)",''')
# Catches a line with objects between brackets only: ["foo", "bar"],
__snake_case = re.compile('''^\s+\[([^\]]+)\]''')
# Catches a line with from foo import bar, bla, boo
__snake_case = re.compile(r'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''')
# Catches a line with try:
__snake_case = re.compile(r'''^\s*try:''')
# Catches a line with else:
__snake_case = re.compile(r'''^\s*else:''')
def A_ ( _lowerCAmelCase : Optional[int] ):
"""simple docstring"""
if _re_test_backend.search(_lowerCAmelCase ) is None:
return None
_a = [b[0] for b in _re_backend.findall(_lowerCAmelCase )]
backends.sort()
return "_and_".join(_lowerCAmelCase )
def A_ ( _lowerCAmelCase : Tuple ):
"""simple docstring"""
with open(_lowerCAmelCase, '''r''', encoding='''utf-8''', newline='''\n''' ) as f:
_a = f.readlines()
_a = 0
while line_index < len(_lowerCAmelCase ) and not lines[line_index].startswith('''_import_structure = {''' ):
line_index += 1
# If this is a traditional init, just return.
if line_index >= len(_lowerCAmelCase ):
return None
# First grab the objects without a specific backend in _import_structure
_a = []
while not lines[line_index].startswith('''if TYPE_CHECKING''' ) and find_backend(lines[line_index] ) is None:
_a = lines[line_index]
# If we have everything on a single line, let's deal with it.
if _re_one_line_import_struct.search(_lowerCAmelCase ):
_a = _re_one_line_import_struct.search(_lowerCAmelCase ).groups()[0]
_a = re.findall('''\[([^\]]+)\]''', _lowerCAmelCase )
for imp in imports:
objects.extend([obj[1:-1] for obj in imp.split(''', ''' )] )
line_index += 1
continue
_a = _re_import_struct_key_value.search(_lowerCAmelCase )
if single_line_import_search is not None:
_a = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', ''' ) if len(_lowerCAmelCase ) > 0]
objects.extend(_lowerCAmelCase )
elif line.startswith(''' ''' * 8 + '''"''' ):
objects.append(line[9:-3] )
line_index += 1
_a = {'''none''': objects}
# Let's continue with backend-specific objects in _import_structure
while not lines[line_index].startswith('''if TYPE_CHECKING''' ):
# If the line is an if not is_backend_available, we grab all objects associated.
_a = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
_a = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
_a = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 4 ):
_a = lines[line_index]
if _re_import_struct_add_one.search(_lowerCAmelCase ) is not None:
objects.append(_re_import_struct_add_one.search(_lowerCAmelCase ).groups()[0] )
elif _re_import_struct_add_many.search(_lowerCAmelCase ) is not None:
_a = _re_import_struct_add_many.search(_lowerCAmelCase ).groups()[0].split(''', ''' )
_a = [obj[1:-1] for obj in imports if len(_lowerCAmelCase ) > 0]
objects.extend(_lowerCAmelCase )
elif _re_between_brackets.search(_lowerCAmelCase ) is not None:
_a = _re_between_brackets.search(_lowerCAmelCase ).groups()[0].split(''', ''' )
_a = [obj[1:-1] for obj in imports if len(_lowerCAmelCase ) > 0]
objects.extend(_lowerCAmelCase )
elif _re_quote_object.search(_lowerCAmelCase ) is not None:
objects.append(_re_quote_object.search(_lowerCAmelCase ).groups()[0] )
elif line.startswith(''' ''' * 8 + '''"''' ):
objects.append(line[9:-3] )
elif line.startswith(''' ''' * 12 + '''"''' ):
objects.append(line[13:-3] )
line_index += 1
_a = objects
else:
line_index += 1
# At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
_a = []
while (
line_index < len(_lowerCAmelCase )
and find_backend(lines[line_index] ) is None
and not lines[line_index].startswith('''else''' )
):
_a = lines[line_index]
_a = _re_import.search(_lowerCAmelCase )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(''', ''' ) )
elif line.startswith(''' ''' * 8 ):
objects.append(line[8:-2] )
line_index += 1
_a = {'''none''': objects}
# Let's continue with backend-specific objects
while line_index < len(_lowerCAmelCase ):
# If the line is an if is_backend_available, we grab all objects associated.
_a = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
_a = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
_a = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 8 ):
_a = lines[line_index]
_a = _re_import.search(_lowerCAmelCase )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(''', ''' ) )
elif line.startswith(''' ''' * 12 ):
objects.append(line[12:-2] )
line_index += 1
_a = objects
else:
line_index += 1
return import_dict_objects, type_hint_objects
def A_ ( _lowerCAmelCase : Optional[int], _lowerCAmelCase : Union[str, Any] ):
"""simple docstring"""
def find_duplicates(_lowerCAmelCase : Dict ):
return [k for k, v in collections.Counter(_lowerCAmelCase ).items() if v > 1]
if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ):
return ["Both sides of the init do not have the same backends!"]
_a = []
for key in import_dict_objects.keys():
_a = find_duplicates(import_dict_objects[key] )
if duplicate_imports:
errors.append(f'Duplicate _import_structure definitions for: {duplicate_imports}' )
_a = find_duplicates(type_hint_objects[key] )
if duplicate_type_hints:
errors.append(f'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' )
if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ):
_a = '''base imports''' if key == '''none''' else f'{key} backend'
errors.append(f'Differences for {name}:' )
for a in type_hint_objects[key]:
if a not in import_dict_objects[key]:
errors.append(f' {a} in TYPE_HINT but not in _import_structure.' )
for a in import_dict_objects[key]:
if a not in type_hint_objects[key]:
errors.append(f' {a} in _import_structure but not in TYPE_HINT.' )
return errors
def A_ ( ):
"""simple docstring"""
_a = []
for root, _, files in os.walk(_lowerCAmelCase ):
if "__init__.py" in files:
_a = os.path.join(_lowerCAmelCase, '''__init__.py''' )
_a = parse_init(_lowerCAmelCase )
if objects is not None:
_a = analyze_results(*_lowerCAmelCase )
if len(_lowerCAmelCase ) > 0:
_a = f'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}'
failures.append('''\n'''.join(_lowerCAmelCase ) )
if len(_lowerCAmelCase ) > 0:
raise ValueError('''\n\n'''.join(_lowerCAmelCase ) )
def A_ ( ):
"""simple docstring"""
_a = []
for path, directories, files in os.walk(_lowerCAmelCase ):
for folder in directories:
# Ignore private modules
if folder.startswith('''_''' ):
directories.remove(_lowerCAmelCase )
continue
# Ignore leftovers from branches (empty folders apart from pycache)
if len(list((Path(_lowerCAmelCase ) / folder).glob('''*.py''' ) ) ) == 0:
continue
_a = str((Path(_lowerCAmelCase ) / folder).relative_to(_lowerCAmelCase ) )
_a = short_path.replace(os.path.sep, '''.''' )
submodules.append(_lowerCAmelCase )
for fname in files:
if fname == "__init__.py":
continue
_a = str((Path(_lowerCAmelCase ) / fname).relative_to(_lowerCAmelCase ) )
_a = short_path.replace('''.py''', '''''' ).replace(os.path.sep, '''.''' )
if len(submodule.split('''.''' ) ) == 1:
submodules.append(_lowerCAmelCase )
return submodules
__snake_case = [
'''convert_pytorch_checkpoint_to_tf2''',
'''modeling_flax_pytorch_utils''',
]
def A_ ( ):
"""simple docstring"""
_a = importlib.util.spec_from_file_location(
'''transformers''', os.path.join(_lowerCAmelCase, '''__init__.py''' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], )
_a = spec.loader.load_module()
_a = [
module
for module in get_transformers_submodules()
if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()
]
if len(_lowerCAmelCase ) > 0:
_a = '''\n'''.join(f'- {module}' for module in module_not_registered )
raise ValueError(
'''The following submodules are not properly registered in the main init of Transformers:\n'''
f'{list_of_modules}\n'
'''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.''' )
if __name__ == "__main__":
check_all_inits()
check_submodules()
'''simple docstring'''
import sacrebleu as scb
from packaging import version
from sacrebleu import TER
import datasets
_lowercase : List[str] = "\\n@inproceedings{snover-etal-2006-study,\n title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n author = \"Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John\",\n booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n month = aug # \" 8-12\",\n year = \"2006\",\n address = \"Cambridge, Massachusetts, USA\",\n publisher = \"Association for Machine Translation in the Americas\",\n url = \"https://aclanthology.org/2006.amta-papers.25\",\n pages = \"223--231\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n"
_lowercase : Tuple = "\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n"
_lowercase : Optional[int] = "\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n 'score' (float): TER score (num_edits / sum_ref_lengths * 100)\n 'num_edits' (int): The cumulative number of edits\n 'ref_length' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}\n\n Example 2:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}\n\n Example 3:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}\n\n Example 4:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}\n\n Example 5:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)
class __magic_name__ ( datasets.Metric):
def SCREAMING_SNAKE_CASE_ ( self : int ):
if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ):
raise ImportWarning(
"""To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
"""You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" )
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , homepage="""http://www.cs.umd.edu/~snover/tercom/""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Value("""string""" , id="""sequence""" ),
"""references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ),
} ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""] , reference_urls=[
"""https://github.com/jhclark/tercom""",
] , )
def SCREAMING_SNAKE_CASE_ ( self : Any , lowercase_ : Any , lowercase_ : Tuple , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = False , lowercase_ : bool = False , ):
lowercase_ : int = len(references[0] )
if any(len(lowercase_ ) != references_per_prediction for refs in references ):
raise ValueError("""Sacrebleu requires the same number of references for each prediction""" )
lowercase_ : Optional[int] = [[refs[i] for refs in references] for i in range(lowercase_ )]
lowercase_ : List[str] = TER(
normalized=lowercase_ , no_punct=lowercase_ , asian_support=lowercase_ , case_sensitive=lowercase_ , )
lowercase_ : List[str] = sb_ter.corpus_score(lowercase_ , lowercase_ )
return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
239
1
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import sys
import warnings
from os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
a__ = abspath(join(dirname(dirname(__file__)), '''src'''))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='''ignore''', category=FutureWarning)
def __UpperCAmelCase ( __a : Optional[int] ) -> str:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_addoption_shared
pytest_addoption_shared(__a )
def __UpperCAmelCase ( __a : Optional[int] ) -> str:
"""simple docstring"""
from diffusers.utils.testing_utils import pytest_terminal_summary_main
_a : Union[str, Any] = terminalreporter.config.getoption('''--make-reports''' )
if make_reports:
pytest_terminal_summary_main(__a ,id=__a )
355
from typing import Dict
import numpy as np
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException
if is_tf_available():
import tensorflow as tf
from ..tf_utils import stable_softmax
if is_torch_available():
import torch
a__ = logging.get_logger(__name__)
@add_end_docstrings(
__lowercase , r"\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n " , )
class UpperCAmelCase_ ( __lowercase ):
"""simple docstring"""
def __lowercase ( self , _a ) -> np.ndarray:
if self.framework == "tf":
_a : List[str] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
elif self.framework == "pt":
_a : Tuple = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_a )
else:
raise ValueError('''Unsupported framework''' )
return masked_index
def __lowercase ( self , _a ) -> np.ndarray:
_a : int = self.get_masked_index(_a )
_a : Tuple = np.prod(masked_index.shape )
if numel < 1:
raise PipelineException(
'''fill-mask''' , self.model.base_model_prefix , F"""No mask_token ({self.tokenizer.mask_token}) found on the input""" , )
def __lowercase ( self , _a ) -> Optional[int]:
if isinstance(_a , _a ):
for model_input in model_inputs:
self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0] )
else:
for input_ids in model_inputs["input_ids"]:
self._ensure_exactly_one_mask_token(_a )
def __lowercase ( self , _a , _a=None , **_a ) -> Dict[str, GenericTensor]:
if return_tensors is None:
_a : Union[str, Any] = self.framework
_a : str = self.tokenizer(_a , return_tensors=_a )
self.ensure_exactly_one_mask_token(_a )
return model_inputs
def __lowercase ( self , _a ) -> Optional[Any]:
_a : List[str] = self.model(**_a )
_a : Any = model_inputs['''input_ids''']
return model_outputs
def __lowercase ( self , _a , _a=5 , _a=None ) -> str:
# Cap top_k if there are targets
if target_ids is not None and target_ids.shape[0] < top_k:
_a : List[Any] = target_ids.shape[0]
_a : Any = model_outputs['''input_ids'''][0]
_a : List[str] = model_outputs['''logits''']
if self.framework == "tf":
_a : Tuple = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]
_a : List[str] = outputs.numpy()
_a : Dict = outputs[0, masked_index, :]
_a : str = stable_softmax(_a , axis=-1 )
if target_ids is not None:
_a : Any = tf.gather_nd(tf.squeeze(_a , 0 ) , target_ids.reshape(-1 , 1 ) )
_a : Union[str, Any] = tf.expand_dims(_a , 0 )
_a : Optional[int] = tf.math.top_k(_a , k=_a )
_a , _a : Optional[Any] = topk.values.numpy(), topk.indices.numpy()
else:
_a : Optional[Any] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_a ).squeeze(-1 )
# Fill mask pipeline supports only one ${mask_token} per sample
_a : List[str] = outputs[0, masked_index, :]
_a : List[Any] = logits.softmax(dim=-1 )
if target_ids is not None:
_a : List[Any] = probs[..., target_ids]
_a , _a : Optional[Any] = probs.topk(_a )
_a : Dict = []
_a : List[Any] = values.shape[0] == 1
for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ):
_a : Optional[Any] = []
for v, p in zip(_values , _predictions ):
# Copy is important since we're going to modify this array in place
_a : Optional[int] = input_ids.numpy().copy()
if target_ids is not None:
_a : Tuple = target_ids[p].tolist()
_a : List[str] = p
# Filter padding out:
_a : List[Any] = tokens[np.where(tokens != self.tokenizer.pad_token_id )]
# Originally we skip special tokens to give readable output.
# For multi masks though, the other [MASK] would be removed otherwise
# making the output look odd, so we add them back
_a : List[str] = self.tokenizer.decode(_a , skip_special_tokens=_a )
_a : List[Any] = {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p] ), '''sequence''': sequence}
row.append(_a )
result.append(_a )
if single_mask:
return result[0]
return result
def __lowercase ( self , _a , _a=None ) -> Dict:
if isinstance(_a , _a ):
_a : Tuple = [targets]
try:
_a : int = self.tokenizer.get_vocab()
except Exception:
_a : Any = {}
_a : List[Any] = []
for target in targets:
_a : List[Any] = vocab.get(_a , _a )
if id_ is None:
_a : Tuple = self.tokenizer(
_a , add_special_tokens=_a , return_attention_mask=_a , return_token_type_ids=_a , max_length=1 , truncation=_a , )['''input_ids''']
if len(_a ) == 0:
logger.warning(
F"""The specified target token `{target}` does not exist in the model vocabulary. """
'''We cannot replace it with anything meaningful, ignoring it''' )
continue
_a : Tuple = input_ids[0]
# XXX: If users encounter this pass
# it becomes pretty slow, so let's make sure
# The warning enables them to fix the input to
# get faster performance.
logger.warning(
F"""The specified target token `{target}` does not exist in the model vocabulary. """
F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" )
target_ids.append(id_ )
_a : List[str] = list(set(_a ) )
if len(_a ) == 0:
raise ValueError('''At least one target must be provided when passed.''' )
_a : int = np.array(_a )
return target_ids
def __lowercase ( self , _a=None , _a=None ) -> Tuple:
_a : str = {}
if targets is not None:
_a : List[Any] = self.get_target_ids(_a , _a )
_a : Optional[Any] = target_ids
if top_k is not None:
_a : Union[str, Any] = top_k
if self.tokenizer.mask_token_id is None:
raise PipelineException(
'''fill-mask''' , self.model.base_model_prefix , '''The tokenizer does not define a `mask_token`.''' )
return {}, {}, postprocess_params
def __call__( self , _a , *_a , **_a ) -> int:
_a : Optional[Any] = super().__call__(_a , **_a )
if isinstance(_a , _a ) and len(_a ) == 1:
return outputs[0]
return outputs
15
0
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
UpperCAmelCase__ : Dict = logging.get_logger(__name__)
UpperCAmelCase__ : Optional[int] = '▁'
UpperCAmelCase__ : List[Any] = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'}
UpperCAmelCase__ : Any = {
'vocab_file': {
'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model',
},
'monolingual_vocab_file': {
'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt',
},
}
UpperCAmelCase__ : Tuple = {'vinai/bartpho-syllable': 1024}
class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
__UpperCamelCase : Optional[int] = VOCAB_FILES_NAMES
__UpperCamelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP
__UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__UpperCamelCase : List[Any] = ['''input_ids''', '''attention_mask''']
def __init__( self : Dict , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int]="<s>" , lowerCAmelCase_ : Tuple="</s>" , lowerCAmelCase_ : Union[str, Any]="</s>" , lowerCAmelCase_ : List[str]="<s>" , lowerCAmelCase_ : Optional[int]="<unk>" , lowerCAmelCase_ : Optional[int]="<pad>" , lowerCAmelCase_ : Optional[int]="<mask>" , lowerCAmelCase_ : Optional[Dict[str, Any]] = None , **lowerCAmelCase_ : Optional[Any] , ):
"""simple docstring"""
# Mask token behave like a normal word, i.e. include the space before it
_A: Union[str, Any] = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else mask_token
_A: Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , mask_token=lowerCAmelCase_ , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase_ , )
_A: int = vocab_file
_A: Optional[Any] = monolingual_vocab_file
_A: List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(str(lowerCAmelCase_ ) )
# Load the reduced vocab
# Keep order of special tokens for backward compatibility
_A: Dict = {}
_A: Dict = 0
for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
if str(lowerCAmelCase_ ) not in self.fairseq_tokens_to_ids:
_A: str = cnt
cnt += 1
with open(lowerCAmelCase_ , '''r''' , encoding='''utf-8''' ) as f:
for line in f.readlines():
_A: Optional[Any] = line.strip().split()[0]
_A: Union[str, Any] = len(self.fairseq_tokens_to_ids )
if str(lowerCAmelCase_ ) not in self.fairseq_tokens_to_ids:
_A: Optional[int] = len(self.fairseq_tokens_to_ids )
_A: Optional[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
def __getstate__( self : List[str] ):
"""simple docstring"""
_A: Optional[int] = self.__dict__.copy()
_A: str = None
_A: List[str] = self.sp_model.serialized_model_proto()
return state
def __setstate__( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] ):
"""simple docstring"""
_A: Dict = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs''' ):
_A: str = {}
_A: str = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
def __magic_name__ ( self : str , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ):
"""simple docstring"""
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
_A: Union[str, Any] = [self.cls_token_id]
_A: int = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None , lowerCAmelCase_ : bool = False ):
"""simple docstring"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=lowerCAmelCase_ , token_ids_a=lowerCAmelCase_ , already_has_special_tokens=lowerCAmelCase_ )
if token_ids_a is None:
return [1] + ([0] * len(lowerCAmelCase_ )) + [1]
return [1] + ([0] * len(lowerCAmelCase_ )) + [1, 1] + ([0] * len(lowerCAmelCase_ )) + [1]
def __magic_name__ ( self : Tuple , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ):
"""simple docstring"""
_A: Optional[int] = [self.sep_token_id]
_A: Union[str, Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
@property
def __magic_name__ ( self : Union[str, Any] ):
"""simple docstring"""
return len(self.fairseq_ids_to_tokens )
def __magic_name__ ( self : Tuple ):
"""simple docstring"""
_A: Any = {self.convert_ids_to_tokens(lowerCAmelCase_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __magic_name__ ( self : List[str] , lowerCAmelCase_ : str ):
"""simple docstring"""
return self.sp_model.encode(lowerCAmelCase_ , out_type=lowerCAmelCase_ )
def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : int ):
"""simple docstring"""
if token in self.fairseq_tokens_to_ids:
return self.fairseq_tokens_to_ids[token]
else:
return self.unk_token_id
def __magic_name__ ( self : int , lowerCAmelCase_ : Any ):
"""simple docstring"""
return self.fairseq_ids_to_tokens[index]
def __magic_name__ ( self : int , lowerCAmelCase_ : Optional[int] ):
"""simple docstring"""
_A: Optional[Any] = ''''''.join(lowerCAmelCase_ ).replace(lowerCAmelCase_ , ''' ''' ).strip()
return out_string
def __magic_name__ ( self : Tuple , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(lowerCAmelCase_ ):
logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
return
_A: Any = os.path.join(
lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
_A: Optional[int] = os.path.join(
lowerCAmelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''monolingual_vocab_file'''] , )
if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase_ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , lowerCAmelCase_ )
elif not os.path.isfile(self.vocab_file ):
with open(lowerCAmelCase_ , '''wb''' ) as fi:
_A: Optional[int] = self.sp_model.serialized_model_proto()
fi.write(lowerCAmelCase_ )
if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath(
lowerCAmelCase_ ) and os.path.isfile(self.monolingual_vocab_file ):
copyfile(self.monolingual_vocab_file , lowerCAmelCase_ )
elif not os.path.isfile(self.monolingual_vocab_file ):
with open(lowerCAmelCase_ , '''w''' , encoding='''utf-8''' ) as fp:
for token in self.fairseq_tokens_to_ids:
if token not in self.all_special_tokens:
fp.write(F"""{str(lowerCAmelCase_ )} \n""" )
return out_vocab_file, out_monolingual_vocab_file
121
from typing import List, Optional, Union
import numpy as np
import PIL
import torch
from PIL import Image
from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
is_accelerate_available,
is_accelerate_version,
logging,
randn_tensor,
replace_example_docstring,
)
UpperCAmelCase__ : Optional[int] = logging.get_logger(__name__) # pylint: disable=invalid-name
UpperCAmelCase__ : Dict = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "A red cartoon frog, 4k"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n ... )\n >>> pipe.to("cuda")\n\n >>> init_image = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/frog.png"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save("red_frog.png")\n ```\n'
def lowerCamelCase__ ( a , a , a=8 ) -> List[Any]:
_A: int = height // scale_factor**2
if height % scale_factor**2 != 0:
new_height += 1
_A: str = width // scale_factor**2
if width % scale_factor**2 != 0:
new_width += 1
return new_height * scale_factor, new_width * scale_factor
def lowerCamelCase__ ( a , a=5_12 , a=5_12 ) -> Dict:
_A: Union[str, Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 )
_A: Tuple = np.array(pil_image.convert('''RGB''' ) )
_A: List[str] = arr.astype(np.floataa ) / 127.5 - 1
_A: Tuple = np.transpose(a , [2, 0, 1] )
_A: Any = torch.from_numpy(a ).unsqueeze(0 )
return image
class UpperCAmelCase ( SCREAMING_SNAKE_CASE__ ):
'''simple docstring'''
def __init__( self : int , lowerCAmelCase_ : UNetaDConditionModel , lowerCAmelCase_ : DDPMScheduler , lowerCAmelCase_ : VQModel , ):
"""simple docstring"""
super().__init__()
self.register_modules(
unet=lowerCAmelCase_ , scheduler=lowerCAmelCase_ , movq=lowerCAmelCase_ , )
_A: List[Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1)
def __magic_name__ ( self : List[str] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Union[str, Any] ):
"""simple docstring"""
# get the original timestep using init_timestep
_A: Union[str, Any] = min(int(num_inference_steps * strength ) , lowerCAmelCase_ )
_A: str = max(num_inference_steps - init_timestep , 0 )
_A: str = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def __magic_name__ ( self : List[str] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : str , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Optional[int]=None ):
"""simple docstring"""
if not isinstance(lowerCAmelCase_ , (torch.Tensor, PIL.Image.Image, list) ):
raise ValueError(
F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowerCAmelCase_ )}""" )
_A: Optional[int] = image.to(device=lowerCAmelCase_ , dtype=lowerCAmelCase_ )
_A: Union[str, Any] = batch_size * num_images_per_prompt
if image.shape[1] == 4:
_A: Optional[int] = image
else:
if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and len(lowerCAmelCase_ ) != batch_size:
raise ValueError(
F"""You have passed a list of generators of length {len(lowerCAmelCase_ )}, but requested an effective batch"""
F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )
elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
_A: List[Any] = [
self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(lowerCAmelCase_ )
]
_A: Optional[Any] = torch.cat(lowerCAmelCase_ , dim=0 )
else:
_A: Optional[int] = self.movq.encode(lowerCAmelCase_ ).latent_dist.sample(lowerCAmelCase_ )
_A: int = self.movq.config.scaling_factor * init_latents
_A: Optional[Any] = torch.cat([init_latents] , dim=0 )
_A: Any = init_latents.shape
_A: Optional[Any] = randn_tensor(lowerCAmelCase_ , generator=lowerCAmelCase_ , device=lowerCAmelCase_ , dtype=lowerCAmelCase_ )
# get latents
_A: Union[str, Any] = self.scheduler.add_noise(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
_A: List[str] = init_latents
return latents
def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : Optional[int]=0 ):
"""simple docstring"""
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError('''Please install accelerate via `pip install accelerate`''' )
_A: Any = torch.device(F"""cuda:{gpu_id}""" )
_A: int = [
self.unet,
self.movq,
]
for cpu_offloaded_model in models:
if cpu_offloaded_model is not None:
cpu_offload(lowerCAmelCase_ , lowerCAmelCase_ )
def __magic_name__ ( self : Any , lowerCAmelCase_ : Any=0 ):
"""simple docstring"""
if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ):
from accelerate import cpu_offload_with_hook
else:
raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' )
_A: Any = torch.device(F"""cuda:{gpu_id}""" )
if self.device.type != "cpu":
self.to('''cpu''' , silence_dtype_warnings=lowerCAmelCase_ )
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
_A: int = None
for cpu_offloaded_model in [self.unet, self.movq]:
_A , _A: List[Any] = cpu_offload_with_hook(lowerCAmelCase_ , lowerCAmelCase_ , prev_module_hook=lowerCAmelCase_ )
# We'll offload the last model manually.
_A: Tuple = hook
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def __magic_name__ ( self : List[Any] ):
"""simple docstring"""
if not hasattr(self.unet , '''_hf_hook''' ):
return self.device
for module in self.unet.modules():
if (
hasattr(lowerCAmelCase_ , '''_hf_hook''' )
and hasattr(module._hf_hook , '''execution_device''' )
and module._hf_hook.execution_device is not None
):
return torch.device(module._hf_hook.execution_device )
return self.device
@torch.no_grad()
@replace_example_docstring(lowerCAmelCase_ )
def __call__( self : Optional[Any] , lowerCAmelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] , lowerCAmelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCAmelCase_ : int = 5_1_2 , lowerCAmelCase_ : int = 5_1_2 , lowerCAmelCase_ : int = 1_0_0 , lowerCAmelCase_ : float = 4.0 , lowerCAmelCase_ : float = 0.3 , lowerCAmelCase_ : int = 1 , lowerCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCAmelCase_ : Optional[str] = "pil" , lowerCAmelCase_ : bool = True , ):
"""simple docstring"""
_A: Any = self._execution_device
_A: Any = guidance_scale > 1.0
if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
_A: Any = torch.cat(lowerCAmelCase_ , dim=0 )
_A: int = image_embeds.shape[0]
if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
_A: Dict = torch.cat(lowerCAmelCase_ , dim=0 )
if do_classifier_free_guidance:
_A: Any = image_embeds.repeat_interleave(lowerCAmelCase_ , dim=0 )
_A: str = negative_image_embeds.repeat_interleave(lowerCAmelCase_ , dim=0 )
_A: Dict = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCAmelCase_ )
if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ):
_A: List[str] = [image]
if not all(isinstance(lowerCAmelCase_ , (PIL.Image.Image, torch.Tensor) ) for i in image ):
raise ValueError(
F"""Input is in incorrect format: {[type(lowerCAmelCase_ ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" )
_A: List[str] = torch.cat([prepare_image(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) for i in image] , dim=0 )
_A: Tuple = image.to(dtype=image_embeds.dtype , device=lowerCAmelCase_ )
_A: Optional[Any] = self.movq.encode(lowerCAmelCase_ )['''latents''']
_A: Optional[int] = latents.repeat_interleave(lowerCAmelCase_ , dim=0 )
self.scheduler.set_timesteps(lowerCAmelCase_ , device=lowerCAmelCase_ )
_A , _A: List[Any] = self.get_timesteps(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
_A: Dict = timesteps[:1].repeat(batch_size * num_images_per_prompt )
_A , _A: Optional[int] = downscale_height_and_width(lowerCAmelCase_ , lowerCAmelCase_ , self.movq_scale_factor )
_A: Any = self.prepare_latents(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , image_embeds.dtype , lowerCAmelCase_ , lowerCAmelCase_ )
for i, t in enumerate(self.progress_bar(lowerCAmelCase_ ) ):
# expand the latents if we are doing classifier free guidance
_A: Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
_A: str = {'''image_embeds''': image_embeds}
_A: Optional[int] = self.unet(
sample=lowerCAmelCase_ , timestep=lowerCAmelCase_ , encoder_hidden_states=lowerCAmelCase_ , added_cond_kwargs=lowerCAmelCase_ , return_dict=lowerCAmelCase_ , )[0]
if do_classifier_free_guidance:
_A , _A: str = noise_pred.split(latents.shape[1] , dim=1 )
_A , _A: int = noise_pred.chunk(2 )
_A , _A: int = variance_pred.chunk(2 )
_A: Dict = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
_A: List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 )
if not (
hasattr(self.scheduler.config , '''variance_type''' )
and self.scheduler.config.variance_type in ["learned", "learned_range"]
):
_A , _A: Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 )
# compute the previous noisy sample x_t -> x_t-1
_A: Any = self.scheduler.step(
lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , generator=lowerCAmelCase_ , )[0]
# post-processing
_A: Tuple = self.movq.decode(lowerCAmelCase_ , force_not_quantize=lowerCAmelCase_ )['''sample''']
if output_type not in ["pt", "np", "pil"]:
raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" )
if output_type in ["np", "pil"]:
_A: int = image * 0.5 + 0.5
_A: Any = image.clamp(0 , 1 )
_A: Any = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if output_type == "pil":
_A: Union[str, Any] = self.numpy_to_pil(lowerCAmelCase_ )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=lowerCAmelCase_ )
121
1
import os
from collections.abc import Iterator
def snake_case( __magic_name__ = "." ) -> Iterator[str]:
'''simple docstring'''
for dir_path, dir_names, filenames in os.walk(__magic_name__ ):
lowercase : Tuple = [d for d in dir_names if d != '''scripts''' and d[0] not in '''._''']
for filename in filenames:
if filename == "__init__.py":
continue
if os.path.splitext(__magic_name__ )[1] in (".py", ".ipynb"):
yield os.path.join(__magic_name__ , __magic_name__ ).lstrip('''./''' )
def snake_case( __magic_name__ ) -> Dict:
'''simple docstring'''
return F"""{i * ' '}*""" if i else "\n##"
def snake_case( __magic_name__ , __magic_name__ ) -> str:
'''simple docstring'''
lowercase : Dict = old_path.split(os.sep )
for i, new_part in enumerate(new_path.split(os.sep ) ):
if (i + 1 > len(__magic_name__ ) or old_parts[i] != new_part) and new_part:
print(F"""{md_prefix(__magic_name__ )} {new_part.replace('_' , ' ' ).title()}""" )
return new_path
def snake_case( __magic_name__ = "." ) -> None:
'''simple docstring'''
lowercase : str = ''''''
for filepath in sorted(good_file_paths(__magic_name__ ) ):
lowercase , lowercase : Optional[int] = os.path.split(__magic_name__ )
if filepath != old_path:
lowercase : str = print_path(__magic_name__ , __magic_name__ )
lowercase : Optional[int] = (filepath.count(os.sep ) + 1) if filepath else 0
lowercase : Optional[Any] = F"""{filepath}/{filename}""".replace(''' ''' , '''%20''' )
lowercase : List[str] = os.path.splitext(filename.replace('''_''' , ''' ''' ).title() )[0]
print(F"""{md_prefix(__magic_name__ )} [{filename}]({url})""" )
if __name__ == "__main__":
print_directory_md('.')
116
from sklearn.metrics import mean_squared_error
import datasets
lowerCAmelCase_ = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n'
lowerCAmelCase_ = '\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n'
lowerCAmelCase_ = '\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n "raw_values" : Returns a full set of errors in case of multioutput input.\n\n "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric("mse")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {\'mse\': 0.6123724356957945}\n\n If you\'re using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric("mse", "multilist")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mse\': array([0.41666667, 1. ])}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _A ( datasets.Metric ):
def __a ( self : List[Any] ) -> Optional[Any]:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[
'''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html'''
] , )
def __a ( self : List[Any] ) -> int:
"""simple docstring"""
if self.config_name == "multilist":
return {
"predictions": datasets.Sequence(datasets.Value('''float''' ) ),
"references": datasets.Sequence(datasets.Value('''float''' ) ),
}
else:
return {
"predictions": datasets.Value('''float''' ),
"references": datasets.Value('''float''' ),
}
def __a ( self : Any , _A : Dict , _A : Any , _A : Any=None , _A : Any="uniform_average" , _A : Optional[Any]=True ) -> Dict:
"""simple docstring"""
lowercase : Any = mean_squared_error(
_A , _A , sample_weight=_A , multioutput=_A , squared=_A )
return {"mse": mse}
116
1
'''simple docstring'''
from __future__ import annotations
import numpy as np
from numpy import floataa
from numpy.typing import NDArray
def UpperCAmelCase__ ( UpperCAmelCase_ : NDArray[floataa] , UpperCAmelCase_ : NDArray[floataa] , UpperCAmelCase_ : list[int] , UpperCAmelCase_ : int , ) -> list[float]:
__lowerCamelCase , __lowerCamelCase : Optional[int] = coefficient_matrix.shape
__lowerCamelCase , __lowerCamelCase : Dict = constant_matrix.shape
if rowsa != colsa:
__lowerCamelCase : Union[str, Any] = F'Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}'
raise ValueError(UpperCAmelCase_ )
if colsa != 1:
__lowerCamelCase : int = F'Constant matrix must be nx1 but received {rowsa}x{colsa}'
raise ValueError(UpperCAmelCase_ )
if rowsa != rowsa:
__lowerCamelCase : Tuple = (
'Coefficient and constant matrices dimensions must be nxn and nx1 but '
F'received {rowsa}x{colsa} and {rowsa}x{colsa}'
)
raise ValueError(UpperCAmelCase_ )
if len(UpperCAmelCase_ ) != rowsa:
__lowerCamelCase : Optional[Any] = (
'Number of initial values must be equal to number of rows in coefficient '
F'matrix but received {len(UpperCAmelCase_ )} and {rowsa}'
)
raise ValueError(UpperCAmelCase_ )
if iterations <= 0:
raise ValueError('Iterations must be at least 1' )
__lowerCamelCase : NDArray[floataa] = np.concatenate(
(coefficient_matrix, constant_matrix) , axis=1 )
__lowerCamelCase , __lowerCamelCase : Dict = table.shape
strictly_diagonally_dominant(UpperCAmelCase_ )
# Iterates the whole matrix for given number of times
for _ in range(UpperCAmelCase_ ):
__lowerCamelCase : Optional[int] = []
for row in range(UpperCAmelCase_ ):
__lowerCamelCase : Any = 0
for col in range(UpperCAmelCase_ ):
if col == row:
__lowerCamelCase : Union[str, Any] = table[row][col]
elif col == cols - 1:
__lowerCamelCase : Optional[int] = table[row][col]
else:
temp += (-1) * table[row][col] * init_val[col]
__lowerCamelCase : Union[str, Any] = (temp + val) / denom
new_val.append(UpperCAmelCase_ )
__lowerCamelCase : Optional[Any] = new_val
return [float(UpperCAmelCase_ ) for i in new_val]
def UpperCAmelCase__ ( UpperCAmelCase_ : NDArray[floataa] ) -> bool:
__lowerCamelCase , __lowerCamelCase : Optional[int] = table.shape
__lowerCamelCase : str = True
for i in range(0 , UpperCAmelCase_ ):
__lowerCamelCase : int = 0
for j in range(0 , cols - 1 ):
if i == j:
continue
else:
total += table[i][j]
if table[i][i] <= total:
raise ValueError('Coefficient matrix is not strictly diagonally dominant' )
return is_diagonally_dominant
# Test Cases
if __name__ == "__main__":
import doctest
doctest.testmod()
'''simple docstring'''
from __future__ import annotations
def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> bool:
if len(_snake_case ) == 0:
return False
snake_case__ : Dict = len(_snake_case ) // 2
if a_list[midpoint] == item:
return True
if item < a_list[midpoint]:
return binary_search(a_list[:midpoint] , _snake_case )
else:
return binary_search(a_list[midpoint + 1 :] , _snake_case )
if __name__ == "__main__":
__a = input("Enter numbers separated by comma:\n").strip()
__a = [int(item.strip()) for item in user_input.split(",")]
__a = int(input("Enter the number to be found in the list:\n").strip())
__a = "" if binary_search(sequence, target) else "not "
print(F"{target} was {not_str}found in {sequence}")
369
'''simple docstring'''
from queue import Queue
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from ..models.auto import AutoTokenizer
class UpperCAmelCase_ :
"""simple docstring"""
def lowerCamelCase ( self : Optional[Any] , snake_case_ : Optional[int] ):
raise NotImplementedError()
def lowerCamelCase ( self : Optional[int] ):
raise NotImplementedError()
class UpperCAmelCase_ ( _a ):
"""simple docstring"""
def __init__( self : Tuple , snake_case_ : "AutoTokenizer" , snake_case_ : bool = False , **snake_case_ : Tuple ):
snake_case__ : Tuple = tokenizer
snake_case__ : List[str] = skip_prompt
snake_case__ : Optional[int] = decode_kwargs
# variables used in the streaming process
snake_case__ : Optional[int] = []
snake_case__ : Optional[int] = 0
snake_case__ : List[Any] = True
def lowerCamelCase ( self : List[str] , snake_case_ : int ):
if len(value.shape ) > 1 and value.shape[0] > 1:
raise ValueError("""TextStreamer only supports batch size 1""" )
elif len(value.shape ) > 1:
snake_case__ : Optional[Any] = value[0]
if self.skip_prompt and self.next_tokens_are_prompt:
snake_case__ : List[Any] = False
return
# Add the new token to the cache and decodes the entire thing.
self.token_cache.extend(value.tolist() )
snake_case__ : Tuple = self.tokenizer.decode(self.token_cache , **self.decode_kwargs )
# After the symbol for a new line, we flush the cache.
if text.endswith("""\n""" ):
snake_case__ : int = text[self.print_len :]
snake_case__ : Optional[int] = []
snake_case__ : int = 0
# If the last token is a CJK character, we print the characters.
elif len(snake_case_ ) > 0 and self._is_chinese_char(ord(text[-1] ) ):
snake_case__ : str = text[self.print_len :]
self.print_len += len(snake_case_ )
# Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,
# which may change with the subsequent token -- there are probably smarter ways to do this!)
else:
snake_case__ : Dict = text[self.print_len : text.rfind(""" """ ) + 1]
self.print_len += len(snake_case_ )
self.on_finalized_text(snake_case_ )
def lowerCamelCase ( self : int ):
# Flush the cache, if it exists
if len(self.token_cache ) > 0:
snake_case__ : Union[str, Any] = self.tokenizer.decode(self.token_cache , **self.decode_kwargs )
snake_case__ : Optional[Any] = text[self.print_len :]
snake_case__ : Tuple = []
snake_case__ : int = 0
else:
snake_case__ : int = """"""
snake_case__ : Union[str, Any] = True
self.on_finalized_text(snake_case_ , stream_end=snake_case_ )
def lowerCamelCase ( self : Optional[int] , snake_case_ : str , snake_case_ : bool = False ):
print(snake_case_ , flush=snake_case_ , end="""""" if not stream_end else None )
def lowerCamelCase ( self : int , snake_case_ : Optional[int] ):
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if (
(cp >= 0x4E00 and cp <= 0x9FFF)
or (cp >= 0x3400 and cp <= 0x4DBF) #
or (cp >= 0x20000 and cp <= 0x2A6DF) #
or (cp >= 0x2A700 and cp <= 0x2B73F) #
or (cp >= 0x2B740 and cp <= 0x2B81F) #
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
or (cp >= 0xF900 and cp <= 0xFAFF)
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
): #
return True
return False
class UpperCAmelCase_ ( _a ):
"""simple docstring"""
def __init__( self : Optional[int] , snake_case_ : "AutoTokenizer" , snake_case_ : bool = False , snake_case_ : Optional[float] = None , **snake_case_ : List[Any] ):
super().__init__(snake_case_ , snake_case_ , **snake_case_ )
snake_case__ : Dict = Queue()
snake_case__ : List[Any] = None
snake_case__ : int = timeout
def lowerCamelCase ( self : Dict , snake_case_ : str , snake_case_ : bool = False ):
self.text_queue.put(snake_case_ , timeout=self.timeout )
if stream_end:
self.text_queue.put(self.stop_signal , timeout=self.timeout )
def __iter__( self : List[str] ):
return self
def lowerCamelCase ( self : str ):
snake_case__ : List[Any] = self.text_queue.get(timeout=self.timeout )
if value == self.stop_signal:
raise StopIteration()
else:
return value
43
0
'''simple docstring'''
import datasets
from .evaluate import evaluate
_lowerCamelCase : List[str] = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n'
_lowerCamelCase : List[Any] = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n'
_lowerCamelCase : Dict = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the CUAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __UpperCAmelCase ( datasets.Metric ):
'''simple docstring'''
def A (self : int ):
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": {
"""id""": datasets.Value("""string""" ),
"""prediction_text""": datasets.features.Sequence(datasets.Value("""string""" ) ),
},
"""references""": {
"""id""": datasets.Value("""string""" ),
"""answers""": datasets.features.Sequence(
{
"""text""": datasets.Value("""string""" ),
"""answer_start""": datasets.Value("""int32""" ),
} ),
},
} ) , codebase_urls=["""https://www.atticusprojectai.org/cuad"""] , reference_urls=["""https://www.atticusprojectai.org/cuad"""] , )
def A (self : Dict , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Any ):
A = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions}
A = [
{
"""paragraphs""": [
{
"""qas""": [
{
"""answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]],
"""id""": ref["""id"""],
}
for ref in references
]
}
]
}
]
A = evaluate(dataset=_lowerCAmelCase , predictions=_lowerCAmelCase )
return score
258
'''simple docstring'''
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_tf_available():
import tensorflow as tf
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
_lowerCamelCase : Union[str, Any] = logging.get_logger(__name__)
@add_end_docstrings(A__ )
class __UpperCAmelCase ( A__ ):
'''simple docstring'''
def __init__(self : Tuple , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : List[str] ):
super().__init__(*_lowerCAmelCase , **_lowerCAmelCase )
requires_backends(self , """vision""" )
self.check_model_type(
TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
if self.framework == """tf"""
else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING )
def A (self : Any , _lowerCAmelCase : str=None ):
A = {}
if top_k is not None:
A = top_k
return {}, {}, postprocess_params
def __call__(self : str , _lowerCAmelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] , **_lowerCAmelCase : int ):
return super().__call__(_lowerCAmelCase , **_lowerCAmelCase )
def A (self : List[str] , _lowerCAmelCase : List[Any] ):
A = load_image(_lowerCAmelCase )
A = self.image_processor(images=_lowerCAmelCase , return_tensors=self.framework )
return model_inputs
def A (self : Union[str, Any] , _lowerCAmelCase : Optional[int] ):
A = self.model(**_lowerCAmelCase )
return model_outputs
def A (self : Optional[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int=5 ):
if top_k > self.model.config.num_labels:
A = self.model.config.num_labels
if self.framework == "pt":
A = model_outputs.logits.softmax(-1 )[0]
A , A = probs.topk(_lowerCAmelCase )
elif self.framework == "tf":
A = stable_softmax(model_outputs.logits , axis=-1 )[0]
A = tf.math.top_k(_lowerCAmelCase , k=_lowerCAmelCase )
A , A = topk.values.numpy(), topk.indices.numpy()
else:
raise ValueError(F"""Unsupported framework: {self.framework}""" )
A = scores.tolist()
A = ids.tolist()
return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_lowerCAmelCase , _lowerCAmelCase )]
258
1
'''simple docstring'''
import argparse
import os
import re
_snake_case : List[str] = 'src/transformers/models/auto'
# re pattern that matches mapping introductions:
# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict
_snake_case : Any = re.compile(R'[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict')
# re pattern that matches identifiers in mappings
_snake_case : List[str] = re.compile(R'\s*\(\s*"(\S[^"]+)"')
def snake_case_ (UpperCamelCase : str , UpperCamelCase : bool = False ):
'''simple docstring'''
with open(UpperCamelCase , '''r''' , encoding='''utf-8''' ) as f:
_a = f.read()
_a = content.split('''\n''' )
_a = []
_a = 0
while line_idx < len(UpperCamelCase ):
if _re_intro_mapping.search(lines[line_idx] ) is not None:
_a = len(re.search(R'''^(\s*)\S''' , lines[line_idx] ).groups()[0] ) + 8
# Start of a new mapping!
while not lines[line_idx].startswith(''' ''' * indent + '''(''' ):
new_lines.append(lines[line_idx] )
line_idx += 1
_a = []
while lines[line_idx].strip() != "]":
# Blocks either fit in one line or not
if lines[line_idx].strip() == "(":
_a = line_idx
while not lines[line_idx].startswith(''' ''' * indent + ''')''' ):
line_idx += 1
blocks.append('''\n'''.join(lines[start_idx : line_idx + 1] ) )
else:
blocks.append(lines[line_idx] )
line_idx += 1
# Sort blocks by their identifiers
_a = sorted(UpperCamelCase , key=lambda UpperCamelCase : _re_identifier.search(UpperCamelCase ).groups()[0] )
new_lines += blocks
else:
new_lines.append(lines[line_idx] )
line_idx += 1
if overwrite:
with open(UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f:
f.write('''\n'''.join(UpperCamelCase ) )
elif "\n".join(UpperCamelCase ) != content:
return True
def snake_case_ (UpperCamelCase : bool = False ):
'''simple docstring'''
_a = [os.path.join(UpperCamelCase , UpperCamelCase ) for f in os.listdir(UpperCamelCase ) if f.endswith('''.py''' )]
_a = [sort_auto_mapping(UpperCamelCase , overwrite=UpperCamelCase ) for fname in fnames]
if not overwrite and any(UpperCamelCase ):
_a = [f for f, d in zip(UpperCamelCase , UpperCamelCase ) if d]
raise ValueError(
f'The following files have auto mappings that need sorting: {", ".join(UpperCamelCase )}. Run `make style` to fix'
''' this.''' )
if __name__ == "__main__":
_snake_case : Tuple = argparse.ArgumentParser()
parser.add_argument('--check_only', action="https://huggingface.co/datasets/infinityofspace/python_codestyles-mixed1-500/viewer/default/store_true", help='Whether to only check or fix style.')
_snake_case : Tuple = parser.parse_args()
sort_all_auto_mappings(not args.check_only)
179
'''simple docstring'''
from __future__ import annotations
def snake_case_ (UpperCamelCase : list[int] ):
'''simple docstring'''
if not nums:
return 0
_a = nums[0]
_a = 0
for num in nums[1:]:
_a , _a = (
max_excluding + num,
max(UpperCamelCase , UpperCamelCase ),
)
return max(UpperCamelCase , UpperCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
import argparse
import shlex
import runhouse as rh
if __name__ == "__main__":
# Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access
# setup instructions, if using on-demand hardware
# If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster
# If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster
# Throw an error if user passes both BYO and on-demand cluster args
# Otherwise, use default values
__UpperCAmelCase = argparse.ArgumentParser()
parser.add_argument('''--user''', type=str, default='''ubuntu''')
parser.add_argument('''--host''', type=str, default='''localhost''')
parser.add_argument('''--key_path''', type=str, default=None)
parser.add_argument('''--instance''', type=str, default='''V100:1''')
parser.add_argument('''--provider''', type=str, default='''cheapest''')
parser.add_argument('''--use_spot''', type=bool, default=False)
parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''')
__UpperCAmelCase , __UpperCAmelCase = parser.parse_known_args()
if args.host != "localhost":
if args.instance != "V100:1" or args.provider != "cheapest":
raise ValueError('''Cannot specify both BYO and on-demand cluster args''')
__UpperCAmelCase = rh.cluster(
name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path}
)
else:
__UpperCAmelCase = rh.cluster(
name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot
)
__UpperCAmelCase = args.example.rsplit('''/''', 1)[0]
# Set up remote environment
cluster.install_packages(['''pip:./''']) # Installs transformers from local source
# Note transformers is copied into the home directory on the remote machine, so we can install from there
cluster.run([F"""pip install -r transformers/examples/{example_dir}/requirements.txt"""])
cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117'''])
# Run example. You can bypass the CLI wrapper and paste your own code here.
cluster.run([F"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""])
# Alternatively, we can just import and run a training function (especially if there's no wrapper CLI):
# from my_script... import train
# reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard']
# launch_train_gpu = rh.function(fn=train,
# system=gpu,
# reqs=reqs,
# name='train_bert_glue')
#
# We can pass in arguments just like we would to a function:
# launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16
# stream_logs=True)
103
0
'''simple docstring'''
def __lowerCAmelCase ( UpperCamelCase__ ) -> int:
if not isinstance(UpperCamelCase__ , UpperCamelCase__ ):
raise ValueError('''Input must be an integer''' )
if input_num <= 0:
raise ValueError('''Input must be positive''' )
return sum(
divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 )
if __name__ == "__main__":
import doctest
doctest.testmod()
import argparse
from transformers import (
TapasConfig,
TapasForMaskedLM,
TapasForQuestionAnswering,
TapasForSequenceClassification,
TapasModel,
TapasTokenizer,
load_tf_weights_in_tapas,
)
from transformers.utils import logging
logging.set_verbosity_info()
def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : Dict , __UpperCamelCase : Dict , __UpperCamelCase : Optional[int] , __UpperCamelCase : Dict , __UpperCamelCase : List[str] ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE__ = TapasConfig.from_json_file(__UpperCamelCase )
# set absolute/relative position embeddings parameter
SCREAMING_SNAKE_CASE__ = reset_position_index_per_cell
# set remaining parameters of TapasConfig as well as the model based on the task
if task == "SQA":
SCREAMING_SNAKE_CASE__ = TapasForQuestionAnswering(config=__UpperCamelCase )
elif task == "WTQ":
# run_task_main.py hparams
SCREAMING_SNAKE_CASE__ = 4
SCREAMING_SNAKE_CASE__ = True
# hparam_utils.py hparams
SCREAMING_SNAKE_CASE__ = 0.66_4694
SCREAMING_SNAKE_CASE__ = 0.20_7951
SCREAMING_SNAKE_CASE__ = 0.12_1194
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = 0.035_2513
SCREAMING_SNAKE_CASE__ = TapasForQuestionAnswering(config=__UpperCamelCase )
elif task == "WIKISQL_SUPERVISED":
# run_task_main.py hparams
SCREAMING_SNAKE_CASE__ = 4
SCREAMING_SNAKE_CASE__ = False
# hparam_utils.py hparams
SCREAMING_SNAKE_CASE__ = 36.4519
SCREAMING_SNAKE_CASE__ = 0.90_3421
SCREAMING_SNAKE_CASE__ = 222.088
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = 0.76_3141
SCREAMING_SNAKE_CASE__ = TapasForQuestionAnswering(config=__UpperCamelCase )
elif task == "TABFACT":
SCREAMING_SNAKE_CASE__ = TapasForSequenceClassification(config=__UpperCamelCase )
elif task == "MLM":
SCREAMING_SNAKE_CASE__ = TapasForMaskedLM(config=__UpperCamelCase )
elif task == "INTERMEDIATE_PRETRAINING":
SCREAMING_SNAKE_CASE__ = TapasModel(config=__UpperCamelCase )
else:
raise ValueError(f"""Task {task} not supported.""" )
print(f"""Building PyTorch model from configuration: {config}""" )
# Load weights from tf checkpoint
load_tf_weights_in_tapas(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# Save pytorch-model (weights and configuration)
print(f"""Save PyTorch model to {pytorch_dump_path}""" )
model.save_pretrained(__UpperCamelCase )
# Save tokenizer files
print(f"""Save tokenizer files to {pytorch_dump_path}""" )
SCREAMING_SNAKE_CASE__ = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + """vocab.txt""" , model_max_length=5_12 )
tokenizer.save_pretrained(__UpperCamelCase )
print("""Used relative position embeddings:""" , model.config.reset_position_index_per_cell )
if __name__ == "__main__":
__lowerCamelCase : Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.'''
)
parser.add_argument(
'''--reset_position_index_per_cell''',
default=False,
action='''store_true''',
help='''Whether to use relative position embeddings or not. Defaults to True.''',
)
parser.add_argument(
'''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
)
parser.add_argument(
'''--tapas_config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained TAPAS model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
__lowerCamelCase : Dict = parser.parse_args()
convert_tf_checkpoint_to_pytorch(
args.task,
args.reset_position_index_per_cell,
args.tf_checkpoint_path,
args.tapas_config_file,
args.pytorch_dump_path,
)
219
import warnings
from ..trainer import Trainer
from ..utils import logging
__lowerCamelCase : List[Any] = logging.get_logger(__name__)
class __snake_case ( lowerCamelCase_ ):
def __init__( self : Tuple , _lowercase : Optional[int]=None , **_lowercase : List[Any] ):
"""simple docstring"""
warnings.warn(
"""`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """
"""instead.""" , _lowercase , )
super().__init__(args=_lowercase , **_lowercase )
219
1
"""simple docstring"""
import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest
import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed
UpperCamelCase_ =logging.getLogger(__name__)
def a_ ( _lowercase=2 , _lowercase=3 , _lowercase=16 , _lowercase = 10 , _lowercase = 2 ):
def get_dataset(_lowercase ):
_UpperCamelCase : int = torch.randn(batch_size * n_batches , 1 )
return TensorDataset(A__ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) )
_UpperCamelCase : List[str] = get_dataset(A__ )
_UpperCamelCase : int = get_dataset(A__ )
_UpperCamelCase : List[str] = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 )
_UpperCamelCase : Dict = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 )
return (train_dataloader, valid_dataloader)
def a_ ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase=None ):
_UpperCamelCase : str = []
for epoch in range(A__ ):
# Train quickly
model.train()
for batch in dataloader:
_UpperCamelCase , _UpperCamelCase : str = batch
_UpperCamelCase : int = model(A__ )
_UpperCamelCase : str = torch.nn.functional.mse_loss(A__ , A__ )
accelerator.backward(A__ )
optimizer.step()
optimizer.zero_grad()
rands.append(random.random() ) # Introduce some randomness
if scheduler is not None:
scheduler.step()
return rands
class _a ( nn.Module ):
def __init__( self : Dict ) -> Tuple:
'''simple docstring'''
super().__init__()
_UpperCamelCase : Dict = nn.Parameter(torch.randn(1 ) )
_UpperCamelCase : List[str] = nn.Parameter(torch.randn(1 ) )
def snake_case ( self : List[Any], lowerCAmelCase__ : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
return x * self.a + self.b
class _a ( unittest.TestCase ):
def snake_case ( self : str ) -> Optional[int]:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_UpperCamelCase : List[str] = DummyModel()
_UpperCamelCase : Optional[int] = torch.optim.Adam(params=model.parameters(), lr=1e-3 )
_UpperCamelCase , _UpperCamelCase : List[Any] = dummy_dataloaders()
_UpperCamelCase : str = ProjectConfiguration(total_limit=1, project_dir=UpperCamelCase_, automatic_checkpoint_naming=UpperCamelCase_ )
# Train baseline
_UpperCamelCase : str = Accelerator(project_config=UpperCamelCase_ )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Tuple = accelerator.prepare(
UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
# Save initial
accelerator.save_state()
# Save second state
accelerator.save_state()
self.assertEqual(len(os.listdir(accelerator.project_dir ) ), 1 )
def snake_case ( self : Dict ) -> Tuple:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_UpperCamelCase : Optional[Any] = DummyModel()
_UpperCamelCase : List[str] = torch.optim.Adam(params=model.parameters(), lr=1e-3 )
_UpperCamelCase , _UpperCamelCase : str = dummy_dataloaders()
# Train baseline
_UpperCamelCase : Union[str, Any] = Accelerator()
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : List[Any] = accelerator.prepare(
UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
# Save initial
_UpperCamelCase : Union[str, Any] = os.path.join(UpperCamelCase_, '''initial''' )
accelerator.save_state(UpperCamelCase_ )
((_UpperCamelCase) , (_UpperCamelCase)) : Union[str, Any] = model.a.item(), model.b.item()
_UpperCamelCase : List[Any] = optimizer.state_dict()
_UpperCamelCase : List[Any] = train(3, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
((_UpperCamelCase) , (_UpperCamelCase)) : List[str] = model.a.item(), model.b.item()
_UpperCamelCase : int = optimizer.state_dict()
# Train partially
set_seed(4_2 )
_UpperCamelCase : Dict = DummyModel()
_UpperCamelCase : Optional[int] = torch.optim.Adam(params=model.parameters(), lr=1e-3 )
_UpperCamelCase , _UpperCamelCase : List[str] = dummy_dataloaders()
_UpperCamelCase : Tuple = Accelerator()
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : int = accelerator.prepare(
UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
accelerator.load_state(UpperCamelCase_ )
((_UpperCamelCase) , (_UpperCamelCase)) : Tuple = model.a.item(), model.b.item()
_UpperCamelCase : int = optimizer.state_dict()
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
_UpperCamelCase : Optional[Any] = train(2, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
# Save everything
_UpperCamelCase : Dict = os.path.join(UpperCamelCase_, '''checkpoint''' )
accelerator.save_state(UpperCamelCase_ )
# Load everything back in and make sure all states work
accelerator.load_state(UpperCamelCase_ )
test_rands += train(1, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
((_UpperCamelCase) , (_UpperCamelCase)) : List[str] = model.a.item(), model.b.item()
_UpperCamelCase : str = optimizer.state_dict()
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
def snake_case ( self : int ) -> str:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_UpperCamelCase : List[str] = DummyModel()
_UpperCamelCase : List[str] = torch.optim.Adam(params=model.parameters(), lr=1e-3 )
_UpperCamelCase , _UpperCamelCase : List[str] = dummy_dataloaders()
_UpperCamelCase : Optional[Any] = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ )
# Train baseline
_UpperCamelCase : List[Any] = Accelerator(project_dir=UpperCamelCase_, project_config=UpperCamelCase_ )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : List[Any] = accelerator.prepare(
UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
# Save initial
accelerator.save_state()
((_UpperCamelCase) , (_UpperCamelCase)) : List[Any] = model.a.item(), model.b.item()
_UpperCamelCase : Union[str, Any] = optimizer.state_dict()
_UpperCamelCase : Dict = train(3, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
((_UpperCamelCase) , (_UpperCamelCase)) : Any = model.a.item(), model.b.item()
_UpperCamelCase : Optional[int] = optimizer.state_dict()
# Train partially
set_seed(4_2 )
_UpperCamelCase : List[str] = DummyModel()
_UpperCamelCase : int = torch.optim.Adam(params=model.parameters(), lr=1e-3 )
_UpperCamelCase , _UpperCamelCase : Dict = dummy_dataloaders()
_UpperCamelCase : List[Any] = ProjectConfiguration(iteration=1, automatic_checkpoint_naming=UpperCamelCase_ )
_UpperCamelCase : Any = Accelerator(project_dir=UpperCamelCase_, project_config=UpperCamelCase_ )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Optional[Any] = accelerator.prepare(
UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
accelerator.load_state(os.path.join(UpperCamelCase_, '''checkpoints''', '''checkpoint_0''' ) )
((_UpperCamelCase) , (_UpperCamelCase)) : Optional[int] = model.a.item(), model.b.item()
_UpperCamelCase : List[Any] = optimizer.state_dict()
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
_UpperCamelCase : Tuple = train(2, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
# Save everything
accelerator.save_state()
# Load everything back in and make sure all states work
accelerator.load_state(os.path.join(UpperCamelCase_, '''checkpoints''', '''checkpoint_1''' ) )
test_rands += train(1, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
((_UpperCamelCase) , (_UpperCamelCase)) : Optional[int] = model.a.item(), model.b.item()
_UpperCamelCase : List[str] = optimizer.state_dict()
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
self.assertEqual(UpperCamelCase_, UpperCamelCase_ )
def snake_case ( self : List[str] ) -> Tuple:
'''simple docstring'''
_UpperCamelCase : Dict = torch.tensor([1, 2, 3] )
_UpperCamelCase : int = torch.tensor([2, 3, 4] )
_UpperCamelCase : List[str] = DummyModel()
_UpperCamelCase : int = torch.optim.Adam(net.parameters() )
_UpperCamelCase : str = Accelerator()
with self.assertRaises(UpperCamelCase_ ) as ve:
accelerator.register_for_checkpointing(UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
_UpperCamelCase : Dict = str(ve.exception )
self.assertTrue('''Item at index 0''' in message )
self.assertTrue('''Item at index 1''' in message )
self.assertFalse('''Item at index 2''' in message )
self.assertFalse('''Item at index 3''' in message )
def snake_case ( self : int ) -> List[str]:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_UpperCamelCase : int = DummyModel()
_UpperCamelCase : str = torch.optim.Adam(params=model.parameters(), lr=1e-3 )
_UpperCamelCase : List[Any] = torch.optim.lr_scheduler.StepLR(UpperCamelCase_, step_size=1, gamma=0.99 )
_UpperCamelCase , _UpperCamelCase : Any = dummy_dataloaders()
_UpperCamelCase : Union[str, Any] = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ )
# Train baseline
_UpperCamelCase : List[str] = Accelerator(project_dir=UpperCamelCase_, project_config=UpperCamelCase_ )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : Dict = accelerator.prepare(
UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
# Save initial
accelerator.save_state()
_UpperCamelCase : List[str] = scheduler.state_dict()
train(3, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, UpperCamelCase_ )
self.assertNotEqual(UpperCamelCase_, scheduler.state_dict() )
# Load everything back in and make sure all states work
accelerator.load_state(os.path.join(UpperCamelCase_, '''checkpoints''', '''checkpoint_0''' ) )
self.assertEqual(UpperCamelCase_, scheduler.state_dict() )
def snake_case ( self : List[Any] ) -> Any:
'''simple docstring'''
with tempfile.TemporaryDirectory() as tmpdir:
set_seed(4_2 )
_UpperCamelCase : Tuple = DummyModel()
_UpperCamelCase : Any = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_, total_limit=2 )
# Train baseline
_UpperCamelCase : Any = Accelerator(project_dir=UpperCamelCase_, project_config=UpperCamelCase_ )
_UpperCamelCase : Tuple = accelerator.prepare(UpperCamelCase_ )
# Save 3 states:
for _ in range(1_1 ):
accelerator.save_state()
self.assertTrue(not os.path.exists(os.path.join(UpperCamelCase_, '''checkpoints''', '''checkpoint_0''' ) ) )
self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_, '''checkpoints''', '''checkpoint_9''' ) ) )
self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_, '''checkpoints''', '''checkpoint_10''' ) ) )
@require_cuda
def snake_case ( self : Any ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase : int = ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )]
execute_subprocess_async(UpperCamelCase_, env=os.environ.copy() )
if __name__ == "__main__":
UpperCamelCase_ ="""/tmp/accelerate/state_checkpointing"""
UpperCamelCase_ =DummyModel()
UpperCamelCase_ =torch.optim.Adam(params=model.parameters(), lr=1e-3)
UpperCamelCase_ =torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
UpperCamelCase_ , UpperCamelCase_ =dummy_dataloaders()
UpperCamelCase_ =ProjectConfiguration(automatic_checkpoint_naming=True)
# Train baseline
UpperCamelCase_ =Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""")
if accelerator.process_index == 0:
if os.path.exists(savedir):
shutil.rmtree(savedir)
os.makedirs(savedir)
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ =accelerator.prepare(
model, optimizer, train_dataloader, valid_dataloader, scheduler
)
UpperCamelCase_ , UpperCamelCase_ =accelerator.prepare(model, optimizer)
train(3, model, train_dataloader, optimizer, accelerator, scheduler)
# Check that the intial optimizer is loaded on the GPU
for group in optimizer.param_groups:
UpperCamelCase_ =group["""params"""][0].device
break
assert param_device.type == accelerator.device.type
UpperCamelCase_ =model.cpu()
accelerator.wait_for_everyone()
accelerator.save_state()
accelerator.wait_for_everyone()
# Check CPU state
accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""")
for group in optimizer.param_groups:
UpperCamelCase_ =group["""params"""][0].device
break
assert (
param_device.type == torch.device("""cpu""").type
), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"
# Check device state
model.to(accelerator.device)
accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""")
for group in optimizer.param_groups:
UpperCamelCase_ =group["""params"""][0].device
break
assert (
param_device.type == accelerator.device.type
), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"
# Check error
with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""):
accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""")
accelerator.wait_for_everyone()
if accelerator.process_index == 0:
shutil.rmtree(savedir)
accelerator.wait_for_everyone()
357
"""simple docstring"""
import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
embed_questions_for_retrieval,
make_qa_sas_model,
qa_sas_generate,
query_es_index,
query_qa_dense_index,
)
import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer
UpperCamelCase_ ="""bart"""
UpperCamelCase_ =True
@st.cache(allow_output_mutation=_lowercase )
def a_ ( ):
if LOAD_DENSE_INDEX:
_UpperCamelCase : Dict = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' )
_UpperCamelCase : Optional[Any] = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' )
_UpperCamelCase : Union[str, Any] = qar_model.eval()
else:
_UpperCamelCase , _UpperCamelCase : str = (None, None)
if MODEL_TYPE == "bart":
_UpperCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' )
_UpperCamelCase : List[str] = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' )
_UpperCamelCase : List[Any] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' )
sas_model.load_state_dict(save_dict['''model'''] )
_UpperCamelCase : Dict = sas_model.eval()
else:
_UpperCamelCase , _UpperCamelCase : List[Any] = make_qa_sas_model(
model_name='''t5-small''' , from_file='''seq2seq_models/eli5_t5_model_1024_4.pth''' , device='''cuda:0''' )
return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)
@st.cache(allow_output_mutation=_lowercase )
def a_ ( ):
if LOAD_DENSE_INDEX:
_UpperCamelCase : List[Any] = faiss.StandardGpuResources()
_UpperCamelCase : List[str] = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train''']
_UpperCamelCase : Tuple = np.memmap(
'''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , )
_UpperCamelCase : Optional[int] = faiss.IndexFlatIP(128 )
_UpperCamelCase : Tuple = faiss.index_cpu_to_gpu(_lowercase , 1 , _lowercase )
wikiaab_gpu_index_flat.add(_lowercase ) # TODO fix for larger GPU
else:
_UpperCamelCase , _UpperCamelCase : Tuple = (None, None)
_UpperCamelCase : List[Any] = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] )
return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)
@st.cache(allow_output_mutation=_lowercase )
def a_ ( ):
_UpperCamelCase : Optional[Any] = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' )
_UpperCamelCase : Any = elia['''train_eli5''']
_UpperCamelCase : Union[str, Any] = np.memmap(
'''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) )
_UpperCamelCase : str = faiss.IndexFlatIP(128 )
eli5_train_q_index.add(_lowercase )
return (elia_train, eli5_train_q_index)
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ =load_indexes()
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ =load_models()
UpperCamelCase_ , UpperCamelCase_ =load_train_data()
def a_ ( _lowercase , _lowercase=10 ):
_UpperCamelCase : Any = embed_questions_for_retrieval([question] , _lowercase , _lowercase )
_UpperCamelCase , _UpperCamelCase : List[Any] = eli5_train_q_index.search(_lowercase , _lowercase )
_UpperCamelCase : Tuple = [elia_train[int(_lowercase )] for i in I[0]]
return nn_examples
def a_ ( _lowercase , _lowercase="wiki40b" , _lowercase="dense" , _lowercase=10 ):
if source == "none":
_UpperCamelCase , _UpperCamelCase : List[str] = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), [])
else:
if method == "dense":
_UpperCamelCase , _UpperCamelCase : Dict = query_qa_dense_index(
_lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase )
else:
_UpperCamelCase , _UpperCamelCase : List[str] = query_es_index(
_lowercase , _lowercase , index_name='''english_wiki40b_snippets_100w''' , n_results=_lowercase , )
_UpperCamelCase : Any = [
(res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst
]
_UpperCamelCase : List[Any] = '''question: {} context: {}'''.format(_lowercase , _lowercase )
return question_doc, support_list
@st.cache(
hash_funcs={
torch.Tensor: (lambda _lowercase : None),
transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowercase : None),
} )
def a_ ( _lowercase , _lowercase , _lowercase , _lowercase=64 , _lowercase=256 , _lowercase=False , _lowercase=2 , _lowercase=0.95 , _lowercase=0.8 ):
with torch.no_grad():
_UpperCamelCase : List[Any] = qa_sas_generate(
_lowercase , _lowercase , _lowercase , num_answers=1 , num_beams=_lowercase , min_len=_lowercase , max_len=_lowercase , do_sample=_lowercase , temp=_lowercase , top_p=_lowercase , top_k=_lowercase , max_input_length=1024 , device='''cuda:0''' , )[0]
return (answer, support_list)
st.title("""Long Form Question Answering with ELI5""")
# Start sidebar
UpperCamelCase_ ="""<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>"""
UpperCamelCase_ ="""
<html>
<head>
<style>
.img-container {
padding-left: 90px;
padding-right: 90px;
padding-top: 50px;
padding-bottom: 50px;
background-color: #f0f3f9;
}
</style>
</head>
<body>
<span class=\"img-container\"> <!-- Inline parent element -->
%s
</span>
</body>
</html>
""" % (
header_html,
)
st.sidebar.markdown(
header_full,
unsafe_allow_html=True,
)
# Long Form QA with ELI5 and Wikipedia
UpperCamelCase_ ="""
This demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).
First, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,
a pre-processed fixed snapshot of Wikipedia.
"""
st.sidebar.markdown(description, unsafe_allow_html=True)
UpperCamelCase_ =[
"""Answer the question""",
"""View the retrieved document only""",
"""View the most similar ELI5 question and answer""",
"""Show me everything, please!""",
]
UpperCamelCase_ =st.sidebar.checkbox("""Demo options""")
if demo_options:
UpperCamelCase_ =st.sidebar.selectbox(
"""""",
action_list,
index=3,
)
UpperCamelCase_ =action_list.index(action_st)
UpperCamelCase_ =st.sidebar.selectbox(
"""""",
["""Show full text of passages""", """Show passage section titles"""],
index=0,
)
UpperCamelCase_ =show_type == """Show full text of passages"""
else:
UpperCamelCase_ =3
UpperCamelCase_ =True
UpperCamelCase_ =st.sidebar.checkbox("""Retrieval options""")
if retrieval_options:
UpperCamelCase_ ="""
### Information retriever options
The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding
trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.
The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.
"""
st.sidebar.markdown(retriever_info)
UpperCamelCase_ =st.sidebar.selectbox("""Which Wikipedia format should the model use?""", ["""wiki40b""", """none"""])
UpperCamelCase_ =st.sidebar.selectbox("""Which Wikipedia indexer should the model use?""", ["""dense""", """sparse""", """mixed"""])
else:
UpperCamelCase_ ="""wiki40b"""
UpperCamelCase_ ="""dense"""
UpperCamelCase_ ="""beam"""
UpperCamelCase_ =2
UpperCamelCase_ =64
UpperCamelCase_ =256
UpperCamelCase_ =None
UpperCamelCase_ =None
UpperCamelCase_ =st.sidebar.checkbox("""Generation options""")
if generate_options:
UpperCamelCase_ ="""
### Answer generation options
The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)
weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with
**beam** search, or **sample** from the decoder's output probabilities.
"""
st.sidebar.markdown(generate_info)
UpperCamelCase_ =st.sidebar.selectbox("""Would you like to use beam search or sample an answer?""", ["""beam""", """sampled"""])
UpperCamelCase_ =st.sidebar.slider(
"""Minimum generation length""", min_value=8, max_value=256, value=64, step=8, format=None, key=None
)
UpperCamelCase_ =st.sidebar.slider(
"""Maximum generation length""", min_value=64, max_value=512, value=256, step=16, format=None, key=None
)
if sampled == "beam":
UpperCamelCase_ =st.sidebar.slider("""Beam size""", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
else:
UpperCamelCase_ =st.sidebar.slider(
"""Nucleus sampling p""", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
)
UpperCamelCase_ =st.sidebar.slider(
"""Temperature""", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
)
UpperCamelCase_ =None
# start main text
UpperCamelCase_ =[
"""<MY QUESTION>""",
"""How do people make chocolate?""",
"""Why do we get a fever when we are sick?""",
"""How can different animals perceive different colors?""",
"""What is natural language processing?""",
"""What's the best way to treat a sunburn?""",
"""What exactly are vitamins ?""",
"""How does nuclear energy provide electricity?""",
"""What's the difference between viruses and bacteria?""",
"""Why are flutes classified as woodwinds when most of them are made out of metal ?""",
"""Why do people like drinking coffee even though it tastes so bad?""",
"""What happens when wine ages? How does it make the wine taste better?""",
"""If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?""",
"""How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?""",
"""How does New Zealand have so many large bird predators?""",
]
UpperCamelCase_ =st.selectbox(
"""What would you like to ask? ---- select <MY QUESTION> to enter a new query""",
questions_list,
index=1,
)
if question_s == "<MY QUESTION>":
UpperCamelCase_ =st.text_input("""Enter your question here:""", """""")
else:
UpperCamelCase_ =question_s
if st.button("""Show me!"""):
if action in [0, 1, 3]:
if index_type == "mixed":
UpperCamelCase_ , UpperCamelCase_ =make_support(question, source=wiki_source, method="""dense""", n_results=10)
UpperCamelCase_ , UpperCamelCase_ =make_support(question, source=wiki_source, method="""sparse""", n_results=10)
UpperCamelCase_ =[]
for res_d, res_s in zip(support_list_dense, support_list_sparse):
if tuple(res_d) not in support_list:
support_list += [tuple(res_d)]
if tuple(res_s) not in support_list:
support_list += [tuple(res_s)]
UpperCamelCase_ =support_list[:10]
UpperCamelCase_ ="""<P> """ + """ <P> """.join([res[-1] for res in support_list])
else:
UpperCamelCase_ , UpperCamelCase_ =make_support(question, source=wiki_source, method=index_type, n_results=10)
if action in [0, 3]:
UpperCamelCase_ , UpperCamelCase_ =answer_question(
question_doc,
sas_model,
sas_tokenizer,
min_len=min_len,
max_len=int(max_len),
sampling=(sampled == """sampled"""),
n_beams=n_beams,
top_p=top_p,
temp=temp,
)
st.markdown("""### The model generated answer is:""")
st.write(answer)
if action in [0, 1, 3] and wiki_source != "none":
st.markdown("""--- \n ### The model is drawing information from the following Wikipedia passages:""")
for i, res in enumerate(support_list):
UpperCamelCase_ ="""https://en.wikipedia.org/wiki/{}""".format(res[0].replace(""" """, """_"""))
UpperCamelCase_ =res[1].strip()
if sec_titles == "":
UpperCamelCase_ ="""[{}]({})""".format(res[0], wiki_url)
else:
UpperCamelCase_ =sec_titles.split(""" & """)
UpperCamelCase_ =""" & """.join(
["""[{}]({}#{})""".format(sec.strip(), wiki_url, sec.strip().replace(""" """, """_""")) for sec in sec_list]
)
st.markdown(
"""{0:02d} - **Article**: {1:<18} <br> _Section_: {2}""".format(i + 1, res[0], sections),
unsafe_allow_html=True,
)
if show_passages:
st.write(
"""> <span style=\"font-family:arial; font-size:10pt;\">""" + res[-1] + """</span>""", unsafe_allow_html=True
)
if action in [2, 3]:
UpperCamelCase_ =find_nearest_training(question)
UpperCamelCase_ =nn_train_list[0]
st.markdown(
"""--- \n ### The most similar question in the ELI5 training set was: \n\n {}""".format(train_exple["""title"""])
)
UpperCamelCase_ =[
"""{}. {}""".format(i + 1, """ \n""".join([line.strip() for line in ans.split("""\n""") if line.strip() != """"""]))
for i, (ans, sc) in enumerate(zip(train_exple["""answers"""]["""text"""], train_exple["""answers"""]["""score"""]))
if i == 0 or sc > 2
]
st.markdown("""##### Its answers were: \n\n {}""".format("""\n""".join(answers_st)))
UpperCamelCase_ ="""
---
**Disclaimer**
*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.
Evaluating biases of such a model and ensuring factual generations are still very much open research problems.
Therefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*
"""
st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
128
0
'''simple docstring'''
import argparse
from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta
from transformers.utils import logging
logging.set_verbosity_info()
def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> str:
# Initialise PyTorch model
_snake_case = TaConfig.from_json_file(UpperCamelCase__ )
print(F'Building PyTorch model from configuration: {config}' )
_snake_case = TaForConditionalGeneration(UpperCamelCase__ )
# Load weights from tf checkpoint
load_tf_weights_in_ta(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# Save pytorch-model
print(F'Save PyTorch model to {pytorch_dump_path}' )
model.save_pretrained(UpperCamelCase__ )
if __name__ == "__main__":
lowercase : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help=(
"The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture."
),
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
lowercase : str = parser.parse_args()
convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
42
'''simple docstring'''
from collections import namedtuple
import requests
from lxml import html # type: ignore
__A =namedtuple('covid_data', 'cases deaths recovered')
def _UpperCamelCase ( UpperCamelCase__ = "https://www.worldometers.info/coronavirus/" ):
UpperCAmelCase__ : Union[str, Any] = """//div[@class = \"maincounter-number\"]/span/text()"""
return covid_data(*html.fromstring(requests.get(UpperCamelCase__ ).content ).xpath(UpperCamelCase__ ) )
__A ='Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}'
print(fmt.format(*covid_stats()))
163
0
"""simple docstring"""
import timeit
import numpy as np
import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD
def _lowercase ( __lowerCAmelCase ) -> str:
def wrapper(*__lowerCAmelCase , **__lowerCAmelCase ):
SCREAMING_SNAKE_CASE__ : str = timeit.default_timer()
SCREAMING_SNAKE_CASE__ : List[Any] = func(*__lowerCAmelCase , **__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Any = timeit.default_timer() - starttime
return delta
SCREAMING_SNAKE_CASE__ : Optional[int] = func.__name__
return wrapper
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase=100 , __lowerCAmelCase=None ) -> int:
SCREAMING_SNAKE_CASE__ : List[str] = []
SCREAMING_SNAKE_CASE__ : Dict = seq_shapes or {}
for i in range(__lowerCAmelCase ):
SCREAMING_SNAKE_CASE__ : Optional[Any] = {}
for col_id, (k, v) in enumerate(features.items() ):
if isinstance(__lowerCAmelCase , _ArrayXD ):
SCREAMING_SNAKE_CASE__ : Dict = np.random.rand(*v.shape ).astype(v.dtype )
elif isinstance(__lowerCAmelCase , datasets.Value ):
if v.dtype == "string":
SCREAMING_SNAKE_CASE__ : Optional[int] = """The small grey turtle was surprisingly fast when challenged."""
else:
SCREAMING_SNAKE_CASE__ : List[str] = np.random.randint(10 , size=1 ).astype(v.dtype ).item()
elif isinstance(__lowerCAmelCase , datasets.Sequence ):
while isinstance(__lowerCAmelCase , datasets.Sequence ):
SCREAMING_SNAKE_CASE__ : Optional[Any] = v.feature
SCREAMING_SNAKE_CASE__ : str = seq_shapes[k]
SCREAMING_SNAKE_CASE__ : List[str] = np.random.rand(*__lowerCAmelCase ).astype(v.dtype )
SCREAMING_SNAKE_CASE__ : Any = data
dummy_data.append((i, example) )
return dummy_data
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase=100 , __lowerCAmelCase=None ) -> str:
SCREAMING_SNAKE_CASE__ : Tuple = generate_examples(__lowerCAmelCase , num_examples=__lowerCAmelCase , seq_shapes=__lowerCAmelCase )
with ArrowWriter(features=__lowerCAmelCase , path=__lowerCAmelCase ) as writer:
for key, record in dummy_data:
SCREAMING_SNAKE_CASE__ : List[str] = features.encode_example(__lowerCAmelCase )
writer.write(__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = writer.finalize()
if not num_final_examples == num_examples:
raise ValueError(
F'''Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.''' )
SCREAMING_SNAKE_CASE__ : Optional[int] = datasets.Dataset.from_file(filename=__lowerCAmelCase , info=datasets.DatasetInfo(features=__lowerCAmelCase ) )
return dataset
import itertools
import string
from collections.abc import Generator, Iterable
def __lowerCamelCase ( __a :List[str] , __a :Optional[int] ) -> List[Any]:
"""simple docstring"""
A__ = iter(A_ )
while True:
A__ = tuple(itertools.islice(A_ , A_ ) )
if not chunk:
return
yield chunk
def __lowerCamelCase ( __a :Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
A__ = ''''''.join([c.upper() for c in dirty if c in string.ascii_letters] )
A__ = ''''''
if len(A_ ) < 2:
return dirty
for i in range(len(A_ ) - 1 ):
clean += dirty[i]
if dirty[i] == dirty[i + 1]:
clean += "X"
clean += dirty[-1]
if len(A_ ) & 1:
clean += "X"
return clean
def __lowerCamelCase ( __a :Optional[Any] ) -> List[Any]:
"""simple docstring"""
A__ = '''ABCDEFGHIKLMNOPQRSTUVWXYZ'''
# we're using a list instead of a '2d' array because it makes the math
# for setting up the table and doing the actual encoding/decoding simpler
A__ = []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
for char in key.upper():
if char not in table and char in alphabet:
table.append(A_ )
# fill the rest of the table in with the remaining alphabet chars
for char in alphabet:
if char not in table:
table.append(A_ )
return table
def __lowerCamelCase ( __a :int , __a :Any ) -> str:
"""simple docstring"""
A__ = generate_table(A_ )
A__ = prepare_input(A_ )
A__ = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(A_ , 2 ):
A__ = divmod(table.index(A_ ) , 5 )
A__ = divmod(table.index(A_ ) , 5 )
if rowa == rowa:
ciphertext += table[rowa * 5 + (cola + 1) % 5]
ciphertext += table[rowa * 5 + (cola + 1) % 5]
elif cola == cola:
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
ciphertext += table[((rowa + 1) % 5) * 5 + cola]
else: # rectangle
ciphertext += table[rowa * 5 + cola]
ciphertext += table[rowa * 5 + cola]
return ciphertext
def __lowerCamelCase ( __a :Dict , __a :int ) -> List[str]:
"""simple docstring"""
A__ = generate_table(A_ )
A__ = ''''''
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for chara, chara in chunker(A_ , 2 ):
A__ = divmod(table.index(A_ ) , 5 )
A__ = divmod(table.index(A_ ) , 5 )
if rowa == rowa:
plaintext += table[rowa * 5 + (cola - 1) % 5]
plaintext += table[rowa * 5 + (cola - 1) % 5]
elif cola == cola:
plaintext += table[((rowa - 1) % 5) * 5 + cola]
plaintext += table[((rowa - 1) % 5) * 5 + cola]
else: # rectangle
plaintext += table[rowa * 5 + cola]
plaintext += table[rowa * 5 + cola]
return plaintext
358
from __future__ import annotations
import unittest
from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available
from transformers.testing_utils import 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel
@require_tf
class A :
'''simple docstring'''
__lowerCamelCase : Optional[Any] = BlenderbotSmallConfig
__lowerCamelCase : Optional[Any] = {}
__lowerCamelCase : List[Any] = '''gelu'''
def __init__( self : Dict , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str]=13 , __lowerCAmelCase : List[Any]=7 , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : List[Any]=False , __lowerCAmelCase : Union[str, Any]=99 , __lowerCAmelCase : Union[str, Any]=32 , __lowerCAmelCase : Any=2 , __lowerCAmelCase : Optional[Any]=4 , __lowerCAmelCase : Tuple=37 , __lowerCAmelCase : List[Any]=0.1 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : List[str]=20 , __lowerCAmelCase : Union[str, Any]=2 , __lowerCAmelCase : Dict=1 , __lowerCAmelCase : int=0 , ) -> Any:
"""simple docstring"""
A__ = parent
A__ = batch_size
A__ = seq_length
A__ = is_training
A__ = use_labels
A__ = vocab_size
A__ = hidden_size
A__ = num_hidden_layers
A__ = num_attention_heads
A__ = intermediate_size
A__ = hidden_dropout_prob
A__ = attention_probs_dropout_prob
A__ = max_position_embeddings
A__ = eos_token_id
A__ = pad_token_id
A__ = bos_token_id
def a_ ( self : Optional[Any] ) -> Tuple:
"""simple docstring"""
A__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size )
A__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 )
A__ = tf.concat([input_ids, eos_tensor] , axis=1 )
A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
A__ = 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 , )
A__ = prepare_blenderbot_small_inputs_dict(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
return config, inputs_dict
def a_ ( self : Union[str, Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] ) -> str:
"""simple docstring"""
A__ = TFBlenderbotSmallModel(config=__lowerCAmelCase ).get_decoder()
A__ = inputs_dict["""input_ids"""]
A__ = input_ids[:1, :]
A__ = inputs_dict["""attention_mask"""][:1, :]
A__ = inputs_dict["""head_mask"""]
A__ = 1
# first forward pass
A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , head_mask=__lowerCAmelCase , use_cache=__lowerCAmelCase )
A__ , A__ = outputs.to_tuple()
# create hypothetical next token and extent to next_input_ids
A__ = ids_tensor((self.batch_size, 3) , config.vocab_size )
A__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta )
# append to next input_ids and
A__ = tf.concat([input_ids, next_tokens] , axis=-1 )
A__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 )
A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase )[0]
A__ = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , past_key_values=__lowerCAmelCase )[0]
self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] )
# select random slice
A__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) )
A__ = output_from_no_past[:, -3:, random_slice_idx]
A__ = output_from_past[:, :, random_slice_idx]
# test that outputs are equal for slice
tf.debugging.assert_near(__lowerCAmelCase , __lowerCAmelCase , rtol=1e-3 )
def __lowerCamelCase ( __a :Dict , __a :Tuple , __a :List[Any] , __a :List[str]=None , __a :List[Any]=None , __a :Optional[Any]=None , __a :List[str]=None , __a :int=None , ) -> Optional[Any]:
"""simple docstring"""
if attention_mask is None:
A__ = tf.cast(tf.math.not_equal(__a , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
A__ = 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:
A__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
A__ = 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 A (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ):
'''simple docstring'''
__lowerCamelCase : Tuple = (
(TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
)
__lowerCamelCase : List[Any] = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
__lowerCamelCase : Tuple = (
{
'''conversational''': TFBlenderbotSmallForConditionalGeneration,
'''feature-extraction''': TFBlenderbotSmallModel,
'''summarization''': TFBlenderbotSmallForConditionalGeneration,
'''text2text-generation''': TFBlenderbotSmallForConditionalGeneration,
'''translation''': TFBlenderbotSmallForConditionalGeneration,
}
if is_tf_available()
else {}
)
__lowerCamelCase : Dict = True
__lowerCamelCase : Optional[Any] = False
__lowerCamelCase : Tuple = False
def a_ ( self : Tuple ) -> Optional[int]:
"""simple docstring"""
A__ = TFBlenderbotSmallModelTester(self )
A__ = ConfigTester(self , config_class=__lowerCAmelCase )
def a_ ( self : List[str] ) -> int:
"""simple docstring"""
self.config_tester.run_common_tests()
def a_ ( self : List[str] ) -> Any:
"""simple docstring"""
A__ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__lowerCAmelCase )
@require_tokenizers
@require_tf
class A (unittest.TestCase ):
'''simple docstring'''
__lowerCamelCase : List[str] = [
'''Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like '''
''' i\'m going to throw up.\nand why is that?'''
]
__lowerCamelCase : Optional[int] = '''facebook/blenderbot_small-90M'''
@cached_property
def a_ ( self : Optional[int] ) -> List[str]:
"""simple docstring"""
return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" )
@cached_property
def a_ ( self : List[str] ) -> List[str]:
"""simple docstring"""
A__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
return model
@slow
def a_ ( self : int ) -> Optional[Any]:
"""simple docstring"""
A__ = self.tokenizer(self.src_text , return_tensors="""tf""" )
A__ = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__lowerCAmelCase , )
A__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__lowerCAmelCase )[0]
assert generated_words in (
"i don't know. i just feel like i'm going to throw up. it's not fun.",
"i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
"i'm not sure. i just feel like i've been in a bad situation.",
)
276
0
import inspect
import os
import re
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
_UpperCAmelCase = """src/transformers"""
# This is to make sure the transformers module imported is the one in the repo.
_UpperCAmelCase = direct_transformers_import(PATH_TO_TRANSFORMERS)
_UpperCAmelCase = transformers.models.auto.configuration_auto.CONFIG_MAPPING
_UpperCAmelCase = {
# used to compute the property `self.chunk_length`
"""EncodecConfig""": ["""overlap"""],
# used as `self.bert_model = BertModel(config, ...)`
"""DPRConfig""": True,
# not used in modeling files, but it's an important information
"""FSMTConfig""": ["""langs"""],
# used internally in the configuration class file
"""GPTNeoConfig""": ["""attention_types"""],
# used internally in the configuration class file
"""EsmConfig""": ["""is_folding_model"""],
# used during training (despite we don't have training script for these models yet)
"""Mask2FormerConfig""": ["""ignore_value"""],
# `ignore_value` used during training (despite we don't have training script for these models yet)
# `norm` used in conversion script (despite not using in the modeling file)
"""OneFormerConfig""": ["""ignore_value""", """norm"""],
# used during preprocessing and collation, see `collating_graphormer.py`
"""GraphormerConfig""": ["""spatial_pos_max"""],
# used internally in the configuration class file
"""T5Config""": ["""feed_forward_proj"""],
# used internally in the configuration class file
# `tokenizer_class` get default value `T5Tokenizer` intentionally
"""MT5Config""": ["""feed_forward_proj""", """tokenizer_class"""],
"""UMT5Config""": ["""feed_forward_proj""", """tokenizer_class"""],
# used internally in the configuration class file
"""LongT5Config""": ["""feed_forward_proj"""],
# used internally in the configuration class file
"""SwitchTransformersConfig""": ["""feed_forward_proj"""],
# having default values other than `1e-5` - we can't fix them without breaking
"""BioGptConfig""": ["""layer_norm_eps"""],
# having default values other than `1e-5` - we can't fix them without breaking
"""GLPNConfig""": ["""layer_norm_eps"""],
# having default values other than `1e-5` - we can't fix them without breaking
"""SegformerConfig""": ["""layer_norm_eps"""],
# having default values other than `1e-5` - we can't fix them without breaking
"""CvtConfig""": ["""layer_norm_eps"""],
# having default values other than `1e-5` - we can't fix them without breaking
"""PerceiverConfig""": ["""layer_norm_eps"""],
# used internally to calculate the feature size
"""InformerConfig""": ["""num_static_real_features""", """num_time_features"""],
# used internally to calculate the feature size
"""TimeSeriesTransformerConfig""": ["""num_static_real_features""", """num_time_features"""],
# used internally to calculate the feature size
"""AutoformerConfig""": ["""num_static_real_features""", """num_time_features"""],
# used internally to calculate `mlp_dim`
"""SamVisionConfig""": ["""mlp_ratio"""],
# For (head) training, but so far not implemented
"""ClapAudioConfig""": ["""num_classes"""],
# Not used, but providing useful information to users
"""SpeechT5HifiGanConfig""": ["""sampling_rate"""],
}
# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure
SPECIAL_CASES_TO_ALLOW.update(
{
"""CLIPSegConfig""": True,
"""DeformableDetrConfig""": True,
"""DetaConfig""": True,
"""DinatConfig""": True,
"""DonutSwinConfig""": True,
"""EfficientFormerConfig""": True,
"""FSMTConfig""": True,
"""JukeboxConfig""": True,
"""LayoutLMv2Config""": True,
"""MaskFormerSwinConfig""": True,
"""MT5Config""": True,
"""NatConfig""": True,
"""OneFormerConfig""": True,
"""PerceiverConfig""": True,
"""RagConfig""": True,
"""SpeechT5Config""": True,
"""SwinConfig""": True,
"""Swin2SRConfig""": True,
"""Swinv2Config""": True,
"""SwitchTransformersConfig""": True,
"""TableTransformerConfig""": True,
"""TapasConfig""": True,
"""TransfoXLConfig""": True,
"""UniSpeechConfig""": True,
"""UniSpeechSatConfig""": True,
"""WavLMConfig""": True,
"""WhisperConfig""": True,
# TODO: @Arthur (for `alignment_head` and `alignment_layer`)
"""JukeboxPriorConfig""": True,
# TODO: @Younes (for `is_decoder`)
"""Pix2StructTextConfig""": True,
}
)
def UpperCamelCase ( __lowercase : Union[str, Any] ,__lowercase : Union[str, Any] ,__lowercase : Union[str, Any] ,__lowercase : Dict ):
'''simple docstring'''
A_ : Union[str, Any] = False
for attribute in attributes:
for modeling_source in source_strings:
# check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)`
if (
f'''config.{attribute}''' in modeling_source
or f'''getattr(config, "{attribute}"''' in modeling_source
or f'''getattr(self.config, "{attribute}"''' in modeling_source
):
A_ : str = True
# Deal with multi-line cases
elif (
re.search(
rf'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"''' ,__lowercase ,)
is not None
):
A_ : int = True
# `SequenceSummary` is called with `SequenceSummary(config)`
elif attribute in [
"summary_type",
"summary_use_proj",
"summary_activation",
"summary_last_dropout",
"summary_proj_to_labels",
"summary_first_dropout",
]:
if "SequenceSummary" in modeling_source:
A_ : List[Any] = True
if attribute_used:
break
if attribute_used:
break
# common and important attributes, even if they do not always appear in the modeling files
A_ : List[Any] = [
'bos_index',
'eos_index',
'pad_index',
'unk_index',
'mask_index',
'image_size',
'use_cache',
'out_features',
'out_indices',
]
A_ : List[str] = ['encoder_no_repeat_ngram_size']
# Special cases to be allowed
A_ : Any = True
if not attribute_used:
A_ : List[str] = False
for attribute in attributes:
# Allow if the default value in the configuration class is different from the one in `PretrainedConfig`
if attribute in ["is_encoder_decoder"] and default_value is True:
A_ : int = True
elif attribute in ["tie_word_embeddings"] and default_value is False:
A_ : Optional[int] = True
# Allow cases without checking the default value in the configuration class
elif attribute in attributes_to_allow + attributes_used_in_generation:
A_ : int = True
elif attribute.endswith('_token_id' ):
A_ : Any = True
# configuration class specific cases
if not case_allowed:
A_ : Any = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ ,[] )
A_ : Tuple = allowed_cases is True or attribute in allowed_cases
return attribute_used or case_allowed
def UpperCamelCase ( __lowercase : List[Any] ):
'''simple docstring'''
A_ : Tuple = dict(inspect.signature(config_class.__init__ ).parameters )
A_ : int = [x for x in list(signature.keys() ) if x not in ['self', 'kwargs']]
A_ : Any = [signature[param].default for param in parameter_names]
# If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long
# as one variant is used, the test should pass
A_ : Tuple = {}
if len(config_class.attribute_map ) > 0:
A_ : Dict = {v: k for k, v in config_class.attribute_map.items()}
# Get the path to modeling source files
A_ : str = inspect.getsourcefile(__lowercase )
A_ : List[str] = os.path.dirname(__lowercase )
# Let's check against all frameworks: as long as one framework uses an attribute, we are good.
A_ : str = [os.path.join(__lowercase ,__lowercase ) for fn in os.listdir(__lowercase ) if fn.startswith('modeling_' )]
# Get the source code strings
A_ : Optional[Any] = []
for path in modeling_paths:
if os.path.isfile(__lowercase ):
with open(__lowercase ) as fp:
modeling_sources.append(fp.read() )
A_ : Dict = []
for config_param, default_value in zip(__lowercase ,__lowercase ):
# `attributes` here is all the variant names for `config_param`
A_ : Tuple = [config_param]
# some configuration classes have non-empty `attribute_map`, and both names could be used in the
# corresponding modeling files. As long as one of them appears, it is fine.
if config_param in reversed_attribute_map:
attributes.append(reversed_attribute_map[config_param] )
if not check_attribute_being_used(__lowercase ,__lowercase ,__lowercase ,__lowercase ):
unused_attributes.append(attributes[0] )
return sorted(__lowercase )
def UpperCamelCase ( ):
'''simple docstring'''
A_ : List[str] = {}
for _config_class in list(CONFIG_MAPPING.values() ):
# Skip deprecated models
if "models.deprecated" in _config_class.__module__:
continue
# Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.)
A_ : str = [
cls
for name, cls in inspect.getmembers(
inspect.getmodule(_config_class ) ,lambda __lowercase : inspect.isclass(__lowercase )
and issubclass(__lowercase ,__lowercase )
and inspect.getmodule(__lowercase ) == inspect.getmodule(_config_class ) ,)
]
for config_class in config_classes_in_module:
A_ : int = check_config_attributes_being_used(__lowercase )
if len(__lowercase ) > 0:
A_ : Optional[int] = unused_attributes
if len(__lowercase ) > 0:
A_ : Union[str, Any] = 'The following configuration classes contain unused attributes in the corresponding modeling files:\n'
for name, attributes in configs_with_unused_attributes.items():
error += f'''{name}: {attributes}\n'''
raise ValueError(__lowercase )
if __name__ == "__main__":
check_config_attributes()
140
import argparse
from typing import Dict
import tensorflow as tf
import torch
from tqdm import tqdm
from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration
_UpperCAmelCase = [
# tf -> hf
("""/""", """."""),
("""layer_""", """layers."""),
("""kernel""", """weight"""),
("""beta""", """bias"""),
("""gamma""", """weight"""),
("""pegasus""", """model"""),
]
_UpperCAmelCase = [
(""".output.dense""", """.fc2"""),
("""intermediate.LayerNorm""", """final_layer_norm"""),
("""intermediate.dense""", """fc1"""),
]
_UpperCAmelCase = (
INIT_COMMON
+ [
("""attention.self.LayerNorm""", """self_attn_layer_norm"""),
("""attention.output.dense""", """self_attn.out_proj"""),
("""attention.self""", """self_attn"""),
("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""),
("""attention.encdec_output.dense""", """encoder_attn.out_proj"""),
("""attention.encdec""", """encoder_attn"""),
("""key""", """k_proj"""),
("""value""", """v_proj"""),
("""query""", """q_proj"""),
("""decoder.LayerNorm""", """decoder.layernorm_embedding"""),
]
+ END_COMMON
)
_UpperCAmelCase = (
INIT_COMMON
+ [
("""embeddings.word_embeddings""", """shared.weight"""),
("""embeddings.position_embeddings""", """embed_positions.weight"""),
("""attention.self.LayerNorm""", """self_attn_layer_norm"""),
("""attention.output.dense""", """self_attn.output"""),
("""attention.self""", """self_attn.self"""),
("""encoder.LayerNorm""", """encoder.layernorm_embedding"""),
]
+ END_COMMON
)
_UpperCAmelCase = [
"""encdec/key/bias""",
"""encdec/query/bias""",
"""encdec/value/bias""",
"""self/key/bias""",
"""self/query/bias""",
"""self/value/bias""",
"""encdec_output/dense/bias""",
"""attention/output/dense/bias""",
]
def UpperCamelCase ( __lowercase : Optional[Any] ,__lowercase : Tuple ):
'''simple docstring'''
for tf_name, hf_name in patterns:
A_ : Tuple = k.replace(__lowercase ,__lowercase )
return k
def UpperCamelCase ( __lowercase : dict ,__lowercase : dict ):
'''simple docstring'''
A_ : int = BigBirdPegasusConfig(**__lowercase )
A_ : Any = BigBirdPegasusForConditionalGeneration(__lowercase )
A_ : Union[str, Any] = torch_model.state_dict()
A_ : Any = {}
# separating decoder weights
A_ : Any = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )}
A_ : str = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )}
for k, v in tqdm(decoder_weights.items() ,'tf -> hf conversion' ):
A_ : Optional[int] = [k.endswith(__lowercase ) for ending in KEYS_TO_IGNORE]
if any(__lowercase ):
continue
A_ : Optional[Any] = DECODER_PATTERNS
A_ : Tuple = rename_state_dict_key(__lowercase ,__lowercase )
if new_k not in state_dict:
raise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})''' )
if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ):
A_ : Any = v.T
A_ : Any = torch.from_numpy(__lowercase )
assert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'''
for k, v in tqdm(remaining_weights.items() ,'tf -> hf conversion' ):
A_ : int = [k.endswith(__lowercase ) for ending in KEYS_TO_IGNORE]
if any(__lowercase ):
continue
A_ : Any = REMAINING_PATTERNS
A_ : List[str] = rename_state_dict_key(__lowercase ,__lowercase )
if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings":
raise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})''' )
if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ):
A_ : int = v.T
A_ : Dict = torch.from_numpy(__lowercase )
if k != "pegasus/embeddings/position_embeddings":
assert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}'''
A_ : Optional[int] = mapping['model.embed_positions.weight']
A_ : Tuple = mapping.pop('model.embed_positions.weight' )
A_ , A_ : Optional[Any] = torch_model.load_state_dict(__lowercase ,strict=__lowercase )
A_ : Optional[int] = [
k
for k in missing
if k
not in [
'final_logits_bias',
'model.encoder.embed_tokens.weight',
'model.decoder.embed_tokens.weight',
'lm_head.weight',
]
]
assert unexpected_missing == [], f'''no matches found for the following torch keys {unexpected_missing}'''
assert extra == [], f'''no matches found for the following tf keys {extra}'''
return torch_model
def UpperCamelCase ( __lowercase : Union[str, Any] ):
'''simple docstring'''
A_ : str = tf.train.list_variables(__lowercase )
A_ : Union[str, Any] = {}
A_ : Optional[Any] = ['global_step']
for name, shape in tqdm(__lowercase ,desc='converting tf checkpoint to dict' ):
A_ : Union[str, Any] = any(pat in name for pat in ignore_name )
if skip_key:
continue
A_ : Tuple = tf.train.load_variable(__lowercase ,__lowercase )
A_ : Dict = array
return tf_weights
def UpperCamelCase ( __lowercase : str ,__lowercase : str ,__lowercase : dict ):
'''simple docstring'''
A_ : Optional[Any] = get_tf_weights_as_numpy(__lowercase )
A_ : Dict = convert_bigbird_pegasus(__lowercase ,__lowercase )
torch_model.save_pretrained(__lowercase )
if __name__ == "__main__":
_UpperCAmelCase = argparse.ArgumentParser()
parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""")
parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""")
_UpperCAmelCase = parser.parse_args()
_UpperCAmelCase = {}
convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
140
1
'''simple docstring'''
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING
__lowerCAmelCase = logging.get_logger(__name__)
__lowerCAmelCase = {
"salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
}
class __magic_name__ ( SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase : Dict = 'blip_2_vision_model'
def __init__( self : Dict ,_UpperCAmelCase : int=1408 ,_UpperCAmelCase : Any=6144 ,_UpperCAmelCase : Union[str, Any]=39 ,_UpperCAmelCase : Union[str, Any]=16 ,_UpperCAmelCase : List[str]=224 ,_UpperCAmelCase : Optional[int]=14 ,_UpperCAmelCase : Tuple="gelu" ,_UpperCAmelCase : Tuple=0.0_00_01 ,_UpperCAmelCase : Dict=0.0 ,_UpperCAmelCase : Union[str, Any]=1E-10 ,_UpperCAmelCase : int=True ,**_UpperCAmelCase : Tuple ,):
super().__init__(**a_ )
_a : Union[str, Any] = hidden_size
_a : List[str] = intermediate_size
_a : Dict = num_hidden_layers
_a : List[Any] = num_attention_heads
_a : Any = patch_size
_a : Union[str, Any] = image_size
_a : Union[str, Any] = initializer_range
_a : Union[str, Any] = attention_dropout
_a : Optional[int] = layer_norm_eps
_a : Optional[Any] = hidden_act
_a : List[str] = qkv_bias
@classmethod
def __lowercase ( cls : Any ,_UpperCAmelCase : Union[str, os.PathLike] ,**_UpperCAmelCase : Any ):
cls._set_token_in_kwargs(a_ )
_a , _a : Optional[Any] = cls.get_config_dict(a_ ,**a_ )
# get the vision config dict if we are loading from Blip2Config
if config_dict.get('model_type' ) == "blip-2":
_a : Any = config_dict['vision_config']
if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" )
return cls.from_dict(a_ ,**a_ )
class __magic_name__ ( SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase : Optional[int] = 'blip_2_qformer'
def __init__( self : Tuple ,_UpperCAmelCase : Tuple=30522 ,_UpperCAmelCase : Any=768 ,_UpperCAmelCase : Union[str, Any]=12 ,_UpperCAmelCase : Optional[int]=12 ,_UpperCAmelCase : Union[str, Any]=3072 ,_UpperCAmelCase : List[Any]="gelu" ,_UpperCAmelCase : Dict=0.1 ,_UpperCAmelCase : Dict=0.1 ,_UpperCAmelCase : List[Any]=512 ,_UpperCAmelCase : Any=0.02 ,_UpperCAmelCase : Optional[Any]=1E-12 ,_UpperCAmelCase : str=0 ,_UpperCAmelCase : List[str]="absolute" ,_UpperCAmelCase : List[str]=2 ,_UpperCAmelCase : List[Any]=1408 ,**_UpperCAmelCase : Tuple ,):
super().__init__(pad_token_id=a_ ,**a_ )
_a : int = vocab_size
_a : Optional[Any] = hidden_size
_a : str = num_hidden_layers
_a : List[Any] = num_attention_heads
_a : List[Any] = hidden_act
_a : int = intermediate_size
_a : Optional[Any] = hidden_dropout_prob
_a : List[Any] = attention_probs_dropout_prob
_a : Optional[int] = max_position_embeddings
_a : List[Any] = initializer_range
_a : Optional[Any] = layer_norm_eps
_a : Any = position_embedding_type
_a : Optional[int] = cross_attention_frequency
_a : Tuple = encoder_hidden_size
@classmethod
def __lowercase ( cls : Optional[int] ,_UpperCAmelCase : Union[str, os.PathLike] ,**_UpperCAmelCase : List[str] ):
cls._set_token_in_kwargs(a_ )
_a , _a : Dict = cls.get_config_dict(a_ ,**a_ )
# get the qformer config dict if we are loading from Blip2Config
if config_dict.get('model_type' ) == "blip-2":
_a : int = config_dict['qformer_config']
if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" )
return cls.from_dict(a_ ,**a_ )
class __magic_name__ ( SCREAMING_SNAKE_CASE__ ):
lowerCAmelCase : Optional[int] = 'blip-2'
lowerCAmelCase : Dict = True
def __init__( self : Dict ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : Optional[Any]=None ,_UpperCAmelCase : Dict=None ,_UpperCAmelCase : Tuple=32 ,**_UpperCAmelCase : Optional[int] ):
super().__init__(**a_ )
if vision_config is None:
_a : List[Any] = {}
logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' )
if qformer_config is None:
_a : List[Any] = {}
logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' )
if text_config is None:
_a : Optional[Any] = {}
logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' )
_a : Optional[Any] = BlipaVisionConfig(**a_ )
_a : Optional[Any] = BlipaQFormerConfig(**a_ )
_a : Optional[Any] = text_config['model_type'] if 'model_type' in text_config else 'opt'
_a : Dict = CONFIG_MAPPING[text_model_type](**a_ )
_a : Dict = self.text_config.tie_word_embeddings
_a : Union[str, Any] = self.text_config.is_encoder_decoder
_a : str = num_query_tokens
_a : int = self.vision_config.hidden_size
_a : Optional[int] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
_a : int = 1.0
_a : Any = 0.02
@classmethod
def __lowercase ( cls : int ,_UpperCAmelCase : BlipaVisionConfig ,_UpperCAmelCase : BlipaQFormerConfig ,_UpperCAmelCase : PretrainedConfig ,**_UpperCAmelCase : int ,):
return cls(
vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**a_ ,)
def __lowercase ( self : Tuple ):
_a : Tuple = copy.deepcopy(self.__dict__ )
_a : str = self.vision_config.to_dict()
_a : Any = self.qformer_config.to_dict()
_a : Optional[int] = self.text_config.to_dict()
_a : Any = self.__class__.model_type
return output
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
SCREAMING_SNAKE_CASE__ = {
"""configuration_ernie""": ["""ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ErnieConfig""", """ErnieOnnxConfig"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE__ = [
"""ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ErnieForCausalLM""",
"""ErnieForMaskedLM""",
"""ErnieForMultipleChoice""",
"""ErnieForNextSentencePrediction""",
"""ErnieForPreTraining""",
"""ErnieForQuestionAnswering""",
"""ErnieForSequenceClassification""",
"""ErnieForTokenClassification""",
"""ErnieModel""",
"""ErniePreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
297
from scipy.stats import pearsonr
import datasets
SCREAMING_SNAKE_CASE__ = """
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""
SCREAMING_SNAKE_CASE__ = """
Args:
predictions (`list` of `int`): Predicted class labels, as returned by a model.
references (`list` of `int`): Ground truth labels.
return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.
Returns:
pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.
Examples:
Example 1-A simple example using only predictions and references.
>>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
>>> print(round(results['pearsonr'], 2))
-0.74
Example 2-The same as Example 1, but that also returns the `p-value`.
>>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
>>> print(sorted(list(results.keys())))
['p-value', 'pearsonr']
>>> print(round(results['pearsonr'], 2))
-0.74
>>> print(round(results['p-value'], 2))
0.15
"""
SCREAMING_SNAKE_CASE__ = """
@article{2020SciPy-NMeth,
author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
Haberland, Matt and Reddy, Tyler and Cournapeau, David and
Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
Kern, Robert and Larson, Eric and Carey, C J and
Polat, Ilhan and Feng, Yu and Moore, Eric W. and
{VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
Harris, Charles R. and Archibald, Anne M. and
Ribeiro, Antonio H. and Pedregosa, Fabian and
{van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
Computing in Python}},
journal = {Nature Methods},
year = {2020},
volume = {17},
pages = {261--272},
adsurl = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __lowerCamelCase ( datasets.Metric ):
"""simple docstring"""
def A__ ( self ) -> int:
'''simple docstring'''
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"predictions": datasets.Value("float" ),
"references": datasets.Value("float" ),
} ) , reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"] , )
def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=False ) -> int:
'''simple docstring'''
if return_pvalue:
lowercase_ = pearsonr(UpperCAmelCase , UpperCAmelCase )
return {"pearsonr": results[0], "p-value": results[1]}
else:
return {"pearsonr": float(pearsonr(UpperCAmelCase , UpperCAmelCase )[0] )}
297
1
"""simple docstring"""
import argparse
import os
import re
lowercase__ = '''src/transformers'''
# Pattern that looks at the indentation in a line.
lowercase__ = re.compile(R"""^(\s*)\S""")
# Pattern that matches `"key":" and puts `key` in group 0.
lowercase__ = re.compile(R"""^\s*\"([^\"]+)\":""")
# Pattern that matches `_import_structure["key"]` and puts `key` in group 0.
lowercase__ = re.compile(R"""^\s*_import_structure\[\"([^\"]+)\"\]""")
# Pattern that matches `"key",` and puts `key` in group 0.
lowercase__ = re.compile(R"""^\s*\"([^\"]+)\",\s*$""")
# Pattern that matches any `[stuff]` and puts `stuff` in group 0.
lowercase__ = re.compile(R"""\[([^\]]+)\]""")
def _snake_case ( lowercase__ ):
_lowerCamelCase : Tuple = _re_indent.search(a__ )
return "" if search is None else search.groups()[0]
def _snake_case ( lowercase__ , lowercase__="" , lowercase__=None , lowercase__=None ):
_lowerCamelCase : Union[str, Any] = 0
_lowerCamelCase : int = code.split('\n' )
if start_prompt is not None:
while not lines[index].startswith(a__ ):
index += 1
_lowerCamelCase : str = ['''\n'''.join(lines[:index] )]
else:
_lowerCamelCase : List[Any] = []
# We split into blocks until we get to the `end_prompt` (or the end of the block).
_lowerCamelCase : Optional[Any] = [lines[index]]
index += 1
while index < len(a__ ) and (end_prompt is None or not lines[index].startswith(a__ )):
if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level:
if len(a__ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ' ' ):
current_block.append(lines[index] )
blocks.append('\n'.join(a__ ) )
if index < len(a__ ) - 1:
_lowerCamelCase : List[str] = [lines[index + 1]]
index += 1
else:
_lowerCamelCase : Union[str, Any] = []
else:
blocks.append('\n'.join(a__ ) )
_lowerCamelCase : Union[str, Any] = [lines[index]]
else:
current_block.append(lines[index] )
index += 1
# Adds current block if it's nonempty.
if len(a__ ) > 0:
blocks.append('\n'.join(a__ ) )
# Add final block after end_prompt if provided.
if end_prompt is not None and index < len(a__ ):
blocks.append('\n'.join(lines[index:] ) )
return blocks
def _snake_case ( lowercase__ ):
def _inner(lowercase__ ):
return key(a__ ).lower().replace('_' , '' )
return _inner
def _snake_case ( lowercase__ , lowercase__=None ):
def noop(lowercase__ ):
return x
if key is None:
_lowerCamelCase : List[Any] = noop
# Constants are all uppercase, they go first.
_lowerCamelCase : Union[str, Any] = [obj for obj in objects if key(a__ ).isupper()]
# Classes are not all uppercase but start with a capital, they go second.
_lowerCamelCase : int = [obj for obj in objects if key(a__ )[0].isupper() and not key(a__ ).isupper()]
# Functions begin with a lowercase, they go last.
_lowerCamelCase : Dict = [obj for obj in objects if not key(a__ )[0].isupper()]
_lowerCamelCase : Optional[int] = ignore_underscore(a__ )
return sorted(a__ , key=a__ ) + sorted(a__ , key=a__ ) + sorted(a__ , key=a__ )
def _snake_case ( lowercase__ ):
def _replace(lowercase__ ):
_lowerCamelCase : List[Any] = match.groups()[0]
if "," not in imports:
return f'''[{imports}]'''
_lowerCamelCase : Optional[int] = [part.strip().replace('"' , '' ) for part in imports.split(',' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
_lowerCamelCase : List[Any] = keys[:-1]
return "[" + ", ".join([f'''\"{k}\"''' for k in sort_objects(a__ )] ) + "]"
_lowerCamelCase : Dict = import_statement.split('\n' )
if len(a__ ) > 3:
# Here we have to sort internal imports that are on several lines (one per name):
# key: [
# "object1",
# "object2",
# ...
# ]
# We may have to ignore one or two lines on each side.
_lowerCamelCase : Dict = 2 if lines[1].strip() == '''[''' else 1
_lowerCamelCase : Dict = [(i, _re_strip_line.search(a__ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )]
_lowerCamelCase : Union[str, Any] = sort_objects(a__ , key=lambda lowercase__ : x[1] )
_lowerCamelCase : int = [lines[x[0] + idx] for x in sorted_indices]
return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] )
elif len(a__ ) == 3:
# Here we have to sort internal imports that are on one separate line:
# key: [
# "object1", "object2", ...
# ]
if _re_bracket_content.search(lines[1] ) is not None:
_lowerCamelCase : str = _re_bracket_content.sub(_replace , lines[1] )
else:
_lowerCamelCase : Any = [part.strip().replace('"' , '' ) for part in lines[1].split(',' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
_lowerCamelCase : Dict = keys[:-1]
_lowerCamelCase : List[str] = get_indent(lines[1] ) + ''', '''.join([f'''\"{k}\"''' for k in sort_objects(a__ )] )
return "\n".join(a__ )
else:
# Finally we have to deal with imports fitting on one line
_lowerCamelCase : str = _re_bracket_content.sub(_replace , a__ )
return import_statement
def _snake_case ( lowercase__ , lowercase__=True ):
with open(a__ , encoding='utf-8' ) as f:
_lowerCamelCase : List[Any] = f.read()
if "_import_structure" not in code:
return
# Blocks of indent level 0
_lowerCamelCase : Tuple = split_code_in_indented_blocks(
a__ , start_prompt='_import_structure = {' , end_prompt='if TYPE_CHECKING:' )
# We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt).
for block_idx in range(1 , len(a__ ) - 1 ):
# Check if the block contains some `_import_structure`s thingy to sort.
_lowerCamelCase : str = main_blocks[block_idx]
_lowerCamelCase : str = block.split('\n' )
# Get to the start of the imports.
_lowerCamelCase : str = 0
while line_idx < len(a__ ) and "_import_structure" not in block_lines[line_idx]:
# Skip dummy import blocks
if "import dummy" in block_lines[line_idx]:
_lowerCamelCase : Tuple = len(a__ )
else:
line_idx += 1
if line_idx >= len(a__ ):
continue
# Ignore beginning and last line: they don't contain anything.
_lowerCamelCase : Optional[Any] = '''\n'''.join(block_lines[line_idx:-1] )
_lowerCamelCase : Optional[Any] = get_indent(block_lines[1] )
# Slit the internal block into blocks of indent level 1.
_lowerCamelCase : Optional[Any] = split_code_in_indented_blocks(a__ , indent_level=a__ )
# We have two categories of import key: list or _import_structure[key].append/extend
_lowerCamelCase : Optional[Any] = _re_direct_key if '''_import_structure = {''' in block_lines[0] else _re_indirect_key
# Grab the keys, but there is a trap: some lines are empty or just comments.
_lowerCamelCase : Dict = [(pattern.search(a__ ).groups()[0] if pattern.search(a__ ) is not None else None) for b in internal_blocks]
# We only sort the lines with a key.
_lowerCamelCase : Any = [(i, key) for i, key in enumerate(a__ ) if key is not None]
_lowerCamelCase : Union[str, Any] = [x[0] for x in sorted(a__ , key=lambda lowercase__ : x[1] )]
# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.
_lowerCamelCase : Optional[Any] = 0
_lowerCamelCase : str = []
for i in range(len(a__ ) ):
if keys[i] is None:
reorderded_blocks.append(internal_blocks[i] )
else:
_lowerCamelCase : int = sort_objects_in_import(internal_blocks[sorted_indices[count]] )
reorderded_blocks.append(a__ )
count += 1
# And we put our main block back together with its first and last line.
_lowerCamelCase : Union[str, Any] = '''\n'''.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] )
if code != "\n".join(a__ ):
if check_only:
return True
else:
print(f'''Overwriting {file}.''' )
with open(a__ , 'w' , encoding='utf-8' ) as f:
f.write('\n'.join(a__ ) )
def _snake_case ( lowercase__=True ):
_lowerCamelCase : Tuple = []
for root, _, files in os.walk(a__ ):
if "__init__.py" in files:
_lowerCamelCase : str = sort_imports(os.path.join(a__ , '__init__.py' ) , check_only=a__ )
if result:
_lowerCamelCase : str = [os.path.join(a__ , '__init__.py' )]
if len(a__ ) > 0:
raise ValueError(f'''Would overwrite {len(a__ )} files, run `make style`.''' )
if __name__ == "__main__":
lowercase__ = argparse.ArgumentParser()
parser.add_argument("""--check_only""", action="""store_true""", help="""Whether to only check or fix style.""")
lowercase__ = parser.parse_args()
sort_imports_in_all_inits(check_only=args.check_only)
from __future__ import annotations
from math import pi
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :float , SCREAMING_SNAKE_CASE :float , SCREAMING_SNAKE_CASE :float ) -> dict[str, float]:
if (inductance, frequency, reactance).count(0 ) != 1:
raise ValueError("""One and only one argument must be 0""" )
if inductance < 0:
raise ValueError("""Inductance cannot be negative""" )
if frequency < 0:
raise ValueError("""Frequency cannot be negative""" )
if reactance < 0:
raise ValueError("""Inductive reactance cannot be negative""" )
if inductance == 0:
return {"inductance": reactance / (2 * pi * frequency)}
elif frequency == 0:
return {"frequency": reactance / (2 * pi * inductance)}
elif reactance == 0:
return {"reactance": 2 * pi * frequency * inductance}
else:
raise ValueError("""Exactly one argument must be 0""" )
if __name__ == "__main__":
import doctest
doctest.testmod()
232
from math import isqrt
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int ) -> list[int]:
__lowerCAmelCase : Tuple = [True] * max_number
for i in range(2 , isqrt(max_number - 1 ) + 1 ):
if is_prime[i]:
for j in range(i**2 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
__lowerCAmelCase : Tuple = False
return [i for i in range(2 , SCREAMING_SNAKE_CASE ) if is_prime[i]]
def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :int = 10**8 ) -> int:
__lowerCAmelCase : int = calculate_prime_numbers(max_number // 2 )
__lowerCAmelCase : List[Any] = 0
__lowerCAmelCase : List[str] = 0
__lowerCAmelCase : List[Any] = len(SCREAMING_SNAKE_CASE ) - 1
while left <= right:
while prime_numbers[left] * prime_numbers[right] >= max_number:
right -= 1
semiprimes_count += right - left + 1
left += 1
return semiprimes_count
if __name__ == "__main__":
print(f'''{solution() = }''')
"""simple docstring"""
from collections.abc import Callable
from math import pi, sqrt
from random import uniform
from statistics import mean
def a__ ( SCREAMING_SNAKE_CASE : int ):
'''simple docstring'''
def is_in_circle(SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float ) -> bool:
lowerCAmelCase : Any = sqrt((x**2) + (y**2) )
# Our circle has a radius of 1, so a distance
# greater than 1 would land outside the circle.
return distance_from_centre <= 1
# The proportion of guesses that landed in the circle
lowerCAmelCase : Any = mean(
int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) )
for _ in range(SCREAMING_SNAKE_CASE ) )
# The ratio of the area for circle to square is pi/4.
lowerCAmelCase : List[str] = proportion * 4
print(f"""The estimated value of pi is {pi_estimate}""" )
print(f"""The numpy value of pi is {pi}""" )
print(f"""The total error is {abs(pi - pi_estimate )}""" )
def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Callable[[float], float] , SCREAMING_SNAKE_CASE : float = 0.0 , SCREAMING_SNAKE_CASE : float = 1.0 , ):
'''simple docstring'''
return mean(
function_to_integrate(uniform(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) for _ in range(SCREAMING_SNAKE_CASE ) ) * (max_value - min_value)
def a__ ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : float = 0.0 , SCREAMING_SNAKE_CASE : float = 1.0 ):
'''simple docstring'''
def identity_function(SCREAMING_SNAKE_CASE : float ) -> float:
return x
lowerCAmelCase : Union[str, Any] = area_under_curve_estimator(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
lowerCAmelCase : Optional[int] = (max_value * max_value - min_value * min_value) / 2
print("******************" )
print(f"""Estimating area under y=x where x varies from {min_value} to {max_value}""" )
print(f"""Estimated value is {estimated_value}""" )
print(f"""Expected value is {expected_value}""" )
print(f"""Total error is {abs(estimated_value - expected_value )}""" )
print("******************" )
def a__ ( SCREAMING_SNAKE_CASE : int ):
'''simple docstring'''
def function_to_integrate(SCREAMING_SNAKE_CASE : float ) -> float:
return sqrt(4.0 - x * x )
lowerCAmelCase : Dict = area_under_curve_estimator(
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 0.0 , 2.0 )
print("******************" )
print("Estimating pi using area_under_curve_estimator" )
print(f"""Estimated value is {estimated_value}""" )
print(f"""Expected value is {pi}""" )
print(f"""Total error is {abs(estimated_value - pi )}""" )
print("******************" )
if __name__ == "__main__":
import doctest
doctest.testmod()
133
"""simple docstring"""
import re
from filelock import FileLock
try:
import nltk
lowerCAmelCase__ = True
except (ImportError, ModuleNotFoundError):
lowerCAmelCase__ = False
if NLTK_AVAILABLE:
with FileLock('''.lock''') as lock:
nltk.download('''punkt''', quiet=True)
def a__ ( SCREAMING_SNAKE_CASE : str ):
'''simple docstring'''
re.sub("<n>" , "" , SCREAMING_SNAKE_CASE ) # remove pegasus newline char
assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)"
return "\n".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE ) )
import argparse
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
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing the experiment tracking capability,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
# - single CPU or single GPU
# - multi GPUS (using PyTorch distributed mode)
# - (multi) TPUs
# - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################
lowercase : Any = 16
lowercase : Optional[int] = 32
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Accelerator , _lowerCamelCase : int = 16) -> int:
'''simple docstring'''
__UpperCamelCase : Any = AutoTokenizer.from_pretrained("bert-base-cased")
__UpperCamelCase : Optional[Any] = load_dataset("glue" , "mrpc")
def tokenize_function(_lowerCamelCase : Dict):
# max_length=None => use the model max length (it's actually the default)
__UpperCamelCase : List[str] = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_lowerCamelCase , max_length=_lowerCamelCase)
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
__UpperCamelCase : Optional[int] = datasets.map(
_lowerCamelCase , batched=_lowerCamelCase , remove_columns=["idx", "sentence1", "sentence2"] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
__UpperCamelCase : List[str] = tokenized_datasets.rename_column("label" , "labels")
def collate_fn(_lowerCamelCase : Union[str, Any]):
# On TPU it's best to pad everything to the same length or training will be very slow.
__UpperCamelCase : str = 128 if accelerator.distributed_type == DistributedType.TPU else None
# When using mixed precision we want round multiples of 8/16
if accelerator.mixed_precision == "fp8":
__UpperCamelCase : Optional[Any] = 16
elif accelerator.mixed_precision != "no":
__UpperCamelCase : Dict = 8
else:
__UpperCamelCase : Optional[Any] = None
return tokenizer.pad(
_lowerCamelCase , padding="longest" , max_length=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_tensors="pt" , )
# Instantiate dataloaders.
__UpperCamelCase : Optional[Any] = DataLoader(
tokenized_datasets["train"] , shuffle=_lowerCamelCase , collate_fn=_lowerCamelCase , batch_size=_lowerCamelCase)
__UpperCamelCase : int = DataLoader(
tokenized_datasets["validation"] , shuffle=_lowerCamelCase , collate_fn=_lowerCamelCase , batch_size=_lowerCamelCase)
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
lowercase : Union[str, Any] = mocked_dataloaders # noqa: F811
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Union[str, Any]) -> str:
'''simple docstring'''
if os.environ.get("TESTING_MOCKED_DATALOADERS" , _lowerCamelCase) == "1":
__UpperCamelCase : List[str] = 2
# Initialize Accelerator
# New Code #
# We pass in "all" to `log_with` to grab all available trackers in the environment
# Note: If using a custom `Tracker` class, should be passed in here such as:
# >>> log_with = ["all", MyCustomTrackerClassInstance()]
if args.with_tracking:
__UpperCamelCase : Union[str, Any] = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir)
else:
__UpperCamelCase : Optional[Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision)
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__UpperCamelCase : List[str] = config["lr"]
__UpperCamelCase : Optional[Any] = int(config["num_epochs"])
__UpperCamelCase : List[Any] = int(config["seed"])
__UpperCamelCase : Any = int(config["batch_size"])
set_seed(_lowerCamelCase)
__UpperCamelCase , __UpperCamelCase : List[Any] = get_dataloaders(_lowerCamelCase , _lowerCamelCase)
__UpperCamelCase : List[str] = evaluate.load("glue" , "mrpc")
# If the batch size is too big we use gradient accumulation
__UpperCamelCase : Union[str, Any] = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
__UpperCamelCase : List[Any] = batch_size // MAX_GPU_BATCH_SIZE
__UpperCamelCase : Union[str, Any] = MAX_GPU_BATCH_SIZE
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__UpperCamelCase : str = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_lowerCamelCase)
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
__UpperCamelCase : Optional[int] = model.to(accelerator.device)
# Instantiate optimizer
__UpperCamelCase : List[str] = AdamW(params=model.parameters() , lr=_lowerCamelCase)
# Instantiate scheduler
__UpperCamelCase : Union[str, Any] = get_linear_schedule_with_warmup(
optimizer=_lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(_lowerCamelCase) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase : Union[str, Any] = accelerator.prepare(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase)
# New Code #
# We need to initialize the trackers we use. Overall configurations can also be stored
if args.with_tracking:
__UpperCamelCase : Dict = os.path.split(_lowerCamelCase)[-1].split(".")[0]
accelerator.init_trackers(_lowerCamelCase , _lowerCamelCase)
# Now we train the model
for epoch in range(_lowerCamelCase):
model.train()
# New Code #
# For our tracking example, we will log the total loss of each epoch
if args.with_tracking:
__UpperCamelCase : Tuple = 0
for step, batch in enumerate(_lowerCamelCase):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device)
__UpperCamelCase : Dict = model(**_lowerCamelCase)
__UpperCamelCase : Any = outputs.loss
# New Code #
if args.with_tracking:
total_loss += loss.detach().float()
__UpperCamelCase : List[Any] = loss / gradient_accumulation_steps
accelerator.backward(_lowerCamelCase)
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(_lowerCamelCase):
# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
batch.to(accelerator.device)
with torch.no_grad():
__UpperCamelCase : Union[str, Any] = model(**_lowerCamelCase)
__UpperCamelCase : str = outputs.logits.argmax(dim=-1)
__UpperCamelCase , __UpperCamelCase : Dict = accelerator.gather_for_metrics((predictions, batch["labels"]))
metric.add_batch(
predictions=_lowerCamelCase , references=_lowerCamelCase , )
__UpperCamelCase : Optional[Any] = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F'epoch {epoch}:' , _lowerCamelCase)
# New Code #
# To actually log, we call `Accelerator.log`
# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`
if args.with_tracking:
accelerator.log(
{
"accuracy": eval_metric["accuracy"],
"f1": eval_metric["f1"],
"train_loss": total_loss.item() / len(_lowerCamelCase),
"epoch": epoch,
} , step=_lowerCamelCase , )
# New Code #
# When a run is finished, you should call `accelerator.end_training()`
# to close all of the open trackers
if args.with_tracking:
accelerator.end_training()
def _SCREAMING_SNAKE_CASE ( ) -> Optional[int]:
'''simple docstring'''
__UpperCamelCase : str = argparse.ArgumentParser(description="Simple example of training script.")
parser.add_argument(
"--mixed_precision" , type=_lowerCamelCase , default=_lowerCamelCase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose"
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
"and an Nvidia Ampere GPU." , )
parser.add_argument("--cpu" , action="https://huggingface.co/datasets/infinityofspace/python_codestyles-mixed1-500/viewer/default/store_true" , help="If passed, will train on the CPU.")
parser.add_argument(
"--with_tracking" , action="https://huggingface.co/datasets/infinityofspace/python_codestyles-mixed1-500/viewer/default/store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , )
parser.add_argument(
"--project_dir" , type=_lowerCamelCase , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , )
__UpperCamelCase : Union[str, Any] = parser.parse_args()
__UpperCamelCase : str = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
training_function(_lowerCamelCase , _lowerCamelCase)
if __name__ == "__main__":
main()
import unittest
import numpy as np
def SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = None , ) -> np.ndarray:
lowerCAmelCase = np.shape(snake_case__ )
lowerCAmelCase = np.shape(snake_case__ )
lowerCAmelCase = np.shape(snake_case__ )
if shape_a[0] != shape_b[0]:
lowerCAmelCase = (
'''Expected the same number of rows for A and B. '''
f"Instead found A of size {shape_a} and B of size {shape_b}"
)
raise ValueError(snake_case__ )
if shape_b[1] != shape_c[1]:
lowerCAmelCase = (
'''Expected the same number of columns for B and C. '''
f"Instead found B of size {shape_b} and C of size {shape_c}"
)
raise ValueError(snake_case__ )
lowerCAmelCase = pseudo_inv
if a_inv is None:
try:
lowerCAmelCase = np.linalg.inv(snake_case__ )
except np.linalg.LinAlgError:
raise ValueError(
'''Input matrix A is not invertible. Cannot compute Schur complement.''' )
return mat_c - mat_b.T @ a_inv @ mat_b
class lowercase_ ( unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE_ ( self ) ->None:
lowerCAmelCase = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
lowerCAmelCase = np.array([[0, 3], [3, 0], [2, 3]] )
lowerCAmelCase = np.array([[2, 1], [6, 3]] )
lowerCAmelCase = schur_complement(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
lowerCAmelCase = np.block([[a, b], [b.T, c]] )
lowerCAmelCase = np.linalg.det(__SCREAMING_SNAKE_CASE )
lowerCAmelCase = np.linalg.det(__SCREAMING_SNAKE_CASE )
lowerCAmelCase = np.linalg.det(__SCREAMING_SNAKE_CASE )
self.assertAlmostEqual(__SCREAMING_SNAKE_CASE , det_a * det_s )
def SCREAMING_SNAKE_CASE_ ( self ) ->None:
lowerCAmelCase = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
lowerCAmelCase = np.array([[0, 3], [3, 0], [2, 3]] )
lowerCAmelCase = np.array([[2, 1], [6, 3]] )
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
schur_complement(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
def SCREAMING_SNAKE_CASE_ ( self ) ->None:
lowerCAmelCase = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
lowerCAmelCase = np.array([[0, 3], [3, 0], [2, 3]] )
lowerCAmelCase = np.array([[2, 1, 3], [6, 3, 5]] )
with self.assertRaises(__SCREAMING_SNAKE_CASE ):
schur_complement(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
unittest.main()
338
0
from __future__ import annotations
import time
import numpy as np
lowercase : Optional[Any] = [8, 5, 9, 7]
lowercase : Union[str, Any] = [
[2, 0, 1, 1],
[0, 1, 2, 1],
[4, 0, 0, 3],
[0, 2, 1, 0],
[1, 0, 3, 0],
]
lowercase : Optional[Any] = [
[3, 2, 1, 4],
[0, 2, 5, 2],
[5, 1, 0, 5],
[1, 5, 3, 0],
[3, 0, 3, 3],
]
class __snake_case :
def __init__( self ,snake_case ,snake_case ,snake_case ,):
'''simple docstring'''
lowercase : Any = claim_vector
lowercase : Union[str, Any] = allocated_resources_table
lowercase : Dict = maximum_claim_table
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
return [
sum(p_item[i] for p_item in self.__allocated_resources_table )
for i in range(len(self.__allocated_resources_table[0] ) )
]
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
return np.array(self.__claim_vector ) - np.array(
self.__processes_resource_summation() )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
return [
list(np.array(self.__maximum_claim_table[i] ) - np.array(snake_case ) )
for i, allocated_resource in enumerate(self.__allocated_resources_table )
]
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
return {self.__need().index(snake_case ): i for i in self.__need()}
def _SCREAMING_SNAKE_CASE ( self ,**snake_case ):
'''simple docstring'''
lowercase : Any = self.__need()
lowercase : List[str] = self.__allocated_resources_table
lowercase : int = self.__available_resources()
lowercase : int = self.__need_index_manager()
for kw, val in kwargs.items():
if kw and val is True:
self.__pretty_data()
print("""_""" * 50 + """\n""" )
while need_list:
lowercase : List[str] = False
for each_need in need_list:
lowercase : Optional[Any] = True
for index, need in enumerate(snake_case ):
if need > available_resources[index]:
lowercase : Optional[Any] = False
break
if execution:
lowercase : Optional[Any] = True
# get the original index of the process from ind_ctrl db
for original_need_index, need_clone in need_index_manager.items():
if each_need == need_clone:
lowercase : Union[str, Any] = original_need_index
print(f"Process {process_number + 1} is executing." )
# remove the process run from stack
need_list.remove(snake_case )
# update available/freed resources stack
lowercase : Dict = np.array(snake_case ) + np.array(
alloc_resources_table[process_number] )
print(
"""Updated available resource stack for processes: """
+ """ """.join([str(snake_case ) for x in available_resources] ) )
break
if safe:
print("""The process is in a safe state.\n""" )
else:
print("""System in unsafe state. Aborting...\n""" )
break
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
print(""" """ * 9 + """Allocated Resource Table""" )
for item in self.__allocated_resources_table:
print(
f"P{self.__allocated_resources_table.index(snake_case ) + 1}"
+ """ """.join(f"{it:>8}" for it in item )
+ """\n""" )
print(""" """ * 9 + """System Resource Table""" )
for item in self.__maximum_claim_table:
print(
f"P{self.__maximum_claim_table.index(snake_case ) + 1}"
+ """ """.join(f"{it:>8}" for it in item )
+ """\n""" )
print(
"""Current Usage by Active Processes: """
+ """ """.join(str(snake_case ) for x in self.__claim_vector ) )
print(
"""Initial Available Resources: """
+ """ """.join(str(snake_case ) for x in self.__available_resources() ) )
time.sleep(1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
359
import os
import re
import shutil
from argparse import ArgumentParser, Namespace
from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger
lowercase : Tuple = """<<<<<<< This should probably be modified because it mentions: """
lowercase : Any = """=======
>>>>>>>
"""
lowercase : List[str] = [
"""TextEncoderConfig""",
"""ByteTextEncoder""",
"""SubwordTextEncoder""",
"""encoder_config""",
"""maybe_build_from_corpus""",
"""manual_dir""",
]
lowercase : Any = [
# (pattern, replacement)
# Order is important here for some replacements
(R"""tfds\.core""", R"""datasets"""),
(R"""tf\.io\.gfile\.GFile""", R"""open"""),
(R"""tf\.([\w\d]+)""", R"""datasets.Value('\1')"""),
(R"""tfds\.features\.Text\(\)""", R"""datasets.Value('string')"""),
(R"""tfds\.features\.Text\(""", R"""datasets.Value('string'),"""),
(R"""features\s*=\s*tfds.features.FeaturesDict\(""", R"""features=datasets.Features("""),
(R"""tfds\.features\.FeaturesDict\(""", R"""dict("""),
(R"""The TensorFlow Datasets Authors""", R"""The TensorFlow Datasets Authors and the HuggingFace Datasets Authors"""),
(R"""tfds\.""", R"""datasets."""),
(R"""dl_manager\.manual_dir""", R"""self.config.data_dir"""),
(R"""self\.builder_config""", R"""self.config"""),
]
def _snake_case( SCREAMING_SNAKE_CASE__ ) -> List[Any]:
return ConvertCommand(args.tfds_path , args.datasets_directory )
class __snake_case ( lowerCAmelCase ):
@staticmethod
def _SCREAMING_SNAKE_CASE ( snake_case ):
'''simple docstring'''
lowercase : str = parser.add_parser(
"""convert""" ,help="""Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset.""" ,)
train_parser.add_argument(
"""--tfds_path""" ,type=snake_case ,required=snake_case ,help="""Path to a TensorFlow Datasets folder to convert or a single tfds file to convert.""" ,)
train_parser.add_argument(
"""--datasets_directory""" ,type=snake_case ,required=snake_case ,help="""Path to the HuggingFace Datasets folder.""" )
train_parser.set_defaults(func=snake_case )
def __init__( self ,snake_case ,snake_case ,*snake_case ):
'''simple docstring'''
lowercase : Optional[Any] = get_logger("""datasets-cli/converting""" )
lowercase : Optional[int] = tfds_path
lowercase : Dict = datasets_directory
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
if os.path.isdir(self._tfds_path ):
lowercase : List[str] = os.path.abspath(self._tfds_path )
elif os.path.isfile(self._tfds_path ):
lowercase : Tuple = os.path.dirname(self._tfds_path )
else:
raise ValueError("""--tfds_path is neither a directory nor a file. Please check path.""" )
lowercase : Optional[int] = os.path.abspath(self._datasets_directory )
self._logger.info(f"Converting datasets from {abs_tfds_path} to {abs_datasets_path}" )
lowercase : List[Any] = []
lowercase : Optional[int] = []
lowercase : Dict = {}
if os.path.isdir(self._tfds_path ):
lowercase : int = os.listdir(snake_case )
else:
lowercase : List[Any] = [os.path.basename(self._tfds_path )]
for f_name in file_names:
self._logger.info(f"Looking at file {f_name}" )
lowercase : List[Any] = os.path.join(snake_case ,snake_case )
lowercase : List[str] = os.path.join(snake_case ,snake_case )
if not os.path.isfile(snake_case ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
self._logger.info("""Skipping file""" )
continue
with open(snake_case ,encoding="""utf-8""" ) as f:
lowercase : str = f.readlines()
lowercase : Union[str, Any] = []
lowercase : Optional[Any] = False
lowercase : Optional[Any] = False
lowercase : Optional[int] = []
for line in lines:
lowercase : int = line
# Convert imports
if "import tensorflow.compat.v2 as tf" in out_line:
continue
elif "@tfds.core" in out_line:
continue
elif "builder=self" in out_line:
continue
elif "import tensorflow_datasets.public_api as tfds" in out_line:
lowercase : Union[str, Any] = """import datasets\n"""
elif "import tensorflow" in out_line:
# order is important here
lowercase : List[Any] = """"""
continue
elif "from absl import logging" in out_line:
lowercase : Optional[int] = """from datasets import logging\n"""
elif "getLogger" in out_line:
lowercase : Any = out_line.replace("""getLogger""" ,"""get_logger""" )
elif any(expression in out_line for expression in TO_HIGHLIGHT ):
lowercase : Optional[Any] = True
lowercase : Optional[Any] = list(filter(lambda snake_case : e in out_line ,snake_case ) )
out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(snake_case ) + """\n""" )
out_lines.append(snake_case )
out_lines.append(snake_case )
continue
else:
for pattern, replacement in TO_CONVERT:
lowercase : Union[str, Any] = re.sub(snake_case ,snake_case ,snake_case )
# Take care of saving utilities (to later move them together with main script)
if "tensorflow_datasets" in out_line:
lowercase : Dict = re.match(r"""from\stensorflow_datasets.*import\s([^\.\r\n]+)""" ,snake_case )
tfds_imports.extend(imp.strip() for imp in match.group(1 ).split(""",""" ) )
lowercase : Optional[int] = """from . import """ + match.group(1 )
# Check we have not forget anything
if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
raise ValueError(f"Error converting {out_line.strip()}" )
if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
lowercase : Any = True
out_lines.append(snake_case )
if is_builder or "wmt" in f_name:
# We create a new directory for each dataset
lowercase : Union[str, Any] = f_name.replace(""".py""" ,"""""" )
lowercase : Optional[Any] = os.path.join(snake_case ,snake_case )
lowercase : List[str] = os.path.join(snake_case ,snake_case )
os.makedirs(snake_case ,exist_ok=snake_case )
self._logger.info(f"Adding directory {output_dir}" )
imports_to_builder_map.update({imp: output_dir for imp in tfds_imports} )
else:
# Utilities will be moved at the end
utils_files.append(snake_case )
if needs_manual_update:
with_manual_update.append(snake_case )
with open(snake_case ,"""w""" ,encoding="""utf-8""" ) as f:
f.writelines(snake_case )
self._logger.info(f"Converted in {output_file}" )
for utils_file in utils_files:
try:
lowercase : Optional[int] = os.path.basename(snake_case )
lowercase : int = imports_to_builder_map[f_name.replace(""".py""" ,"""""" )]
self._logger.info(f"Moving {dest_folder} to {utils_file}" )
shutil.copy(snake_case ,snake_case )
except KeyError:
self._logger.error(f"Cannot find destination folder for {utils_file}. Please copy manually." )
if with_manual_update:
for file_path in with_manual_update:
self._logger.warning(
f"You need to manually update file {file_path} to remove configurations using 'TextEncoderConfig'." )
285
0
'''simple docstring'''
lowercase_ = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"
lowercase_ = [{"type": "code", "content": INSTALL_CONTENT}]
lowercase_ = {
"{processor_class}": "FakeProcessorClass",
"{model_class}": "FakeModelClass",
"{object_class}": "FakeObjectClass",
}
211
'''simple docstring'''
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import flax
import jax
import jax.numpy as jnp
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
CommonSchedulerState,
FlaxKarrasDiffusionSchedulers,
FlaxSchedulerMixin,
FlaxSchedulerOutput,
add_noise_common,
get_velocity_common,
)
@flax.struct.dataclass
class __A :
'''simple docstring'''
__lowerCamelCase : CommonSchedulerState
# setable values
__lowerCamelCase : jnp.ndarray
__lowerCamelCase : jnp.ndarray
__lowerCamelCase : Optional[int] = None
@classmethod
def a__ (cls , A , A , A ) -> str:
"""simple docstring"""
return cls(common=A , init_noise_sigma=A , timesteps=A )
@dataclass
class __A ( A ):
'''simple docstring'''
__lowerCamelCase : DDPMSchedulerState
class __A ( A , A ):
'''simple docstring'''
__lowerCamelCase : Dict = [e.name for e in FlaxKarrasDiffusionSchedulers]
__lowerCamelCase : jnp.dtype
@property
def a__ (self ) -> List[str]:
"""simple docstring"""
return True
@register_to_config
def __init__(self , A = 1_000 , A = 0.0001 , A = 0.02 , A = "linear" , A = None , A = "fixed_small" , A = True , A = "epsilon" , A = jnp.floataa , ) -> Union[str, Any]:
"""simple docstring"""
_a = dtype
def a__ (self , A = None ) -> DDPMSchedulerState:
"""simple docstring"""
if common is None:
_a = CommonSchedulerState.create(self )
# standard deviation of the initial noise distribution
_a = jnp.array(1.0 , dtype=self.dtype )
_a = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1]
return DDPMSchedulerState.create(
common=A , init_noise_sigma=A , timesteps=A , )
def a__ (self , A , A , A = None ) -> jnp.ndarray:
"""simple docstring"""
return sample
def a__ (self , A , A , A = () ) -> DDPMSchedulerState:
"""simple docstring"""
_a = self.config.num_train_timesteps // num_inference_steps
# creates integer timesteps by multiplying by ratio
# rounding to avoid issues when num_inference_step is power of 3
_a = (jnp.arange(0 , A ) * step_ratio).round()[::-1]
return state.replace(
num_inference_steps=A , timesteps=A , )
def a__ (self , A , A , A=None , A=None ) -> int:
"""simple docstring"""
_a = state.common.alphas_cumprod[t]
_a = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
# For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
# and sample from it to get previous sample
# x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
_a = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t]
if variance_type is None:
_a = self.config.variance_type
# hacks - were probably added for training stability
if variance_type == "fixed_small":
_a = jnp.clip(A , a_min=1E-20 )
# for rl-diffuser https://arxiv.org/abs/2205.09991
elif variance_type == "fixed_small_log":
_a = jnp.log(jnp.clip(A , a_min=1E-20 ) )
elif variance_type == "fixed_large":
_a = state.common.betas[t]
elif variance_type == "fixed_large_log":
# Glide max_log
_a = jnp.log(state.common.betas[t] )
elif variance_type == "learned":
return predicted_variance
elif variance_type == "learned_range":
_a = variance
_a = state.common.betas[t]
_a = (predicted_variance + 1) / 2
_a = frac * max_log + (1 - frac) * min_log
return variance
def a__ (self , A , A , A , A , A = None , A = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]:
"""simple docstring"""
_a = timestep
if key is None:
_a = jax.random.PRNGKey(0 )
if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]:
_a , _a = jnp.split(A , sample.shape[1] , axis=1 )
else:
_a = None
# 1. compute alphas, betas
_a = state.common.alphas_cumprod[t]
_a = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) )
_a = 1 - alpha_prod_t
_a = 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 self.config.prediction_type == "epsilon":
_a = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif self.config.prediction_type == "sample":
_a = model_output
elif self.config.prediction_type == "v_prediction":
_a = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
else:
raise ValueError(
f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` '''
''' for the FlaxDDPMScheduler.''' )
# 3. Clip "predicted x_0"
if self.config.clip_sample:
_a = jnp.clip(A , -1 , 1 )
# 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
_a = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t
_a = state.common.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
_a = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
def random_variance():
_a = jax.random.split(A , num=1 )
_a = jax.random.normal(A , shape=model_output.shape , dtype=self.dtype )
return (self._get_variance(A , A , predicted_variance=A ) ** 0.5) * noise
_a = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) )
_a = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample, state)
return FlaxDDPMSchedulerOutput(prev_sample=A , state=A )
def a__ (self , A , A , A , A , ) -> jnp.ndarray:
"""simple docstring"""
return add_noise_common(state.common , A , A , A )
def a__ (self , A , A , A , A , ) -> jnp.ndarray:
"""simple docstring"""
return get_velocity_common(state.common , A , A , A )
def __len__(self ) -> Tuple:
"""simple docstring"""
return self.config.num_train_timesteps
211
1
"""simple docstring"""
from __future__ import annotations
import os
from collections.abc import Mapping
__lowercase = tuple[int, int]
class _lowercase :
"""simple docstring"""
def __init__( self : Optional[int] , UpperCamelCase__ : set[int] , UpperCamelCase__ : Mapping[EdgeT, int] ) -> None:
'''simple docstring'''
__UpperCamelCase =vertices
__UpperCamelCase ={
(min(UpperCamelCase__ ), max(UpperCamelCase__ )): weight for edge, weight in edges.items()
}
def UpperCAmelCase_ ( self : str , UpperCamelCase__ : EdgeT , UpperCamelCase__ : int ) -> None:
'''simple docstring'''
self.vertices.add(edge[0] )
self.vertices.add(edge[1] )
__UpperCamelCase =weight
def UpperCAmelCase_ ( self : List[Any] ) -> Graph:
'''simple docstring'''
__UpperCamelCase =Graph({min(self.vertices )} , {} )
__UpperCamelCase =42
__UpperCamelCase =42
__UpperCamelCase =42
__UpperCamelCase =42
while len(subgraph.vertices ) < len(self.vertices ):
__UpperCamelCase =max(self.edges.values() ) + 1
for edge, weight in self.edges.items():
if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices):
if weight < min_weight:
__UpperCamelCase =edge
__UpperCamelCase =weight
subgraph.add_edge(UpperCamelCase__ , UpperCamelCase__ )
return subgraph
def lowerCAmelCase (__UpperCamelCase : str = "p107_network.txt" ):
"""simple docstring"""
__UpperCamelCase =os.path.abspath(os.path.dirname(__UpperCamelCase ) )
__UpperCamelCase =os.path.join(__UpperCamelCase , __UpperCamelCase )
__UpperCamelCase ={}
__UpperCamelCase =42
__UpperCamelCase =42
__UpperCamelCase =42
with open(__UpperCamelCase ) as f:
__UpperCamelCase =f.read().strip().split('''\n''' )
__UpperCamelCase =[line.split(''',''' ) for line in data]
for edgea in range(1 , len(__UpperCamelCase ) ):
for edgea in range(__UpperCamelCase ):
if adjaceny_matrix[edgea][edgea] != "-":
__UpperCamelCase =int(adjaceny_matrix[edgea][edgea] )
__UpperCamelCase =Graph(set(range(len(__UpperCamelCase ) ) ) , __UpperCamelCase )
__UpperCamelCase =graph.prims_algorithm()
__UpperCamelCase =sum(graph.edges.values() )
__UpperCamelCase =sum(subgraph.edges.values() )
return initial_total - optimal_total
if __name__ == "__main__":
print(f'''{solution() = }''')
85
"""simple docstring"""
def lowerCAmelCase (__UpperCamelCase : Dict , __UpperCamelCase : Optional[Any] ):
"""simple docstring"""
__UpperCamelCase =[0 for i in range(r + 1 )]
# nc0 = 1
__UpperCamelCase =1
for i in range(1 , n + 1 ):
# to compute current row from previous row.
__UpperCamelCase =min(__UpperCamelCase , __UpperCamelCase )
while j > 0:
c[j] += c[j - 1]
j -= 1
return c[r]
print(binomial_coefficient(n=10, r=5))
85
1
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
from ...utils import OptionalDependencyNotAvailable
lowerCAmelCase = {'configuration_dpt': ['DPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DPTConfig']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase = ['DPTFeatureExtractor']
lowerCAmelCase = ['DPTImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase = [
'DPT_PRETRAINED_MODEL_ARCHIVE_LIST',
'DPTForDepthEstimation',
'DPTForSemanticSegmentation',
'DPTModel',
'DPTPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_dpt import DPTFeatureExtractor
from .image_processing_dpt import DPTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_dpt import (
DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
DPTForDepthEstimation,
DPTForSemanticSegmentation,
DPTModel,
DPTPreTrainedModel,
)
else:
import sys
lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
110
def _a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
return credit_card_number.startswith(('''34''', '''35''', '''37''', '''4''', '''5''', '''6''') )
def _a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
lowercase__ = credit_card_number
lowercase__ = 0
lowercase__ = len(SCREAMING_SNAKE_CASE ) - 2
for i in range(SCREAMING_SNAKE_CASE , -1 , -2 ):
# double the value of every second digit
lowercase__ = int(cc_number[i] )
digit *= 2
# If doubling of a number results in a two digit number
# i.e greater than 9(e.g., 6 × 2 = 12),
# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
# to get a single digit number.
if digit > 9:
digit %= 10
digit += 1
lowercase__ = cc_number[:i] + str(SCREAMING_SNAKE_CASE ) + cc_number[i + 1 :]
total += digit
# Sum up the remaining digits
for i in range(len(SCREAMING_SNAKE_CASE ) - 1 , -1 , -2 ):
total += int(cc_number[i] )
return total % 10 == 0
def _a ( SCREAMING_SNAKE_CASE ):
"""simple docstring"""
lowercase__ = f'{credit_card_number} is an invalid credit card number because'
if not credit_card_number.isdigit():
print(f'{error_message} it has nonnumerical characters.' )
return False
if not 13 <= len(SCREAMING_SNAKE_CASE ) <= 16:
print(f'{error_message} of its length.' )
return False
if not validate_initial_digits(SCREAMING_SNAKE_CASE ):
print(f'{error_message} of its first two digits.' )
return False
if not luhn_validation(SCREAMING_SNAKE_CASE ):
print(f'{error_message} it fails the Luhn check.' )
return False
print(f'{credit_card_number} is a valid credit card number.' )
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
validate_credit_card_number('4111111111111111')
validate_credit_card_number('32323')
110
1
from timeit import timeit
__UpperCamelCase : Dict = {
'MALAYALAM': True,
'String': False,
'rotor': True,
'level': True,
'A': True,
'BB': True,
'ABC': False,
'amanaplanacanalpanama': True, # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())
def A ( _lowercase ):
SCREAMING_SNAKE_CASE : Any = 0
SCREAMING_SNAKE_CASE : str = len(_lowercase ) - 1
while start_i < end_i:
if s[start_i] == s[end_i]:
start_i += 1
end_i -= 1
else:
return False
return True
def A ( _lowercase ):
SCREAMING_SNAKE_CASE : Tuple = len(_lowercase ) // 2
SCREAMING_SNAKE_CASE : List[str] = len(_lowercase )
# We need to traverse till half of the length of string
# as we can get access of the i'th last element from
# i'th index.
# eg: [0,1,2,3,4,5] => 4th index can be accessed
# with the help of 1st index (i==n-i-1)
# where n is length of string
return all(s[i] == s[n - i - 1] for i in range(_lowercase ) )
def A ( _lowercase ):
if len(_lowercase ) <= 2:
return True
if s[0] == s[len(_lowercase ) - 1]:
return is_palindrome_recursive(s[1:-1] )
else:
return False
def A ( _lowercase ):
return s == s[::-1]
def A ( _lowercase ):
SCREAMING_SNAKE_CASE : Any = f"""all({name}(key) is value for key, value in test_data.items())"""
SCREAMING_SNAKE_CASE : str = f"""from __main__ import test_data, {name}"""
SCREAMING_SNAKE_CASE : List[Any] = 500_000
SCREAMING_SNAKE_CASE : List[Any] = timeit(stmt=_lowercase , setup=_lowercase , number=_lowercase )
print(f"""{name:<35} finished {number:,} runs in {result:.5f} seconds""" )
if __name__ == "__main__":
for key, value in test_data.items():
assert is_palindrome(key) is is_palindrome_recursive(key)
assert is_palindrome(key) is is_palindrome_slice(key)
print(f"""{key:21} {value}""")
print('a man a plan a canal panama')
# finished 500,000 runs in 0.46793 seconds
benchmark_function('is_palindrome_slice')
# finished 500,000 runs in 0.85234 seconds
benchmark_function('is_palindrome')
# finished 500,000 runs in 1.32028 seconds
benchmark_function('is_palindrome_recursive')
# finished 500,000 runs in 2.08679 seconds
benchmark_function('is_palindrome_traversal')
258
import os
from typing import List, Optional, Union
from ...tokenization_utils import PreTrainedTokenizer
from ...tokenization_utils_base import AddedToken
from ...utils import logging
__UpperCamelCase : Any = logging.get_logger(__name__)
__UpperCamelCase : Tuple = {'vocab_file': 'vocab.txt'}
__UpperCamelCase : Tuple = {
'vocab_file': {
'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt',
'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt',
},
}
__UpperCamelCase : Union[str, Any] = {
'facebook/esm2_t6_8M_UR50D': 1024,
'facebook/esm2_t12_35M_UR50D': 1024,
}
def A ( _lowercase ):
with open(_lowercase , '''r''' ) as f:
SCREAMING_SNAKE_CASE : Optional[int] = f.read().splitlines()
return [l.strip() for l in lines]
class lowercase__ ( UpperCamelCase_):
UpperCamelCase_ = VOCAB_FILES_NAMES
UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase_ = ["""input_ids""", """attention_mask"""]
def __init__( self : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple="<unk>" , UpperCamelCase__ : Union[str, Any]="<cls>" , UpperCamelCase__ : Dict="<pad>" , UpperCamelCase__ : str="<mask>" , UpperCamelCase__ : Any="<eos>" , **UpperCamelCase__ : int , ):
'''simple docstring'''
super().__init__(**UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = load_vocab_file(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : int = dict(enumerate(self.all_tokens ) )
SCREAMING_SNAKE_CASE : List[Any] = {tok: ind for ind, tok in enumerate(self.all_tokens )}
SCREAMING_SNAKE_CASE : Union[str, Any] = unk_token
SCREAMING_SNAKE_CASE : Any = cls_token
SCREAMING_SNAKE_CASE : List[str] = pad_token
SCREAMING_SNAKE_CASE : List[str] = mask_token
SCREAMING_SNAKE_CASE : Any = eos_token
SCREAMING_SNAKE_CASE : List[str] = self.all_tokens
self._create_trie(self.unique_no_split_tokens )
def __A ( self : Union[str, Any] , UpperCamelCase__ : int ):
'''simple docstring'''
return self._id_to_token.get(UpperCamelCase__ , self.unk_token )
def __A ( self : Dict , UpperCamelCase__ : str ):
'''simple docstring'''
return self._token_to_id.get(UpperCamelCase__ , self._token_to_id.get(self.unk_token ) )
def __A ( self : List[Any] , UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : List[Any] ):
'''simple docstring'''
return text.split()
def __A ( self : List[str] , UpperCamelCase__ : Dict=False ):
'''simple docstring'''
return len(self._id_to_token )
def __A ( self : Optional[Any] ):
'''simple docstring'''
return {token: i for i, token in enumerate(self.all_tokens )}
def __A ( self : Union[str, Any] , UpperCamelCase__ : str ):
'''simple docstring'''
return self._token_to_id.get(UpperCamelCase__ , self._token_to_id.get(self.unk_token ) )
def __A ( self : List[str] , UpperCamelCase__ : int ):
'''simple docstring'''
return self._id_to_token.get(UpperCamelCase__ , self.unk_token )
def __A ( self : str , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = [self.cls_token_id]
SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] # No sep token in ESM vocabulary
if token_ids_a is None:
if self.eos_token_id is None:
return cls + token_ids_a
else:
return cls + token_ids_a + sep
elif self.eos_token_id is None:
raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' )
return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token
def __A ( self : Union[str, Any] , UpperCamelCase__ : List , UpperCamelCase__ : Optional[List] = None , UpperCamelCase__ : bool = False ):
'''simple docstring'''
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
'''You should not supply a second sequence if the provided sequence of '''
'''ids is already formatted with special tokens for the model.''' )
return [1 if token in self.all_special_ids else 0 for token in token_ids_a]
SCREAMING_SNAKE_CASE : List[str] = [1] + ([0] * len(UpperCamelCase__ )) + [1]
if token_ids_a is not None:
mask += [0] * len(UpperCamelCase__ ) + [1]
return mask
def __A ( self : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[str] ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : str = os.path.join(UpperCamelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' )
with open(UpperCamelCase__ , '''w''' ) as f:
f.write('''\n'''.join(self.all_tokens ) )
return (vocab_file,)
@property
def __A ( self : Dict ):
'''simple docstring'''
return self.get_vocab_size(with_added_tokens=UpperCamelCase__ )
def __A ( self : str , UpperCamelCase__ : Union[List[str], List[AddedToken]] , UpperCamelCase__ : bool = False ):
'''simple docstring'''
return super()._add_tokens(UpperCamelCase__ , special_tokens=UpperCamelCase__ )
258
1
from __future__ import annotations
import string
from itertools import cycle, product
from pathlib import Path
_snake_case = (
string.ascii_letters + string.digits + string.punctuation + string.whitespace
)
_snake_case = [ord(letter) for letter in string.ascii_lowercase]
_snake_case = {ord(char) for char in VALID_CHARS}
_snake_case = ['''the''', '''be''', '''to''', '''of''', '''and''', '''in''', '''that''', '''have''']
def _UpperCamelCase ( snake_case__, snake_case__ ) -> str | None:
__UpperCAmelCase : Union[str, Any] = ""
__UpperCAmelCase : str = 42
__UpperCAmelCase : List[Any] = 42
__UpperCAmelCase : Optional[Any] = 42
for keychar, cipherchar in zip(cycle(UpperCamelCase_ ), UpperCamelCase_ ):
__UpperCAmelCase : Any = cipherchar ^ keychar
if decodedchar not in VALID_INTS:
return None
decoded += chr(UpperCamelCase_ )
return decoded
def _UpperCamelCase ( snake_case__ ) -> list[str]:
__UpperCAmelCase : Optional[Any] = []
for key in product(UpperCamelCase_, repeat=3 ):
__UpperCAmelCase : int = try_key(UpperCamelCase_, UpperCamelCase_ )
if encoded is not None:
possibles.append(UpperCamelCase_ )
return possibles
def _UpperCamelCase ( snake_case__, snake_case__ ) -> list[str]:
return [possible for possible in possibles if common_word in possible.lower()]
def _UpperCamelCase ( snake_case__ = "p059_cipher.txt" ) -> int:
__UpperCAmelCase : Dict = 42
__UpperCAmelCase : List[Any] = 42
__UpperCAmelCase : Tuple = 42
__UpperCAmelCase : int = 42
__UpperCAmelCase : List[str] = Path(UpperCamelCase_ ).parent.joinpath(UpperCamelCase_ ).read_text(encoding="utf-8" )
__UpperCAmelCase : Any = [int(UpperCamelCase_ ) for number in data.strip().split("," )]
__UpperCAmelCase : List[Any] = filter_valid_chars(UpperCamelCase_ )
for common_word in COMMON_WORDS:
__UpperCAmelCase : Union[str, Any] = filter_common_word(UpperCamelCase_, UpperCamelCase_ )
if len(UpperCamelCase_ ) == 1:
break
__UpperCAmelCase : Dict = possibles[0]
return sum(ord(UpperCamelCase_ ) for char in decoded_text )
if __name__ == "__main__":
print(F'{solution() = }')
157
import math
import numpy as np
import qiskit
from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute
def _a ( UpperCamelCase_ : int = 3 ) -> qiskit.result.counts.Counts:
"""simple docstring"""
if isinstance(UpperCamelCase_ , UpperCamelCase_ ):
raise TypeError("number of qubits must be a integer." )
if number_of_qubits <= 0:
raise ValueError("number of qubits must be > 0." )
if math.floor(UpperCamelCase_ ) != number_of_qubits:
raise ValueError("number of qubits must be exact integer." )
if number_of_qubits > 10:
raise ValueError("number of qubits too large to simulate(>10)." )
lowerCAmelCase__ = QuantumRegister(UpperCamelCase_ , "qr" )
lowerCAmelCase__ = ClassicalRegister(UpperCamelCase_ , "cr" )
lowerCAmelCase__ = QuantumCircuit(UpperCamelCase_ , UpperCamelCase_ )
lowerCAmelCase__ = number_of_qubits
for i in range(UpperCamelCase_ ):
quantum_circuit.h(number_of_qubits - i - 1 )
counter -= 1
for j in range(UpperCamelCase_ ):
quantum_circuit.cp(np.pi / 2 ** (counter - j) , UpperCamelCase_ , UpperCamelCase_ )
for k in range(number_of_qubits // 2 ):
quantum_circuit.swap(UpperCamelCase_ , number_of_qubits - k - 1 )
# measure all the qubits
quantum_circuit.measure(UpperCamelCase_ , UpperCamelCase_ )
# simulate with 10000 shots
lowerCAmelCase__ = Aer.get_backend("qasm_simulator" )
lowerCAmelCase__ = execute(UpperCamelCase_ , UpperCamelCase_ , shots=10_000 )
return job.result().get_counts(UpperCamelCase_ )
if __name__ == "__main__":
print(
F"Total count for quantum fourier transform state is: \
{quantum_fourier_transform(3)}"
)
340
0
def _lowercase ( UpperCamelCase_ ) -> bool:
'''simple docstring'''
if num < 0:
return False
SCREAMING_SNAKE_CASE__ = num
SCREAMING_SNAKE_CASE__ = 0
while num > 0:
SCREAMING_SNAKE_CASE__ = rev_num * 10 + (num % 10)
num //= 10
return num_copy == rev_num
if __name__ == "__main__":
import doctest
doctest.testmod()
355
import shutil
import tempfile
import unittest
from transformers import (
SPIECE_UNDERLINE,
AddedToken,
BatchEncoding,
NllbTokenizer,
NllbTokenizerFast,
is_torch_available,
)
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
)
from ...test_tokenization_common import TokenizerTesterMixin
__snake_case = get_tests_dir("""fixtures/test_sentencepiece.model""")
if is_torch_available():
from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right
__snake_case = 25_60_47
__snake_case = 25_61_45
@require_sentencepiece
@require_tokenizers
class lowercase__ ( _UpperCAmelCase , unittest.TestCase ):
A__ : int =NllbTokenizer
A__ : Optional[int] =NllbTokenizerFast
A__ : Union[str, Any] =True
A__ : Dict =True
A__ : Tuple ={}
def A_ ( self : List[str] ):
super().setUp()
# We have a SentencePiece fixture for testing
SCREAMING_SNAKE_CASE__ = NllbTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_ )
tokenizer.save_pretrained(self.tmpdirname )
def A_ ( self : Union[str, Any] ):
SCREAMING_SNAKE_CASE__ = NllbTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer.tokenize('This is a test' )
self.assertListEqual(UpperCAmelCase_ , ['▁This', '▁is', '▁a', '▁t', 'est'] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , )
SCREAMING_SNAKE_CASE__ = tokenizer.tokenize('I was born in 92000, and this is falsé.' )
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + 'I',
SPIECE_UNDERLINE + 'was',
SPIECE_UNDERLINE + 'b',
'or',
'n',
SPIECE_UNDERLINE + 'in',
SPIECE_UNDERLINE + '',
'9',
'2',
'0',
'0',
'0',
',',
SPIECE_UNDERLINE + 'and',
SPIECE_UNDERLINE + 'this',
SPIECE_UNDERLINE + 'is',
SPIECE_UNDERLINE + 'f',
'al',
's',
'é',
'.',
] , )
SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(UpperCAmelCase_ )
self.assertListEqual(
UpperCAmelCase_ , [
value + tokenizer.fairseq_offset
for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
] , )
SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(UpperCAmelCase_ )
self.assertListEqual(
UpperCAmelCase_ , [
SPIECE_UNDERLINE + 'I',
SPIECE_UNDERLINE + 'was',
SPIECE_UNDERLINE + 'b',
'or',
'n',
SPIECE_UNDERLINE + 'in',
SPIECE_UNDERLINE + '',
'<unk>',
'2',
'0',
'0',
'0',
',',
SPIECE_UNDERLINE + 'and',
SPIECE_UNDERLINE + 'this',
SPIECE_UNDERLINE + 'is',
SPIECE_UNDERLINE + 'f',
'al',
's',
'<unk>',
'.',
] , )
def A_ ( self : Optional[int] ):
SCREAMING_SNAKE_CASE__ = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-nllb', {})
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ):
SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE__ = tokenizer_r.save_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_p.save_pretrained(UpperCAmelCase_ )
# Checks it save with the same files + the tokenizer.json file for the fast one
self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) )
SCREAMING_SNAKE_CASE__ = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f )
self.assertSequenceEqual(UpperCAmelCase_ , UpperCAmelCase_ )
# Checks everything loads correctly in the same way
SCREAMING_SNAKE_CASE__ = tokenizer_r.from_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_p.from_pretrained(UpperCAmelCase_ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(UpperCAmelCase_ , UpperCAmelCase_ ) )
shutil.rmtree(UpperCAmelCase_ )
# Save tokenizer rust, legacy_format=True
SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE__ = tokenizer_r.save_pretrained(UpperCAmelCase_ , legacy_format=UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_p.save_pretrained(UpperCAmelCase_ )
# Checks it save with the same files
self.assertSequenceEqual(UpperCAmelCase_ , UpperCAmelCase_ )
# Checks everything loads correctly in the same way
SCREAMING_SNAKE_CASE__ = tokenizer_r.from_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_p.from_pretrained(UpperCAmelCase_ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(UpperCAmelCase_ , UpperCAmelCase_ ) )
shutil.rmtree(UpperCAmelCase_ )
# Save tokenizer rust, legacy_format=False
SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE__ = tokenizer_r.save_pretrained(UpperCAmelCase_ , legacy_format=UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_p.save_pretrained(UpperCAmelCase_ )
# Checks it saved the tokenizer.json file
self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) )
# Checks everything loads correctly in the same way
SCREAMING_SNAKE_CASE__ = tokenizer_r.from_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_p.from_pretrained(UpperCAmelCase_ )
# Check special tokens are set accordingly on Rust and Python
for key in tokenizer_pp.special_tokens_map:
self.assertTrue(hasattr(UpperCAmelCase_ , UpperCAmelCase_ ) )
shutil.rmtree(UpperCAmelCase_ )
@require_torch
def A_ ( self : Tuple ):
if not self.test_seqaseq:
return
SCREAMING_SNAKE_CASE__ = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(F'{tokenizer.__class__.__name__}' ):
# Longer text that will definitely require truncation.
SCREAMING_SNAKE_CASE__ = [
' UN Chief Says There Is No Military Solution in Syria',
' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for'
' Syria is that \'there is no military solution\' to the nearly five-year conflict and more weapons'
' will only worsen the violence and misery for millions of people.',
]
SCREAMING_SNAKE_CASE__ = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al'
' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi'
' că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.',
]
try:
SCREAMING_SNAKE_CASE__ = tokenizer.prepare_seqaseq_batch(
src_texts=UpperCAmelCase_ , tgt_texts=UpperCAmelCase_ , max_length=3 , max_target_length=10 , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='ron_Latn' , )
except NotImplementedError:
return
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.labels.shape[1] , 10 )
# max_target_length will default to max_length if not specified
SCREAMING_SNAKE_CASE__ = tokenizer.prepare_seqaseq_batch(
UpperCAmelCase_ , tgt_texts=UpperCAmelCase_ , max_length=3 , return_tensors='pt' )
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.labels.shape[1] , 3 )
SCREAMING_SNAKE_CASE__ = tokenizer.prepare_seqaseq_batch(
src_texts=UpperCAmelCase_ , max_length=3 , max_target_length=10 , return_tensors='pt' )
self.assertEqual(batch_encoder_only.input_ids.shape[1] , 3 )
self.assertEqual(batch_encoder_only.attention_mask.shape[1] , 3 )
self.assertNotIn('decoder_input_ids' , UpperCAmelCase_ )
@unittest.skip('Unfortunately way too slow to build a BPE with SentencePiece.' )
def A_ ( self : List[Any] ):
pass
def A_ ( self : Optional[Any] ):
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ):
SCREAMING_SNAKE_CASE__ = [AddedToken('<special>' , lstrip=UpperCAmelCase_ )]
SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , **UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_r.encode('Hey this is a <special> token' )
SCREAMING_SNAKE_CASE__ = tokenizer_r.encode('<special>' , add_special_tokens=UpperCAmelCase_ )[0]
self.assertTrue(special_token_id in r_output )
if self.test_slow_tokenizer:
SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(
UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , **UpperCAmelCase_ , )
SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(
UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , **UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = tokenizer_p.encode('Hey this is a <special> token' )
SCREAMING_SNAKE_CASE__ = tokenizer_cr.encode('Hey this is a <special> token' )
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ )
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ )
self.assertTrue(special_token_id in p_output )
self.assertTrue(special_token_id in cr_output )
@require_torch
@require_sentencepiece
@require_tokenizers
class lowercase__ ( unittest.TestCase ):
A__ : List[Any] ="""facebook/nllb-200-distilled-600M"""
A__ : Tuple =[
""" UN Chief Says There Is No Military Solution in Syria""",
""" Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""",
]
A__ : Optional[Any] =[
"""Şeful ONU declară că nu există o soluţie militară în Siria""",
"""Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei"""
""" pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor"""
""" face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""",
]
A__ : Optional[int] =[
2_5_6_0_4_7,
1_6_2_9_7,
1_3_4_4_0_8,
8_1_6_5,
2_4_8_0_6_6,
1_4_7_3_4,
9_5_0,
1_1_3_5,
1_0_5_7_2_1,
3_5_7_3,
8_3,
2_7_3_5_2,
1_0_8,
4_9_4_8_6,
2,
]
@classmethod
def A_ ( cls : Tuple ):
SCREAMING_SNAKE_CASE__ = NllbTokenizer.from_pretrained(
cls.checkpoint_name , src_lang='eng_Latn' , tgt_lang='ron_Latn' )
SCREAMING_SNAKE_CASE__ = 1
return cls
def A_ ( self : int ):
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Arab'] , 256001 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ace_Latn'] , 256002 )
self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['fra_Latn'] , 256057 )
def A_ ( self : Optional[Any] ):
SCREAMING_SNAKE_CASE__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , UpperCAmelCase_ )
def A_ ( self : Dict ):
self.assertIn(UpperCAmelCase_ , self.tokenizer.all_special_ids )
# fmt: off
SCREAMING_SNAKE_CASE__ = [RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047]
# fmt: on
SCREAMING_SNAKE_CASE__ = self.tokenizer.decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase_ )
self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_ )
self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase_ )
def A_ ( self : str ):
SCREAMING_SNAKE_CASE__ = ['this is gunna be a long sentence ' * 20]
assert isinstance(src_text[0] , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = 10
SCREAMING_SNAKE_CASE__ = self.tokenizer(UpperCAmelCase_ , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ ).input_ids[0]
self.assertEqual(ids[-1] , 2 )
self.assertEqual(ids[0] , UpperCAmelCase_ )
self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ )
def A_ ( self : Optional[Any] ):
self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [256203, 3] )
def A_ ( self : Dict ):
SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp()
SCREAMING_SNAKE_CASE__ = self.tokenizer.fairseq_tokens_to_ids
self.tokenizer.save_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE__ = NllbTokenizer.from_pretrained(UpperCAmelCase_ )
self.assertDictEqual(new_tok.fairseq_tokens_to_ids , UpperCAmelCase_ )
@require_torch
def A_ ( self : Optional[int] ):
SCREAMING_SNAKE_CASE__ = self.tokenizer(
self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , )
SCREAMING_SNAKE_CASE__ = shift_tokens_right(
batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.lang_code_to_id['ron_Latn'] )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
self.assertEqual((2, 15) , batch.input_ids.shape )
self.assertEqual((2, 15) , batch.attention_mask.shape )
SCREAMING_SNAKE_CASE__ = batch.input_ids.tolist()[0]
self.assertListEqual(self.expected_src_tokens , UpperCAmelCase_ )
self.assertEqual(UpperCAmelCase_ , batch.decoder_input_ids[0, 0] ) # EOS
# Test that special tokens are reset
self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] )
self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
def A_ ( self : str ):
SCREAMING_SNAKE_CASE__ = self.tokenizer(self.src_text , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=3 , return_tensors='pt' )
SCREAMING_SNAKE_CASE__ = self.tokenizer(
text_target=self.tgt_text , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=10 , return_tensors='pt' )
SCREAMING_SNAKE_CASE__ = targets['input_ids']
SCREAMING_SNAKE_CASE__ = shift_tokens_right(
UpperCAmelCase_ , self.tokenizer.pad_token_id , decoder_start_token_id=self.tokenizer.lang_code_to_id[self.tokenizer.tgt_lang] , )
self.assertEqual(batch.input_ids.shape[1] , 3 )
self.assertEqual(batch.decoder_input_ids.shape[1] , 10 )
@require_torch
def A_ ( self : List[str] ):
SCREAMING_SNAKE_CASE__ = self.tokenizer._build_translation_inputs(
'A test' , return_tensors='pt' , src_lang='eng_Latn' , tgt_lang='fra_Latn' )
self.assertEqual(
nested_simplify(UpperCAmelCase_ ) , {
# A, test, EOS, en_XX
'input_ids': [[256047, 70, 7356, 2]],
'attention_mask': [[1, 1, 1, 1]],
# ar_AR
'forced_bos_token_id': 256057,
} , )
@require_torch
def A_ ( self : Optional[int] ):
SCREAMING_SNAKE_CASE__ = True
SCREAMING_SNAKE_CASE__ = self.tokenizer(
'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' )
self.assertEqual(
inputs.input_ids , [16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047] )
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = self.tokenizer(
'UN Chief says there is no military solution in Syria' , src_lang='eng_Latn' , tgt_lang='fra_Latn' )
self.assertEqual(
inputs.input_ids , [256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2] )
"""simple docstring"""
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class A_ ( SCREAMING_SNAKE_CASE_ ):
"""simple docstring"""
__UpperCamelCase = ["""image_processor""", """tokenizer"""]
__UpperCamelCase = """LayoutLMv2ImageProcessor"""
__UpperCamelCase = ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""")
def __init__( self :Any , lowercase_ :int=None , lowercase_ :Union[str, Any]=None , **lowercase_ :Optional[Any] ) -> Dict:
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , lowercase_ , )
UpperCAmelCase = kwargs.pop('feature_extractor' )
UpperCAmelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('You need to specify an `image_processor`.' )
if tokenizer is None:
raise ValueError('You need to specify a `tokenizer`.' )
super().__init__(lowercase_ , lowercase_ )
def __call__( self :str , lowercase_ :Optional[int] , lowercase_ :Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowercase_ :Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , lowercase_ :Union[List[List[int]], List[List[List[int]]]] = None , lowercase_ :Optional[Union[List[int], List[List[int]]]] = None , lowercase_ :bool = True , lowercase_ :Union[bool, str, PaddingStrategy] = False , lowercase_ :Union[bool, str, TruncationStrategy] = None , lowercase_ :Optional[int] = None , lowercase_ :int = 0 , lowercase_ :Optional[int] = None , lowercase_ :Optional[bool] = None , lowercase_ :Optional[bool] = None , lowercase_ :bool = False , lowercase_ :bool = False , lowercase_ :bool = False , lowercase_ :bool = False , lowercase_ :bool = True , lowercase_ :Optional[Union[str, TensorType]] = None , **lowercase_ :Any , ) -> BatchEncoding:
# verify input
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
'You cannot provide bounding boxes '
'if you initialized the image processor with apply_ocr set to True.' )
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' )
if return_overflowing_tokens is True and return_offsets_mapping is False:
raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.' )
# first, apply the image processor
UpperCAmelCase = self.image_processor(images=lowercase_ , return_tensors=lowercase_ )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(lowercase_ , lowercase_ ):
UpperCAmelCase = [text] # add batch dimension (as the image processor always adds a batch dimension)
UpperCAmelCase = features['words']
UpperCAmelCase = self.tokenizer(
text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=lowercase_ , add_special_tokens=lowercase_ , padding=lowercase_ , truncation=lowercase_ , max_length=lowercase_ , stride=lowercase_ , pad_to_multiple_of=lowercase_ , return_token_type_ids=lowercase_ , return_attention_mask=lowercase_ , return_overflowing_tokens=lowercase_ , return_special_tokens_mask=lowercase_ , return_offsets_mapping=lowercase_ , return_length=lowercase_ , verbose=lowercase_ , return_tensors=lowercase_ , **lowercase_ , )
# add pixel values
UpperCAmelCase = features.pop('pixel_values' )
if return_overflowing_tokens is True:
UpperCAmelCase = self.get_overflowing_images(lowercase_ , encoded_inputs['overflow_to_sample_mapping'] )
UpperCAmelCase = images
return encoded_inputs
def UpperCAmelCase__ ( self :Dict , lowercase_ :List[Any] , lowercase_ :Any ) -> Optional[Any]:
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
UpperCAmelCase = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(lowercase_ ) != len(lowercase_ ):
raise ValueError(
'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
f""" {len(lowercase_ )} and {len(lowercase_ )}""" )
return images_with_overflow
def UpperCAmelCase__ ( self :Any , *lowercase_ :int , **lowercase_ :Tuple ) -> Tuple:
return self.tokenizer.batch_decode(*lowercase_ , **lowercase_ )
def UpperCAmelCase__ ( self :Any , *lowercase_ :List[Any] , **lowercase_ :Optional[int] ) -> Optional[Any]:
return self.tokenizer.decode(*lowercase_ , **lowercase_ )
@property
def UpperCAmelCase__ ( self :int ) -> Optional[int]:
return ["input_ids", "bbox", "attention_mask", "image"]
@property
def UpperCAmelCase__ ( self :int ) -> Dict:
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , lowercase_ , )
return self.image_processor_class
@property
def UpperCAmelCase__ ( self :Union[str, Any] ) -> Optional[int]:
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , lowercase_ , )
return self.image_processor
78
0
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
__a = {
'''configuration_blip''': [
'''BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''BlipConfig''',
'''BlipTextConfig''',
'''BlipVisionConfig''',
],
'''processing_blip''': ['''BlipProcessor'''],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__a = ['''BlipImageProcessor''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__a = [
'''BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BlipModel''',
'''BlipPreTrainedModel''',
'''BlipForConditionalGeneration''',
'''BlipForQuestionAnswering''',
'''BlipVisionModel''',
'''BlipTextModel''',
'''BlipForImageTextRetrieval''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__a = [
'''TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TFBlipModel''',
'''TFBlipPreTrainedModel''',
'''TFBlipForConditionalGeneration''',
'''TFBlipForQuestionAnswering''',
'''TFBlipVisionModel''',
'''TFBlipTextModel''',
'''TFBlipForImageTextRetrieval''',
]
if TYPE_CHECKING:
from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
from .processing_blip import BlipProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_blip import BlipImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blip import (
BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
BlipForConditionalGeneration,
BlipForImageTextRetrieval,
BlipForQuestionAnswering,
BlipModel,
BlipPreTrainedModel,
BlipTextModel,
BlipVisionModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blip import (
TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
TFBlipForConditionalGeneration,
TFBlipForImageTextRetrieval,
TFBlipForQuestionAnswering,
TFBlipModel,
TFBlipPreTrainedModel,
TFBlipTextModel,
TFBlipVisionModel,
)
else:
import sys
__a = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
364
from maths.prime_factors import prime_factors
def __lowercase ( _UpperCamelCase ) ->int:
"""simple docstring"""
if not isinstance(_UpperCamelCase, _UpperCamelCase ):
lowercase : List[str] = f"""Input value of [number={number}] must be an integer"""
raise TypeError(_UpperCamelCase )
if number < 1:
raise ValueError('''Input must be a positive integer''' )
return -1 if len(prime_factors(_UpperCamelCase ) ) % 2 else 1
if __name__ == "__main__":
import doctest
doctest.testmod()
173
0
from __future__ import annotations
import time
from math import sqrt
# 1 for manhattan, 0 for euclidean
__A : List[str] = 0
__A : List[str] = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
__A : Union[str, Any] = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
__A : Tuple = tuple[int, int]
class __A :
def __init__( self : List[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Node | None , ):
lowerCAmelCase : Union[str, Any] = pos_x
lowerCAmelCase : Dict = pos_y
lowerCAmelCase : Dict = (pos_y, pos_x)
lowerCAmelCase : List[str] = goal_x
lowerCAmelCase : List[str] = goal_y
lowerCAmelCase : int = g_cost
lowerCAmelCase : str = parent
lowerCAmelCase : str = self.calculate_heuristic()
lowerCAmelCase : int = self.g_cost + self.h_cost
def lowercase__ ( self : List[Any] ):
lowerCAmelCase : int = self.pos_x - self.goal_x
lowerCAmelCase : int = self.pos_y - self.goal_y
if HEURISTIC == 1:
return abs(UpperCAmelCase_ ) + abs(UpperCAmelCase_ )
else:
return sqrt(dy**2 + dx**2 )
def __lt__( self : Tuple , UpperCAmelCase_ : Node ):
return self.f_cost < other.f_cost
class __A :
def __init__( self : Tuple , UpperCAmelCase_ : TPosition , UpperCAmelCase_ : TPosition ):
lowerCAmelCase : Optional[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCAmelCase_ )
lowerCAmelCase : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , UpperCAmelCase_ )
lowerCAmelCase : Any = [self.start]
lowerCAmelCase : list[Node] = []
lowerCAmelCase : Tuple = False
def lowercase__ ( self : Any ):
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
lowerCAmelCase : Union[str, Any] = self.open_nodes.pop(0 )
if current_node.pos == self.target.pos:
return self.retrace_path(UpperCAmelCase_ )
self.closed_nodes.append(UpperCAmelCase_ )
lowerCAmelCase : Dict = self.get_successors(UpperCAmelCase_ )
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(UpperCAmelCase_ )
else:
# retrieve the best current path
lowerCAmelCase : str = self.open_nodes.pop(self.open_nodes.index(UpperCAmelCase_ ) )
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(UpperCAmelCase_ )
else:
self.open_nodes.append(UpperCAmelCase_ )
return [self.start.pos]
def lowercase__ ( self : Optional[int] , UpperCAmelCase_ : Node ):
lowerCAmelCase : Optional[Any] = []
for action in delta:
lowerCAmelCase : Union[str, Any] = parent.pos_x + action[1]
lowerCAmelCase : List[str] = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase_ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
UpperCAmelCase_ , UpperCAmelCase_ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCAmelCase_ , ) )
return successors
def lowercase__ ( self : Dict , UpperCAmelCase_ : Node | None ):
lowerCAmelCase : int = node
lowerCAmelCase : str = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
lowerCAmelCase : List[str] = current_node.parent
path.reverse()
return path
class __A :
def __init__( self : int , UpperCAmelCase_ : TPosition , UpperCAmelCase_ : TPosition ):
lowerCAmelCase : List[str] = AStar(UpperCAmelCase_ , UpperCAmelCase_ )
lowerCAmelCase : List[str] = AStar(UpperCAmelCase_ , UpperCAmelCase_ )
lowerCAmelCase : Tuple = False
def lowercase__ ( self : Union[str, Any] ):
while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes:
self.fwd_astar.open_nodes.sort()
self.bwd_astar.open_nodes.sort()
lowerCAmelCase : Optional[int] = self.fwd_astar.open_nodes.pop(0 )
lowerCAmelCase : Any = self.bwd_astar.open_nodes.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
return self.retrace_bidirectional_path(
UpperCAmelCase_ , UpperCAmelCase_ )
self.fwd_astar.closed_nodes.append(UpperCAmelCase_ )
self.bwd_astar.closed_nodes.append(UpperCAmelCase_ )
lowerCAmelCase : str = current_bwd_node
lowerCAmelCase : List[Any] = current_fwd_node
lowerCAmelCase : List[str] = {
self.fwd_astar: self.fwd_astar.get_successors(UpperCAmelCase_ ),
self.bwd_astar: self.bwd_astar.get_successors(UpperCAmelCase_ ),
}
for astar in [self.fwd_astar, self.bwd_astar]:
for child_node in successors[astar]:
if child_node in astar.closed_nodes:
continue
if child_node not in astar.open_nodes:
astar.open_nodes.append(UpperCAmelCase_ )
else:
# retrieve the best current path
lowerCAmelCase : int = astar.open_nodes.pop(
astar.open_nodes.index(UpperCAmelCase_ ) )
if child_node.g_cost < better_node.g_cost:
astar.open_nodes.append(UpperCAmelCase_ )
else:
astar.open_nodes.append(UpperCAmelCase_ )
return [self.fwd_astar.start.pos]
def lowercase__ ( self : Union[str, Any] , UpperCAmelCase_ : Node , UpperCAmelCase_ : Node ):
lowerCAmelCase : List[str] = self.fwd_astar.retrace_path(UpperCAmelCase_ )
lowerCAmelCase : Optional[Any] = self.bwd_astar.retrace_path(UpperCAmelCase_ )
bwd_path.pop()
bwd_path.reverse()
lowerCAmelCase : Any = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
__A : Optional[int] = (0, 0)
__A : int = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
__A : Optional[Any] = time.time()
__A : List[Any] = AStar(init, goal)
__A : List[str] = a_star.search()
__A : Union[str, Any] = time.time() - start_time
print(F'AStar execution time = {end_time:f} seconds')
__A : Union[str, Any] = time.time()
__A : Dict = BidirectionalAStar(init, goal)
__A : List[Any] = time.time() - bd_start_time
print(F'BidirectionalAStar execution time = {bd_end_time:f} seconds')
"""simple docstring"""
from __future__ import annotations
import requests
def __SCREAMING_SNAKE_CASE ( A_ ):
lowerCAmelCase__ : Dict = f'https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty'
return requests.get(A_ ).json()
def __SCREAMING_SNAKE_CASE ( A_ = 10 ):
lowerCAmelCase__ : int = '''https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'''
lowerCAmelCase__ : Optional[int] = requests.get(A_ ).json()[:max_stories]
return [get_hackernews_story(A_ ) for story_id in story_ids]
def __SCREAMING_SNAKE_CASE ( A_ = 10 ):
lowerCAmelCase__ : Tuple = hackernews_top_stories(A_ )
return "\n".join('''* [{title}]({url})'''.format(**A_ ) for story in stories )
if __name__ == "__main__":
print(hackernews_top_stories_as_markdown())
74
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import (
VersatileDiffusionDualGuidedPipeline,
VersatileDiffusionImageVariationPipeline,
VersatileDiffusionPipeline,
VersatileDiffusionTextToImagePipeline,
)
else:
from .modeling_text_unet import UNetFlatConditionModel
from .pipeline_versatile_diffusion import VersatileDiffusionPipeline
from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
74
1
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.