






"""simple docstring"""



import argparse
import collections

import torch
from flax import traverse_util
from tax import checkpoints

from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Optional[Any]		,					__snake_case			:  Union[str, Any]		,					__snake_case			:  Union[str, Any]		,					__snake_case			:  List[str]="attention"    ):





  '''simple docstring'''





  lowercase							    =       params[f'{prefix}/layers_{i}/{layer_name}/key/kernel']
  lowercase							    =       params[f'{prefix}/layers_{i}/{layer_name}/out/kernel']
  lowercase							    =       params[f'{prefix}/layers_{i}/{layer_name}/query/kernel']
  lowercase							    =       params[f'{prefix}/layers_{i}/{layer_name}/value/kernel']
  return k, o, q, v
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  str		,					__snake_case			:  Union[str, Any]		,					__snake_case			:  Any		,					__snake_case			:  Optional[int]=False    ):





  '''simple docstring'''





  if split_mlp_wi:
    lowercase							    =       params[f'{prefix}/layers_{i}/mlp/wi_0/kernel']
    lowercase							    =       params[f'{prefix}/layers_{i}/mlp/wi_1/kernel']
    lowercase							    =       (wi_a, wi_a)
  else:
    lowercase							    =       params[f'{prefix}/layers_{i}/mlp/wi/kernel']

  lowercase							    =       params[f'{prefix}/layers_{i}/mlp/wo/kernel']
  return wi, wo
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Optional[Any]		,					__snake_case			:  Union[str, Any]		,					__snake_case			:  Dict		,					__snake_case			:  Tuple    ):





  '''simple docstring'''





  return params[f'{prefix}/layers_{i}/{layer_name}/scale']
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  dict		,					*, __snake_case			:  int		,					__snake_case			:  bool    ):





  '''simple docstring'''





  lowercase							    =       traverse_util.flatten_dict(variables['target']    )
  lowercase							    =       {'/'.join(SCREAMING_SNAKE_CASE_    ): v for k, v in old.items()}

  # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
  lowercase							    =       'encoder/layers_0/mlp/wi_0/kernel' in old
  print('Split MLP:'		,					SCREAMING_SNAKE_CASE_    )

  lowercase							    =       collections.OrderedDict()

  # Shared embeddings.
  lowercase							    =       old['token_embedder/embedding']

  # Encoder.
  for i in range(SCREAMING_SNAKE_CASE_    ):
    # Block i, layer 0 (Self Attention).
    lowercase							    =       tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'encoder'		,					'pre_attention_layer_norm'    )
    lowercase							    =       tax_attention_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'encoder'		,					'attention'    )
    lowercase							    =       layer_norm
    lowercase							    =       k.T
    lowercase							    =       o.T
    lowercase							    =       q.T
    lowercase							    =       v.T

    # Block i, layer 1 (MLP).
    lowercase							    =       tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'encoder'		,					'pre_mlp_layer_norm'    )
    lowercase							    =       tax_mlp_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'encoder'		,					SCREAMING_SNAKE_CASE_    )
    lowercase							    =       layer_norm
    if split_mlp_wi:
      lowercase							    =       wi[0].T
      lowercase							    =       wi[1].T
    else:
      lowercase							    =       wi.T
    lowercase							    =       wo.T

  lowercase							    =       old[
      'encoder/relpos_bias/rel_embedding'
  ].T
  lowercase							    =       old['encoder/encoder_norm/scale']

  if not is_encoder_only:
    # Decoder.
    for i in range(SCREAMING_SNAKE_CASE_    ):
      # Block i, layer 0 (Self Attention).
      lowercase							    =       tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'decoder'		,					'pre_self_attention_layer_norm'    )
      lowercase							    =       tax_attention_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'decoder'		,					'self_attention'    )
      lowercase							    =       layer_norm
      lowercase							    =       k.T
      lowercase							    =       o.T
      lowercase							    =       q.T
      lowercase							    =       v.T

      # Block i, layer 1 (Cross Attention).
      lowercase							    =       tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'decoder'		,					'pre_cross_attention_layer_norm'    )
      lowercase							    =       tax_attention_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'decoder'		,					'encoder_decoder_attention'    )
      lowercase							    =       layer_norm
      lowercase							    =       k.T
      lowercase							    =       o.T
      lowercase							    =       q.T
      lowercase							    =       v.T

      # Block i, layer 2 (MLP).
      lowercase							    =       tax_layer_norm_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'decoder'		,					'pre_mlp_layer_norm'    )
      lowercase							    =       tax_mlp_lookup(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					'decoder'		,					SCREAMING_SNAKE_CASE_    )
      lowercase							    =       layer_norm
      if split_mlp_wi:
        lowercase							    =       wi[0].T
        lowercase							    =       wi[1].T
      else:
        lowercase							    =       wi.T
      lowercase							    =       wo.T

    lowercase							    =       old['decoder/decoder_norm/scale']
    lowercase							    =       old[
        'decoder/relpos_bias/rel_embedding'
    ].T

    # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
    if "decoder/logits_dense/kernel" in old:
      lowercase							    =       old['decoder/logits_dense/kernel'].T

  return new
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Optional[int]		,					__snake_case			:  bool    ):





  '''simple docstring'''





  lowercase							    =       collections.OrderedDict([(k, torch.from_numpy(v.copy()    )) for (k, v) in converted_params.items()]    )

  # Add what is missing.
  if "encoder.embed_tokens.weight" not in state_dict:
    lowercase							    =       state_dict['shared.weight']

  if not is_encoder_only:
    if "decoder.embed_tokens.weight" not in state_dict:
      lowercase							    =       state_dict['shared.weight']

    if "lm_head.weight" not in state_dict:  # For old 1.0 models.
      print('Using shared word embeddings as lm_head.'    )
      lowercase							    =       state_dict['shared.weight']

  return state_dict
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  int		,					__snake_case			:  Dict		,					__snake_case			:  Union[str, Any]		,					__snake_case			:  List[str]    ):





  '''simple docstring'''





  lowercase							    =       checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE_    )
  lowercase							    =       convert_tax_to_pytorch(SCREAMING_SNAKE_CASE_		,					num_layers=config.num_layers		,					is_encoder_only=SCREAMING_SNAKE_CASE_    )
  lowercase							    =       make_state_dict(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_    )
  model.load_state_dict(SCREAMING_SNAKE_CASE_		,					strict=SCREAMING_SNAKE_CASE_    )
