



'''simple docstring'''





import argparse
import collections

import numpy as np
import torch
from flax import traverse_util
from tax import checkpoints

from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()





def   a_   (		_UpperCAmelCase    :      Optional[int] ,_UpperCAmelCase    :      Any ,_UpperCAmelCase    :      List[Any]				)    ->  Tuple:
      return params[f'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :]





def   a_   (		_UpperCAmelCase    :      Optional[int] ,_UpperCAmelCase    :      List[Any] ,_UpperCAmelCase    :      int ,_UpperCAmelCase    :      List[Any]="attention"				)    ->  Union[str, Any]:
      __snake_case :   str													=    np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :]				)
      __snake_case :   str													=    k_tmp.reshape(k_tmp.shape[0] ,k_tmp.shape[1] * k_tmp.shape[2]				)
      __snake_case :   List[Any]													=    np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :]				)
      __snake_case :   List[str]													=    o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] ,o_tmp.shape[2]				)
      __snake_case :   Any													=    np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :]				)
      __snake_case :   Tuple													=    q_tmp.reshape(q_tmp.shape[0] ,q_tmp.shape[1] * q_tmp.shape[2]				)
      __snake_case :   Tuple													=    np.ascontiguousarray(params[f'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :]				)
      __snake_case :   Dict													=    v_tmp.reshape(v_tmp.shape[0] ,v_tmp.shape[1] * v_tmp.shape[2]				)
      return k, o, q, v





def   a_   (		_UpperCAmelCase    :      str ,_UpperCAmelCase    :      List[str] ,_UpperCAmelCase    :      Union[str, Any] ,_UpperCAmelCase    :      Dict=False				)    ->  List[str]:
      if split_mlp_wi:
            __snake_case :   Any													=    params[f'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :]
            __snake_case :   Optional[Any]													=    params[f'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :]
            __snake_case :   Any													=    (wi_a, wi_a)
      else:
            __snake_case :   Dict													=    params[f'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :]

      __snake_case :   Optional[Any]													=    params[f'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :]
      return wi, wo





def   a_   (		_UpperCAmelCase    :      Optional[Any] ,_UpperCAmelCase    :      Union[str, Any] ,_UpperCAmelCase    :      List[str] ,_UpperCAmelCase    :      List[str]				)    ->  List[str]:
      return params[f'''{prefix}/{prefix}/{layer_name}/scale'''][:, i]





def   a_   (		_UpperCAmelCase    :      dict ,*, _UpperCAmelCase    :      int ,_UpperCAmelCase    :      bool ,_UpperCAmelCase    :      bool = False				)    ->  Dict:
      __snake_case :   int													=    traverse_util.flatten_dict(variables['target']				)
      __snake_case :   Dict													=    {'/'.join(_UpperCAmelCase				): v for k, v in old.items()}

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

      __snake_case :   Any													=    collections.OrderedDict()

      # Shared embeddings.
      __snake_case :   Dict													=    old['token_embedder/embedding']

      # Encoder.
      for i in range(_UpperCAmelCase				):
            # Block i, layer 0 (Self Attention).
            __snake_case :   Union[str, Any]													=    tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'encoder' ,'pre_attention_layer_norm'				)
            __snake_case							,     __snake_case							,     __snake_case							,     __snake_case :   Tuple													=    tax_attention_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'encoder' ,'attention'				)
            __snake_case :   Optional[int]													=    layer_norm
            __snake_case :   Union[str, Any]													=    k.T
            __snake_case :   Union[str, Any]													=    o.T
            __snake_case :   List[str]													=    q.T
            __snake_case :   Optional[Any]													=    v.T

            # Block i, layer 1 (MLP).
            __snake_case :   Any													=    tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'encoder' ,'pre_mlp_layer_norm'				)
            __snake_case							,     __snake_case :   int													=    tax_mlp_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'encoder' ,_UpperCAmelCase				)
            __snake_case :   int													=    layer_norm
            if split_mlp_wi:
                  __snake_case :   Any													=    wi[0].T
                  __snake_case :   Union[str, Any]													=    wi[1].T
            else:
                  __snake_case :   Tuple													=    wi.T
            __snake_case :   Tuple													=    wo.T
            if scalable_attention:
                  # convert the rel_embedding of each layer
                  __snake_case :   List[Any]													=    tax_relpos_bias_lookup(
                      _UpperCAmelCase ,_UpperCAmelCase ,'encoder'				).T

      __snake_case :   int													=    old['encoder/encoder_norm/scale']

      if not scalable_attention:
            __snake_case :   List[str]													=    tax_relpos_bias_lookup(
                _UpperCAmelCase ,0 ,'encoder'				).T
            __snake_case :   List[Any]													=    tax_relpos_bias_lookup(
                _UpperCAmelCase ,0 ,'decoder'				).T

      if not is_encoder_only:
            # Decoder.
            for i in range(_UpperCAmelCase				):
                  # Block i, layer 0 (Self Attention).
                  __snake_case :   List[str]													=    tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'decoder' ,'pre_self_attention_layer_norm'				)
                  __snake_case							,     __snake_case							,     __snake_case							,     __snake_case :   List[str]													=    tax_attention_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'decoder' ,'self_attention'				)
                  __snake_case :   Tuple													=    layer_norm
                  __snake_case :   Union[str, Any]													=    k.T
                  __snake_case :   List[str]													=    o.T
                  __snake_case :   List[str]													=    q.T
                  __snake_case :   int													=    v.T

                  # Block i, layer 1 (Cross Attention).
                  __snake_case :   Any													=    tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'decoder' ,'pre_cross_attention_layer_norm'				)
                  __snake_case							,     __snake_case							,     __snake_case							,     __snake_case :   int													=    tax_attention_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'decoder' ,'encoder_decoder_attention'				)
                  __snake_case :   Optional[int]													=    layer_norm
                  __snake_case :   Any													=    k.T
                  __snake_case :   Optional[Any]													=    o.T
                  __snake_case :   List[Any]													=    q.T
                  __snake_case :   Optional[int]													=    v.T

                  # Block i, layer 2 (MLP).
                  __snake_case :   Any													=    tax_layer_norm_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'decoder' ,'pre_mlp_layer_norm'				)
                  __snake_case							,     __snake_case :   List[str]													=    tax_mlp_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'decoder' ,_UpperCAmelCase				)
                  __snake_case :   Tuple													=    layer_norm
                  if split_mlp_wi:
                        __snake_case :   Optional[int]													=    wi[0].T
                        __snake_case :   Union[str, Any]													=    wi[1].T
                  else:
                        __snake_case :   int													=    wi.T
                  __snake_case :   int													=    wo.T

                  if scalable_attention:
                        # convert the rel_embedding of each layer
                        __snake_case :   Union[str, Any]													=    tax_relpos_bias_lookup(_UpperCAmelCase ,_UpperCAmelCase ,'decoder'				).T

            __snake_case :   Union[str, Any]													=    old['decoder/decoder_norm/scale']

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

      return new





