



'''simple docstring'''





from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...file_utils import TensorType, is_torch_available
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


_UpperCamelCase							       =		logging.get_logger(__name__)

_UpperCamelCase							       =		{
    'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json',
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  a_							      ="""blenderbot"""
  a_							      =["""past_key_values"""]
  a_							      ={"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}




  def __init__(				self   :			List[str]    ,			_a   :			List[str]=8008    ,			_a   :			Optional[Any]=128    ,			_a   :			Union[str, Any]=2    ,			_a   :			List[Any]=1_0240    ,			_a   :			str=32    ,			_a   :			Tuple=24    ,			_a   :			List[str]=1_0240    ,			_a   :			str=32    ,			_a   :			Dict=0.0    ,			_a   :			List[Any]=0.0    ,			_a   :			str=True    ,			_a   :			List[str]=True    ,			_a   :			Dict="gelu"    ,			_a   :			Any=2560    ,			_a   :			Any=0.1    ,			_a   :			Tuple=0.0    ,			_a   :			Optional[Any]=0.0    ,			_a   :			List[Any]=0.02    ,			_a   :			str=1    ,			_a   :			Any=False    ,			_a   :			Tuple=0    ,			_a   :			Tuple=1    ,			_a   :			Union[str, Any]=2    ,			_a   :			List[Any]=3    ,			_a   :			str=2    ,			**_a   :			int    ,			)      ->      int:
    __lowerCamelCase : Optional[int]					 =				vocab_size
    __lowerCamelCase : Dict					 =				max_position_embeddings
    __lowerCamelCase : Dict					 =				d_model
    __lowerCamelCase : Tuple					 =				encoder_ffn_dim
    __lowerCamelCase : List[str]					 =				encoder_layers
    __lowerCamelCase : Any					 =				encoder_attention_heads
    __lowerCamelCase : Dict					 =				decoder_ffn_dim
    __lowerCamelCase : int					 =				decoder_layers
    __lowerCamelCase : Any					 =				decoder_attention_heads
    __lowerCamelCase : str					 =				dropout
    __lowerCamelCase : Optional[Any]					 =				attention_dropout
    __lowerCamelCase : Optional[int]					 =				activation_dropout
    __lowerCamelCase : Union[str, Any]					 =				activation_function
    __lowerCamelCase : Tuple					 =				init_std
    __lowerCamelCase : Dict					 =				encoder_layerdrop
    __lowerCamelCase : Dict					 =				decoder_layerdrop
    __lowerCamelCase : Optional[Any]					 =				use_cache
    __lowerCamelCase : Union[str, Any]					 =				encoder_layers
    __lowerCamelCase : int					 =				scale_embedding  # scale factor will be sqrt(d_model) if True

    super().__init__(
        pad_token_id=_a    ,			bos_token_id=_a    ,			eos_token_id=_a    ,			is_encoder_decoder=_a    ,			decoder_start_token_id=_a    ,			encoder_no_repeat_ngram_size=_a    ,			forced_eos_token_id=_a    ,			**_a    ,			)






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  @property
  def 		_lowercase  (				self   :			Tuple     )      ->      Mapping[str, Mapping[int, str]]:
    if self.task in ["default", "seq2seq-lm"]:
      __lowerCamelCase : Any					 =				OrderedDict(
          [
              ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
              ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
          ]     )
      if self.use_past:
        __lowerCamelCase : Dict					 =				{0: 'batch'}
        __lowerCamelCase : Any					 =				{0: 'batch', 1: 'past_decoder_sequence + sequence'}
      else:
        __lowerCamelCase : Tuple					 =				{0: 'batch', 1: 'decoder_sequence'}
        __lowerCamelCase : Dict					 =				{0: 'batch', 1: 'decoder_sequence'}
      if self.use_past:
        self.fill_with_past_key_values_(_a    ,			direction='inputs'     )
    elif self.task == "causal-lm":
      __lowerCamelCase : List[str]					 =				OrderedDict(
          [
              ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
              ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
          ]     )
      if self.use_past:
        __lowerCamelCase ,__lowerCamelCase : Tuple					 =				self.num_layers
        for i in range(_a     ):
          __lowerCamelCase : Tuple					 =				{0: 'batch', 2: 'past_sequence + sequence'}
          __lowerCamelCase : Optional[int]					 =				{0: 'batch', 2: 'past_sequence + sequence'}
    else:
      __lowerCamelCase : Optional[Any]					 =				OrderedDict(
          [
              ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
              ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
              ('decoder_input_ids', {0: 'batch', 1: 'decoder_sequence'}),
              ('decoder_attention_mask', {0: 'batch', 1: 'decoder_sequence'}),
          ]     )

    return common_inputs




  @property
  # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
  def 		_lowercase  (				self   :			List[Any]     )      ->      Mapping[str, Mapping[int, str]]:
    if self.task in ["default", "seq2seq-lm"]:
      __lowerCamelCase : Tuple					 =				super().outputs
    else:
      __lowerCamelCase : Union[str, Any]					 =				super(_a    ,			self     ).outputs
      if self.use_past:
        __lowerCamelCase ,__lowerCamelCase : int					 =				self.num_layers
        for i in range(_a     ):
          __lowerCamelCase : Dict					 =				{0: 'batch', 2: 'past_sequence + sequence'}
          __lowerCamelCase : List[Any]					 =				{0: 'batch', 2: 'past_sequence + sequence'}
    return common_outputs




  def 		_lowercase  (				self   :			Optional[int]    ,			_a   :			PreTrainedTokenizer    ,			_a   :			int = -1    ,			_a   :			int = -1    ,			_a   :			bool = False    ,			_a   :			Optional[TensorType] = None    ,			)      ->      Mapping[str, Any]:
    __lowerCamelCase : Union[str, Any]					 =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
        _a    ,			_a    ,			_a    ,			_a    ,			_a     )
    # Generate decoder inputs
    __lowerCamelCase : Union[str, Any]					 =				seq_length if not self.use_past else 1
    __lowerCamelCase : str					 =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
        _a    ,			_a    ,			_a    ,			_a    ,			_a     )
    __lowerCamelCase : Tuple					 =				{f'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
    __lowerCamelCase : Union[str, Any]					 =				dict(**_a    ,			**_a     )

    if self.use_past:
      if not is_torch_available():
        raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'     )
      else:
        import torch
      __lowerCamelCase ,__lowerCamelCase : Any					 =				common_inputs['input_ids'].shape
      __lowerCamelCase : str					 =				common_inputs['decoder_input_ids'].shape[1]
      __lowerCamelCase ,__lowerCamelCase : List[Any]					 =				self.num_attention_heads
      __lowerCamelCase : str					 =				(
          batch,
          num_encoder_attention_heads,
          encoder_seq_length,
          self._config.hidden_size // num_encoder_attention_heads,
      )
      __lowerCamelCase : List[Any]					 =				decoder_seq_length
      __lowerCamelCase : List[Any]					 =				(
          batch,
          num_decoder_attention_heads,
          decoder_past_length,
          self._config.hidden_size // num_decoder_attention_heads,
      )
      __lowerCamelCase : Optional[int]					 =				torch.cat(
          [common_inputs['decoder_attention_mask'], torch.ones(_a    ,			_a     )]    ,			dim=1     )
      __lowerCamelCase : Dict					 =				[]
      __lowerCamelCase ,__lowerCamelCase : List[str]					 =				self.num_layers

      for _ in range(_a     ):
        common_inputs["past_key_values"].append(
            (
                torch.zeros(_a     ),
                torch.zeros(_a     ),
                torch.zeros(_a     ),
                torch.zeros(_a     ),
            )     )
    return common_inputs




  def 		_lowercase  (				self   :			Union[str, Any]    ,			_a   :			PreTrainedTokenizer    ,			_a   :			int = -1    ,			_a   :			int = -1    ,			_a   :			bool = False    ,			_a   :			Optional[TensorType] = None    ,			)      ->      Mapping[str, Any]:
    __lowerCamelCase : int					 =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
        _a    ,			_a    ,			_a    ,			_a    ,			_a     )

    if self.use_past:
      if not is_torch_available():
        raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'     )
      else:
        import torch
      __lowerCamelCase ,__lowerCamelCase : Any					 =				common_inputs['input_ids'].shape
      __lowerCamelCase : Optional[Any]					 =				seqlen
      __lowerCamelCase ,__lowerCamelCase : List[str]					 =				self.num_layers
      __lowerCamelCase ,__lowerCamelCase : Optional[int]					 =				self.num_attention_heads
      __lowerCamelCase : Optional[Any]					 =				(
          batch,
          num_encoder_attention_heads,
          past_key_values_length,
          self._config.hidden_size // num_encoder_attention_heads,
      )
      __lowerCamelCase : Union[str, Any]					 =				common_inputs['attention_mask'].dtype
      __lowerCamelCase : List[Any]					 =				torch.cat(
          [common_inputs['attention_mask'], torch.ones(_a    ,			_a    ,			dtype=_a     )]    ,			dim=1     )
      __lowerCamelCase : Tuple					 =				[
          (torch.zeros(_a     ), torch.zeros(_a     )) for _ in range(_a     )
      ]
    return common_inputs




  def 		_lowercase  (				self   :			int    ,			_a   :			PreTrainedTokenizer    ,			_a   :			int = -1    ,			_a   :			int = -1    ,			_a   :			bool = False    ,			_a   :			Optional[TensorType] = None    ,			)      ->      Mapping[str, Any]:
    # Copied from OnnxConfig.generate_dummy_inputs
    # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
    # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
    __lowerCamelCase : List[Any]					 =				compute_effective_axis_dimension(
        _a    ,			fixed_dimension=OnnxConfig.default_fixed_batch    ,			num_token_to_add=0     )

    # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
    __lowerCamelCase : Union[str, Any]					 =				tokenizer.num_special_tokens_to_add(_a     )
    __lowerCamelCase : Optional[Any]					 =				compute_effective_axis_dimension(
        _a    ,			fixed_dimension=OnnxConfig.default_fixed_sequence    ,			num_token_to_add=_a     )

    # Generate dummy inputs according to compute batch and sequence
    __lowerCamelCase : Tuple					 =				[' '.join([tokenizer.unk_token]     ) * seq_length] * batch_size
    __lowerCamelCase : Tuple					 =				dict(tokenizer(_a    ,			return_tensors=_a     )     )
    return common_inputs




  def 		_lowercase  (				self   :			Optional[Any]    ,			_a   :			PreTrainedTokenizer    ,			_a   :			int = -1    ,			_a   :			int = -1    ,			_a   :			bool = False    ,			_a   :			Optional[TensorType] = None    ,			)      ->      Mapping[str, Any]:
    if self.task in ["default", "seq2seq-lm"]:
      __lowerCamelCase : List[str]					 =				self._generate_dummy_inputs_for_default_and_seqaseq_lm(
          _a    ,			batch_size=_a    ,			seq_length=_a    ,			is_pair=_a    ,			framework=_a     )

    elif self.task == "causal-lm":
      __lowerCamelCase : Dict					 =				self._generate_dummy_inputs_for_causal_lm(
          _a    ,			batch_size=_a    ,			seq_length=_a    ,			is_pair=_a    ,			framework=_a     )
    else:
      __lowerCamelCase : Tuple					 =				self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
          _a    ,			batch_size=_a    ,			seq_length=_a    ,			is_pair=_a    ,			framework=_a     )

    return common_inputs




  def 		_lowercase  (				self   :			Tuple    ,			_a   :			List[Any]    ,			_a   :			str    ,			_a   :			List[Any]    ,			_a   :			Union[str, Any]     )      ->      Optional[int]:
    if self.task in ["default", "seq2seq-lm"]:
      __lowerCamelCase : str					 =				super()._flatten_past_key_values_(_a    ,			_a    ,			_a    ,			_a     )
    else:
      __lowerCamelCase : Optional[int]					 =				super(_a    ,			self     )._flatten_past_key_values_(
          _a    ,			_a    ,			_a    ,			_a     )




  def 		_lowercase  (				self   :			Any    ,			_a   :			Mapping[str, Mapping[int, str]]    ,			_a   :			str     )      ->      Dict:
    if direction not in ["inputs", "outputs"]:
      raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given'     )

    __lowerCamelCase : Optional[Any]					 =				'past_key_values' if direction == 'inputs' else 'present'
    __lowerCamelCase ,__lowerCamelCase : Tuple					 =				self.num_layers

    __lowerCamelCase : Optional[Any]					 =				'past_encoder_sequence'
    __lowerCamelCase : Dict					 =				'past_decoder_sequence' if direction == 'inputs' else 'past_decoder_sequence + sequence'

    for i in range(_a     ):
      __lowerCamelCase : List[str]					 =				{0: 'batch', 2: decoder_sequence}
      __lowerCamelCase : Dict					 =				{0: 'batch', 2: decoder_sequence}
      __lowerCamelCase : List[Any]					 =				{0: 'batch', 2: encoder_sequence}
      __lowerCamelCase : Dict					 =				{0: 'batch', 2: encoder_sequence}