def 						_SCREAMING_SNAKE_CASE (    __snake_case			:  Union[str, Any]		,					__snake_case			:  Optional[Any]		,					__snake_case			:  Tuple		,					__snake_case			:  bool = False    ):





  '''simple docstring'''





  lowercase							    =       TaConfig.from_json_file(SCREAMING_SNAKE_CASE_    )
  print(f'Building PyTorch model from configuration: {config}'    )
  # Non-v1.1 checkpoints could also use T5Model, but this works for all.
  # The v1.0 checkpoints will simply have an LM head that is the word embeddings.
  if is_encoder_only:
    lowercase							    =       TaEncoderModel(SCREAMING_SNAKE_CASE_    )
  else:
    lowercase							    =       TaForConditionalGeneration(SCREAMING_SNAKE_CASE_    )

  # Load weights from tf checkpoint
  load_tax_weights_in_ta(SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_    )

  # Save pytorch-model
  print(f'Save PyTorch model to {pytorch_dump_path}'    )
  model.save_pretrained(SCREAMING_SNAKE_CASE_    )

  # Verify that we can load the checkpoint.
  model.from_pretrained(SCREAMING_SNAKE_CASE_    )
  print('Done'    )


if __name__ == "__main__":
    _UpperCamelCase		:  Any						=		argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.')
    # Required parameters
    parser.add_argument(
        '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.'
    )
    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.'
    )
    parser.add_argument(
        '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False
    )
    _UpperCamelCase		:  int						=		parser.parse_args()
    convert_tax_checkpoint_to_pytorch(
        args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only
    )





import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


snake_case_			  = datasets.utils.logging.get_logger(__name__)

snake_case_			  = ['''names''', '''prefix''']
snake_case_			  = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
snake_case_			  = ['''encoding_errors''', '''on_bad_lines''']
snake_case_			  = ['''date_format''']


