





'''simple docstring'''







from __future__ import annotations

from scipy.special import comb  # type: ignore
class 			_lowercase						:







     def __init__( self    ,   A__    ) ->	List[Any]:
      snake_case				=			list_of_points
      # Degree determines the flexibility of the curve.
      # Degree = 1 will produce a straight line.
      snake_case				=			len(A__    ) - 1







     def     UpperCamelCase			( self    ,   A__    ) ->	list[float]:
      assert 0 <= t <= 1, "Time t must be between 0 and 1."
      snake_case				=			[]
      for i in range(len(self.list_of_points    )    ):
       # basis function for each i
       output_values.append(
           comb(self.degree    ,   A__    ) * ((1 - t) ** (self.degree - i)) * (t**i)    )
      # the basis must sum up to 1 for it to produce a valid Bezier curve.
      assert round(sum(A__    )    ,   5    ) == 1
      return output_values







     def     UpperCamelCase			( self    ,   A__    ) ->	tuple[float, float]:
      assert 0 <= t <= 1, "Time t must be between 0 and 1."

      snake_case				=			self.basis_function(A__    )
      snake_case				=			0.0
      snake_case				=			0.0
      for i in range(len(self.list_of_points    )    ):
       # For all points, sum up the product of i-th basis function and i-th point.
       x += basis_function[i] * self.list_of_points[i][0]
       y += basis_function[i] * self.list_of_points[i][1]
      return (x, y)







     def     UpperCamelCase			( self    ,   A__ = 0.0_1    ) ->	str:
      from matplotlib import pyplot as plt  # type: ignore

      snake_case				=			[]  # x coordinates of points to plot
      snake_case				=			[]  # y coordinates of points to plot

      snake_case				=			0.0
      while t <= 1:
       snake_case				=			self.bezier_curve_function(A__    )
       to_plot_x.append(value[0]    )
       to_plot_y.append(value[1]    )
       t += step_size

      snake_case				=			[i[0] for i in self.list_of_points]
      snake_case				=			[i[1] for i in self.list_of_points]

      plt.plot(
          A__    ,   A__    ,   color='''blue'''    ,   label='''Curve of Degree ''' + str(self.degree    )    ,   )
      plt.scatter(A__    ,   A__    ,   color='''red'''    ,   label='''Control Points'''    )
      plt.legend()
      plt.show()


if __name__ == "__main__":
   import doctest

   doctest.testmod()

   BezierCurve([(1, 2), (3, 5)]).plot_curve()  # degree 1
   BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve()  # degree 2
   BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve()  # degree 3








'''simple docstring'''







import argparse
from collections import OrderedDict
from pathlib import Path

import torch

from transformers import (
    VisualBertConfig,
    VisualBertForMultipleChoice,
    VisualBertForPreTraining,
    VisualBertForQuestionAnswering,
    VisualBertForVisualReasoning,
)
from transformers.utils import logging


logging.set_verbosity_info()
_lowercase       						=			logging.get_logger(__name__)

_lowercase       						=			[
    ('bert.bert', 'visual_bert'),
    ('bert.cls', 'cls'),
    ('bert.classifier', 'cls'),
    ('token_type_embeddings_visual', 'visual_token_type_embeddings'),
    ('position_embeddings_visual', 'visual_position_embeddings'),
    ('projection', 'visual_projection'),
]

_lowercase       						=			[
    'nlvr2_coco_pre_trained.th',
    'nlvr2_fine_tuned.th',
    'nlvr2_pre_trained.th',
    'vcr_coco_pre_train.th',
    'vcr_fine_tune.th',
    'vcr_pre_train.th',
    'vqa_coco_pre_trained.th',
    'vqa_fine_tuned.th',
    'vqa_pre_trained.th',
]

def    __UpperCamelCase	(	a    : List[str]     ) ->Optional[int]:
 snake_case				=			torch.load(a					,   map_location='''cpu'''     )
 return sd

def    __UpperCamelCase	(	a    : Optional[int]					,   a    : Union[str, Any]					,   a    : int=rename_keys_prefix     ) ->Tuple:
 snake_case				=			OrderedDict()
 snake_case				=			torch.arange(config.max_position_embeddings     ).expand((1, -1)     )
 # detector_d = OrderedDict()
 for key in d:
  if "detector" in key:
   # detector_d[key.replace('detector.','')] = d[key]
   continue
  snake_case				=			key
  for name_pair in rename_keys_prefix:
   snake_case				=			new_key.replace(name_pair[0]					,   name_pair[1]     )
  snake_case				=			d[key]
  if key == "bert.cls.predictions.decoder.weight":
   # Old bert code didn't have `decoder.bias`, but was added separately
   snake_case				=			new_d['''cls.predictions.bias''']
 return new_d

@torch.no_grad()
def    __UpperCamelCase	(	a    : Optional[int]					,   a    : int     ) ->Union[str, Any]:
 assert (
     checkpoint_path.split('''/'''     )[-1] in ACCEPTABLE_CHECKPOINTS
 ), f"""The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}."""

 # Get Config
 if "pre" in checkpoint_path:
  snake_case				=			'''pretraining'''
  if "vcr" in checkpoint_path:
   snake_case				=			{'''visual_embedding_dim''': 512}
  elif "vqa_advanced" in checkpoint_path:
   snake_case				=			{'''visual_embedding_dim''': 2048}
  elif "vqa" in checkpoint_path:
   snake_case				=			{'''visual_embedding_dim''': 2048}
  elif "nlvr" in checkpoint_path:
   snake_case				=			{'''visual_embedding_dim''': 1024}
  else:
   raise NotImplementedError(f"""No implementation found for `{checkpoint_path}`."""     )
 else:
  if "vcr" in checkpoint_path:
   snake_case				=			{'''visual_embedding_dim''': 512}
   snake_case				=			'''multichoice'''
  elif "vqa_advanced" in checkpoint_path:
   snake_case				=			{'''visual_embedding_dim''': 2048}
   snake_case				=			'''vqa_advanced'''
  elif "vqa" in checkpoint_path:
   snake_case				=			{'''visual_embedding_dim''': 2048, '''num_labels''': 3129}
   snake_case				=			'''vqa'''
  elif "nlvr" in checkpoint_path:
   snake_case				=			{
       '''visual_embedding_dim''': 1024,
       '''num_labels''': 2,
   }
   snake_case				=			'''nlvr'''

 snake_case				=			VisualBertConfig(**a     )

 # Load State Dict
 snake_case				=			load_state_dict(a     )

 snake_case				=			get_new_dict(a					,   a     )

 if model_type == "pretraining":
  snake_case				=			VisualBertForPreTraining(a     )
 elif model_type == "vqa":
  snake_case				=			VisualBertForQuestionAnswering(a     )
 elif model_type == "nlvr":
  snake_case				=			VisualBertForVisualReasoning(a     )
 elif model_type == "multichoice":
  snake_case				=			VisualBertForMultipleChoice(a     )

 model.load_state_dict(a     )
 # Save Checkpoints
 Path(a     ).mkdir(exist_ok=a     )
 model.save_pretrained(a     )


if __name__ == "__main__":
   _lowercase       						=			argparse.ArgumentParser()
   # Required parameters
   parser.add_argument('orig_checkpoint_path', type=str, help='A path to .th on local filesystem.')
   parser.add_argument('pytorch_dump_folder_path', type=str, help='Path to the output PyTorch model.')
   _lowercase       						=			parser.parse_args()
   convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)