'''simple docstring'''





import json
import os
import subprocess
import sys
import warnings
from argparse import ArgumentParser
from contextlib import AbstractContextManager
from typing import Dict, List, Optional

import requests

from ..utils import logging
from . import BaseTransformersCLICommand


_UpperCamelCase							       =		logging.get_logger(__name__)  # pylint: disable=invalid-name


_UpperCamelCase							       =		'lfs-multipart-upload'






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  @staticmethod
  def 		_lowercase  (				_a   :			ArgumentParser     )      ->      List[Any]:
    __lowerCamelCase : Union[str, Any]					 =				parser.add_parser(
        'lfs-enable-largefiles'    ,			help=(
            'Deprecated: use `huggingface-cli` instead. Configure your repository to enable upload of files > 5GB.'
        )    ,			)
    enable_parser.add_argument('path'    ,			type=_a    ,			help='Local path to repository you want to configure.'     )
    enable_parser.set_defaults(func=lambda _a     : LfsEnableCommand(_a     )     )

    __lowerCamelCase : Any					 =				parser.add_parser(
        _a    ,			help=(
            'Deprecated: use `huggingface-cli` instead. '
            'Command will get called by git-lfs, do not call it directly.'
        )    ,			)
    upload_parser.set_defaults(func=lambda _a     : LfsUploadCommand(_a     )     )