@dataclass
class       SCREAMING_SNAKE_CASE__					(datasets.BuilderConfig     ):
    __lowerCamelCase						:       str														=     ","
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[Union[int, List[int], str]]														=     "infer"
    __lowerCamelCase						:       Optional[List[str]]														=     None
    __lowerCamelCase						:       Optional[List[str]]														=     None
    __lowerCamelCase						:       Optional[Union[int, str, List[int], List[str]]]														=     None
    __lowerCamelCase						:       Optional[Union[List[int], List[str]]]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       Optional[Literal["c", "python", "pyarrow"]]														=     None
    __lowerCamelCase						:       Dict[Union[int, str], Callable[[Any], Any]]														=     None
    __lowerCamelCase						:       Optional[list]														=     None
    __lowerCamelCase						:       Optional[list]														=     None
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       Optional[Union[int, List[int]]]														=     None
    __lowerCamelCase						:       Optional[int]														=     None
    __lowerCamelCase						:       Optional[Union[str, List[str]]]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       str														=     "."
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       str														=     '"'
    __lowerCamelCase						:       int														=     0
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       int														=     0
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       int														=     1_0000
    __lowerCamelCase						:       Optional[datasets.Features]														=     None
    __lowerCamelCase						:       Optional[str]														=     "strict"
    __lowerCamelCase						:       Literal["error", "warn", "skip"]														=     "error"
    __lowerCamelCase						:       Optional[str]														=     None





    def       snake_case_				(      self):
         if self.delimiter is not None:
              lowercase__    :   List[Any]      =       self.delimiter
         if self.column_names is not None:
              lowercase__    :   Optional[int]      =       self.column_names





    @property
    def       snake_case_				(      self):
         lowercase__    :   Dict      =       {
             'sep': self.sep,
             'header': self.header,
             'names': self.names,
             'index_col': self.index_col,
             'usecols': self.usecols,
             'prefix': self.prefix,
             'mangle_dupe_cols': self.mangle_dupe_cols,
             'engine': self.engine,
             'converters': self.converters,
             'true_values': self.true_values,
             'false_values': self.false_values,
             'skipinitialspace': self.skipinitialspace,
             'skiprows': self.skiprows,
             'nrows': self.nrows,
             'na_values': self.na_values,
             'keep_default_na': self.keep_default_na,
             'na_filter': self.na_filter,
             'verbose': self.verbose,
             'skip_blank_lines': self.skip_blank_lines,
             'thousands': self.thousands,
             'decimal': self.decimal,
             'lineterminator': self.lineterminator,
             'quotechar': self.quotechar,
             'quoting': self.quoting,
             'escapechar': self.escapechar,
             'comment': self.comment,
             'encoding': self.encoding,
             'dialect': self.dialect,
             'error_bad_lines': self.error_bad_lines,
             'warn_bad_lines': self.warn_bad_lines,
             'skipfooter': self.skipfooter,
             'doublequote': self.doublequote,
             'memory_map': self.memory_map,
             'float_precision': self.float_precision,
             'chunksize': self.chunksize,
             'encoding_errors': self.encoding_errors,
             'on_bad_lines': self.on_bad_lines,
             'date_format': self.date_format,
         }

         # some kwargs must not be passed if they don't have a default value
         # some others are deprecated and we can also not pass them if they are the default value
         for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
              if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()						,   a):
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 2):
              for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
              for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

         return pd_read_csv_kwargs



class       SCREAMING_SNAKE_CASE__					(datasets.ArrowBasedBuilder     ):
    __lowerCamelCase						:       Optional[Any]														=     CsvConfig





    def       snake_case_				(      self):
         return datasets.DatasetInfo(features=self.config.features)





    def       snake_case_				(      self						,   a):
         if not self.config.data_files:
              raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""")
         lowercase__    :   Any      =       dl_manager.download_and_extract(self.config.data_files)
         if isinstance(a						,   (str, list, tuple)):
              lowercase__    :   List[str]      =       data_files
              if isinstance(a						,   a):
                   lowercase__    :   Optional[Any]      =       [files]
              lowercase__    :   Optional[int]      =       [dl_manager.iter_files(a) for file in files]
              return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,   gen_kwargs={'files': files})]
         lowercase__    :   int      =       []
         for split_name, files in data_files.items():
              if isinstance(a						,   a):
                   lowercase__    :   Optional[int]      =       [files]
              lowercase__    :   Tuple      =       [dl_manager.iter_files(a) for file in files]
              splits.append(datasets.SplitGenerator(name=a						,   gen_kwargs={'files': files}))
         return splits





    def       snake_case_				(      self						,   a):
         if self.config.features is not None:
              lowercase__    :   Optional[int]      =       self.config.features.arrow_schema
              if all(not require_storage_cast(a) for feature in self.config.features.values()):
                   # cheaper cast
                   lowercase__    :   Dict      =       pa.Table.from_arrays([pa_table[field.name] for field in schema]						,   schema=a)
              else:
                   # more expensive cast; allows str <-> int/float or str to Audio for example
                   lowercase__    :   Optional[Any]      =       table_cast(a						,   a)
         return pa_table





    def       snake_case_				(      self						,   a):
         lowercase__    :   List[Any]      =       self.config.features.arrow_schema if self.config.features else None
         # dtype allows reading an int column as str
         lowercase__    :   Optional[int]      =       (
             {
                 name: dtype.to_pandas_dtype() if not require_storage_cast(a) else object
                 for name, dtype, feature in zip(schema.names						,   schema.types						,   self.config.features.values())
             }
             if schema is not None
             else None
         )
         for file_idx, file in enumerate(itertools.chain.from_iterable(a)):
              lowercase__    :   int      =       pd.read_csv(a						,   iterator=a						,   dtype=a						,   **self.config.pd_read_csv_kwargs)
              try:
                   for batch_idx, df in enumerate(a):
                        lowercase__    :   List[str]      =       pa.Table.from_pandas(a)
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                        yield (file_idx, batch_idx), self._cast_table(a)
              except ValueError as e:
                   logger.error(f"""Failed to read file '{file}' with error {type(a)}: {e}""")
                   raise