def   a_   (		_UpperCAmelCase    :      Optional[Any] ,_UpperCAmelCase    :      bool				)    ->  List[str]:
      __snake_case :   Dict													=    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:
            __snake_case :   Any													=    state_dict['shared.weight']

      if not is_encoder_only:
            if "decoder.embed_tokens.weight" not in state_dict:
                  __snake_case :   Optional[int]													=    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.'				)
                  __snake_case :   List[str]													=    state_dict['shared.weight']

      return state_dict





def   a_   (		_UpperCAmelCase    :      Union[str, Any] ,_UpperCAmelCase    :      str ,_UpperCAmelCase    :      int ,_UpperCAmelCase    :      List[str] ,_UpperCAmelCase    :      Union[str, Any]				)    ->  Tuple:
      __snake_case :   Any													=    checkpoints.load_tax_checkpoint(_UpperCAmelCase				)
      __snake_case :   Union[str, Any]													=    convert_tax_to_pytorch(
          _UpperCAmelCase ,num_layers=config.num_layers ,is_encoder_only=_UpperCAmelCase ,scalable_attention=_UpperCAmelCase				)
      __snake_case :   Any													=    make_state_dict(_UpperCAmelCase ,_UpperCAmelCase				)
      model.load_state_dict(_UpperCAmelCase ,strict=_UpperCAmelCase				)





def   a_   (		_UpperCAmelCase    :      Optional[Any] ,_UpperCAmelCase    :      int ,_UpperCAmelCase    :      Optional[Any] ,_UpperCAmelCase    :      bool = False ,_UpperCAmelCase    :      bool = False ,)    ->  Tuple:
      __snake_case :   List[Any]													=    MTaConfig.from_json_file(_UpperCAmelCase				)
      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:
            __snake_case :   Optional[Any]													=    UMTaEncoderModel(_UpperCAmelCase				)
      else:
            __snake_case :   str													=    UMTaForConditionalGeneration(_UpperCAmelCase				)

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

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

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


if __name__ == "__main__":
    A__    :   List[str]           =					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
    )
    parser.add_argument(
        '''--scalable_attention''',
        action='''store_true''',
        help='''Whether the model uses scaled attention (umt5 model)''',
        default=False,
    )
    A__    :   List[Any]           =					parser.parse_args()
    convert_tax_checkpoint_to_pytorch(
        args.tax_checkpoint_path,
        args.config_file,
        args.pytorch_dump_path,
        args.is_encoder_only,
        args.scalable_attention,
    )








'''simple docstring'''





import qiskit





def   a_   (		_UpperCAmelCase    :      int = 2				)    ->  qiskit.result.counts.Counts:
      __snake_case :   Union[str, Any]													=    qubits

      # Using Aer's simulator
      __snake_case :   List[Any]													=    qiskit.Aer.get_backend('aer_simulator'				)

      # Creating a Quantum Circuit acting on the q register
      __snake_case :   Dict													=    qiskit.QuantumCircuit(_UpperCAmelCase ,_UpperCAmelCase				)

      # Adding a H gate on qubit 0 (now q0 in superposition)
      circuit.h(0				)

      for i in range(1 ,_UpperCAmelCase				):
            # Adding CX (CNOT) gate
            circuit.cx(i - 1 ,_UpperCAmelCase				)

      # Mapping the quantum measurement to the classical bits
      circuit.measure(list(range(_UpperCAmelCase				)				) ,list(range(_UpperCAmelCase				)				)				)

      # Now measuring any one qubit would affect other qubits to collapse
      # their super position and have same state as the measured one.

      # Executing the circuit on the simulator
      __snake_case :   Optional[Any]													=    qiskit.execute(_UpperCAmelCase ,_UpperCAmelCase ,shots=10_00				)

      return job.result().get_counts(_UpperCAmelCase				)


if __name__ == "__main__":
    print(F"""Total count for various states are: {quantum_entanglement(3)}""")