class       lowerCamelCase_					:
  """simple docstring"""




  def __init__(				self   :			Union[str, Any]    ,			_a   :			Any     )      ->      Tuple:
    __lowerCamelCase : int					 =				args




  def 		_lowercase  (				self   :			Union[str, Any]     )      ->      List[str]:
    warnings.warn(
        'Managing repositories through transformers-cli is deprecated. Please use `huggingface-cli` instead.'     )
    __lowerCamelCase : str					 =				os.path.abspath(self.args.path     )
    if not os.path.isdir(_a     ):
      print('This does not look like a valid git repo.'     )
      exit(1     )
    subprocess.run(
        'git config lfs.customtransfer.multipart.path transformers-cli'.split()    ,			check=_a    ,			cwd=_a     )
    subprocess.run(
        f'git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}'.split()    ,			check=_a    ,			cwd=_a    ,			)
    print('Local repo set up for largefiles'     )




def  a_  (							_lowerCAmelCase )   ->   List[str]:
  __lowerCamelCase : int					 =				json.dumps(_lowerCAmelCase ) + '\n'
  sys.stdout.write(_lowerCAmelCase )
  sys.stdout.flush()

def  a_  (							)   ->   Optional[Dict]:
  __lowerCamelCase : str					 =				json.loads(sys.stdin.readline().strip() )

  if "terminate" in (msg.get('type' ), msg.get('event' )):
    # terminate message received
    return None

  if msg.get('event' ) not in ("download", "upload"):
    logger.critical('Received unexpected message' )
    sys.exit(1 )

  return msg






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  def __init__(				self   :			int    ,			_a   :			str    ,			_a   :			int    ,			_a   :			int     )      ->      Optional[Any]:
    __lowerCamelCase : Any					 =				filepath
    __lowerCamelCase : Dict					 =				seek_from
    __lowerCamelCase : Dict					 =				read_limit
    __lowerCamelCase : Tuple					 =				0




  def __enter__(				self   :			int     )      ->      int:
    __lowerCamelCase : Tuple					 =				open(self.filepath    ,			'rb'     )
    self.f.seek(self.seek_from     )
    return self




  def __len__(				self   :			Optional[int]     )      ->      Any:
    __lowerCamelCase : int					 =				os.fstat(self.f.fileno()     ).st_size
    return min(self.read_limit    ,			total_length - self.seek_from     )




  def 		_lowercase  (				self   :			Tuple    ,			_a   :			Optional[int]=-1     )      ->      Optional[int]:
    if self.n_seen >= self.read_limit:
      return b""
    __lowerCamelCase : Union[str, Any]					 =				self.read_limit - self.n_seen
    __lowerCamelCase : Tuple					 =				self.f.read(remaining_amount if n < 0 else min(_a    ,			_a     )     )
    self.n_seen += len(_a     )
    return data




  def __iter__(				self   :			int     )      ->      List[str]:
    yield self.read(n=4 * 1024 * 1024     )




  def __exit__(				self   :			List[str]    ,			*_a   :			int     )      ->      Optional[Any]:
    self.f.close()






