




'''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 		snake_case_							(_a			:							List[str]					,     _a			:							List[Any]					,     _a			:							List[Any]  ):
    return params[F"{prefix}/{prefix}/relpos_bias/rel_embedding"][:, i, :]





def 		snake_case_							(_a			:							Dict					,     _a			:							Optional[int]					,     _a			:							Union[str, Any]					,     _a			:							Union[str, Any]="attention"  ):
    UpperCAmelCase     =	UpperCAmelCase     =	np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/key/kernel"][:, i, :, :]  )
    UpperCAmelCase     =	k_tmp.reshape(k_tmp.shape[0]					,     k_tmp.shape[1] * k_tmp.shape[2]  )
    UpperCAmelCase     =	np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/out/kernel"][:, i, :, :]  )
    UpperCAmelCase     =	o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1]					,     o_tmp.shape[2]  )
    UpperCAmelCase     =	np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/query/kernel"][:, i, :, :]  )
    UpperCAmelCase     =	q_tmp.reshape(q_tmp.shape[0]					,     q_tmp.shape[1] * q_tmp.shape[2]  )
    UpperCAmelCase     =	np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/value/kernel"][:, i, :, :]  )
    UpperCAmelCase     =	v_tmp.reshape(v_tmp.shape[0]					,     v_tmp.shape[1] * v_tmp.shape[2]  )
    return k, o, q, v





def 		snake_case_							(_a			:							Dict					,     _a			:							str					,     _a			:							Dict					,     _a			:							Dict=False  ):
    if split_mlp_wi:
        UpperCAmelCase     =	params[F"{prefix}/{prefix}/mlp/wi_0/kernel"][:, i, :]
        UpperCAmelCase     =	params[F"{prefix}/{prefix}/mlp/wi_1/kernel"][:, i, :]
        UpperCAmelCase     =	(wi_a, wi_a)
    else:
        UpperCAmelCase     =	params[F"{prefix}/{prefix}/mlp/wi/kernel"][:, i, :]

    UpperCAmelCase     =	params[F"{prefix}/{prefix}/mlp/wo/kernel"][:, i, :]
    return wi, wo





def 		snake_case_							(_a			:							str					,     _a			:							str					,     _a			:							Dict					,     _a			:							Dict  ):
    return params[F"{prefix}/{prefix}/{layer_name}/scale"][:, i]





def 		snake_case_							(_a			:							dict					,     *, _a			:							int					,     _a			:							bool					,     _a			:							bool = False  ):
    UpperCAmelCase     =	traverse_util.flatten_dict(variables['''target''']  )
    UpperCAmelCase     =	{'''/'''.join(_a  ): v for k, v in old.items()}

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

    UpperCAmelCase     =	collections.OrderedDict()

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

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

        # Block i, layer 1 (MLP).
        UpperCAmelCase     =	tax_layer_norm_lookup(_a					,     _a					,     '''encoder'''					,     '''pre_mlp_layer_norm'''  )
        UpperCAmelCase ,  UpperCAmelCase     =	tax_mlp_lookup(_a					,     _a					,     '''encoder'''					,     _a  )
        UpperCAmelCase     =	layer_norm
        if split_mlp_wi:
            UpperCAmelCase     =	wi[0].T
            UpperCAmelCase     =	wi[1].T
        else:
            UpperCAmelCase     =	wi.T
        UpperCAmelCase     =	wo.T
        if scalable_attention:
            # convert the rel_embedding of each layer
            UpperCAmelCase     =	tax_relpos_bias_lookup(
                _a					,     _a					,     '''encoder'''  ).T

    UpperCAmelCase     =	old['''encoder/encoder_norm/scale''']

    if not scalable_attention:
        UpperCAmelCase     =	tax_relpos_bias_lookup(
            _a					,     0					,     '''encoder'''  ).T
        UpperCAmelCase     =	tax_relpos_bias_lookup(
            _a					,     0					,     '''decoder'''  ).T

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

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

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

            if scalable_attention:
                # convert the rel_embedding of each layer
                UpperCAmelCase     =	tax_relpos_bias_lookup(_a					,     _a					,     '''decoder'''  ).T

        UpperCAmelCase     =	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:
            UpperCAmelCase     =	old['''decoder/logits_dense/kernel'''].T

    return new





def 		snake_case_							(_a			:							List[Any]					,     _a			:							bool  ):
    UpperCAmelCase     =	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:
        UpperCAmelCase     =	state_dict['''shared.weight''']

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

    return state_dict





def 		snake_case_							(_a			:							Optional[Any]					,     _a			:							Union[str, Any]					,     _a			:							Tuple					,     _a			:							Optional[int]					,     _a			:							Optional[int]  ):
    UpperCAmelCase     =	checkpoints.load_tax_checkpoint(_a  )
    UpperCAmelCase     =	convert_tax_to_pytorch(
        _a					,     num_layers=config.num_layers					,     is_encoder_only=_a					,     scalable_attention=_a  )
    UpperCAmelCase     =	make_state_dict(_a					,     _a  )
    model.load_state_dict(_a					,     strict=_a  )





def 		snake_case_							(_a			:							str					,     _a			:							Optional[Any]					,     _a			:							Any					,     _a			:							bool = False					,     _a			:							bool = False					,     ):
    UpperCAmelCase     =	MTaConfig.from_json_file(_a  )
    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:
        UpperCAmelCase     =	UMTaEncoderModel(_a  )
    else:
        UpperCAmelCase     =	UMTaForConditionalGeneration(_a  )

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

    # Save pytorch-model
    print(F"Save PyTorch model to {pytorch_dump_path}"  )
    model.save_pretrained(_a  )

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


if __name__ == "__main__":
   A									=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									=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 argparse
import math
import traceback

import dateutil.parser as date_parser
import requests





def 		snake_case_							(_a			:							List[str]  ):
    UpperCAmelCase     =	{}

    UpperCAmelCase     =	job['''started_at''']
    UpperCAmelCase     =	job['''completed_at''']

    UpperCAmelCase     =	date_parser.parse(_a  )
    UpperCAmelCase     =	date_parser.parse(_a  )

    UpperCAmelCase     =	round((end_datetime - start_datetime).total_seconds() / 60.0  )

    UpperCAmelCase     =	start
    UpperCAmelCase     =	end
    UpperCAmelCase     =	duration_in_min

    return job_info





def 		snake_case_							(_a			:							str					,     _a			:							List[str]=None  ):
    UpperCAmelCase     =	None
    if token is not None:
        UpperCAmelCase     =	{'''Accept''': '''application/vnd.github+json''', '''Authorization''': F"Bearer {token}"}

    UpperCAmelCase     =	F"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100"
    UpperCAmelCase     =	requests.get(_a					,     headers=_a  ).json()
    UpperCAmelCase     =	{}

    try:
        job_time.update({job['''name''']: extract_time_from_single_job(_a  ) for job in result['''jobs''']}  )
        UpperCAmelCase     =	math.ceil((result['''total_count'''] - 1_0_0) / 1_0_0  )

        for i in range(_a  ):
            UpperCAmelCase     =	requests.get(url + F"&page={i + 2}"					,     headers=_a  ).json()
            job_time.update({job['''name''']: extract_time_from_single_job(_a  ) for job in result['''jobs''']}  )

        return job_time
    except Exception:
        print(F"Unknown error, could not fetch links:\n{traceback.format_exc()}"  )

    return {}


if __name__ == "__main__":
   A									=argparse.ArgumentParser()
   # Required parameters
   parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.')
   A									=parser.parse_args()

   A									=get_job_time(args.workflow_run_id)
   A									=dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True))

   for k, v in job_time.items():
      print(f"""{k}: {v["duration"]}""")