class       lowerCamelCase_					:
  """simple docstring"""




  def __init__(				self   :			Optional[Any]    ,			_a   :			List[Any]     )      ->      Union[str, Any]:
    __lowerCamelCase : int					 =				args




  def 		_lowercase  (				self   :			Union[str, Any]     )      ->      Tuple:
    # Immediately after invoking a custom transfer process, git-lfs
    # sends initiation data to the process over stdin.
    # This tells the process useful information about the configuration.
    __lowerCamelCase : List[str]					 =				json.loads(sys.stdin.readline().strip()     )
    if not (init_msg.get('event'     ) == "init" and init_msg.get('operation'     ) == "upload"):
      write_msg({'error': {'code': 32, 'message': 'Wrong lfs init operation'}}     )
      sys.exit(1     )

    # The transfer process should use the information it needs from the
    # initiation structure, and also perform any one-off setup tasks it
    # needs to do. It should then respond on stdout with a simple empty
    # confirmation structure, as follows:
    write_msg({}     )

    # After the initiation exchange, git-lfs will send any number of
    # transfer requests to the stdin of the transfer process, in a serial sequence.
    while True:
      __lowerCamelCase : Any					 =				read_msg()
      if msg is None:
        # When all transfers have been processed, git-lfs will send
        # a terminate event to the stdin of the transfer process.
        # On receiving this message the transfer process should
        # clean up and terminate. No response is expected.
        sys.exit(0     )

      __lowerCamelCase : Tuple					 =				msg['oid']
      __lowerCamelCase : Dict					 =				msg['path']
      __lowerCamelCase : Any					 =				msg['action']['href']
      __lowerCamelCase : List[Any]					 =				msg['action']['header']
      __lowerCamelCase : List[str]					 =				int(header.pop('chunk_size'     )     )
      __lowerCamelCase : List[str]					 =				list(header.values()     )

      __lowerCamelCase : Any					 =				[]
      for i, presigned_url in enumerate(_a     ):
        with FileSlice(_a    ,			seek_from=i * chunk_size    ,			read_limit=_a     ) as data:
          __lowerCamelCase : Union[str, Any]					 =				requests.put(_a    ,			data=_a     )
          r.raise_for_status()
          parts.append(
              {
                  'etag': r.headers.get('etag'     ),
                  'partNumber': i + 1,
              }     )
          # In order to support progress reporting while data is uploading / downloading,
          # the transfer process should post messages to stdout
          write_msg(
              {
                  'event': 'progress',
                  'oid': oid,
                  'bytesSoFar': (i + 1) * chunk_size,
                  'bytesSinceLast': chunk_size,
              }     )
          # Not precise but that's ok.

      __lowerCamelCase : Tuple					 =				requests.post(
          _a    ,			json={
              'oid': oid,
              'parts': parts,
          }    ,			)
      r.raise_for_status()

      write_msg({'event': 'complete', 'oid': oid}     )






