"""simple docstring"""
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce





def 				lowerCAmelCase__      (     _UpperCamelCase    :			int   )   ->			Optional[Any]:





						"""simple docstring"""






						return (torch.arange(state.num_processes   ) + 1.0 + (state.num_processes * state.process_index)).to(state.device   )





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict   )   ->			Dict:





						"""simple docstring"""






						snake_case        =     create_tensor(_UpperCamelCase   )
						snake_case        =     gather(_UpperCamelCase   )
						assert gathered_tensor.tolist() == list(range(1	,     state.num_processes**2 + 1   )   )





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Any   )   ->			Any:





						"""simple docstring"""






						snake_case        =     [state.process_index]
						snake_case        =     gather_object(_UpperCamelCase   )
						assert len(_UpperCamelCase   ) == state.num_processes, f"""{gathered_obj}, {len(_UpperCamelCase   )} != {state.num_processes}"""
						assert gathered_obj == list(range(state.num_processes   )   ), f"""{gathered_obj} != {list(range(state.num_processes   )   )}"""





def 				lowerCAmelCase__      (     _UpperCamelCase    :			List[str]   )   ->			str:





						"""simple docstring"""






						snake_case        =     create_tensor(_UpperCamelCase   )
						snake_case        =     broadcast(_UpperCamelCase   )
						assert broadcasted_tensor.shape == torch.Size([state.num_processes]   )
						assert broadcasted_tensor.tolist() == list(range(1	,     state.num_processes + 1   )   )





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict   )   ->			Any:





						"""simple docstring"""






						if state.is_main_process:
												snake_case        =     torch.arange(state.num_processes + 1   ).to(state.device   )
						else:
												snake_case        =     torch.arange(state.num_processes   ).to(state.device   )
						snake_case        =     pad_across_processes(_UpperCamelCase   )
						assert padded_tensor.shape == torch.Size([state.num_processes + 1]   )
						if not state.is_main_process:
												assert padded_tensor.tolist() == list(range(0	,     state.num_processes   )   ) + [0]





def 				lowerCAmelCase__      (     _UpperCamelCase    :			str   )   ->			Dict:





						"""simple docstring"""






						if state.num_processes != 2:
												return
						snake_case        =     create_tensor(_UpperCamelCase   )
						snake_case        =     reduce(_UpperCamelCase	,     'sum'   )
						snake_case        =     torch.tensor([4.0, 6]   ).to(state.device   )
						assert torch.allclose(_UpperCamelCase	,     _UpperCamelCase   ), f"""{reduced_tensor} != {truth_tensor}"""





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Optional[int]   )   ->			List[Any]:





						"""simple docstring"""






						if state.num_processes != 2:
												return
						snake_case        =     create_tensor(_UpperCamelCase   )
						snake_case        =     reduce(_UpperCamelCase	,     'mean'   )
						snake_case        =     torch.tensor([2.0, 3]   ).to(state.device   )
						assert torch.allclose(_UpperCamelCase	,     _UpperCamelCase   ), f"""{reduced_tensor} != {truth_tensor}"""





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Union[str, Any]   )   ->			str:





						"""simple docstring"""






						main()





def 				lowerCAmelCase__      (     )   ->			List[Any]:





						"""simple docstring"""






						snake_case        =     PartialState()
						state.print(f"""State: {state}"""   )
						state.print('testing gather'   )
						test_gather(_UpperCamelCase   )
						state.print('testing gather_object'   )
						test_gather_object(_UpperCamelCase   )
						state.print('testing broadcast'   )
						test_broadcast(_UpperCamelCase   )
						state.print('testing pad_across_processes'   )
						test_pad_across_processes(_UpperCamelCase   )
						state.print('testing reduce_sum'   )
						test_reduce_sum(_UpperCamelCase   )
						state.print('testing reduce_mean'   )
						test_reduce_mean(_UpperCamelCase   )


if __name__ == "__main__":
					main()



"""simple docstring"""
import argparse
import math
import traceback

import dateutil.parser as date_parser
import requests





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Any   )   ->			int:





						"""simple docstring"""






						snake_case        =     {}

						snake_case        =     job['started_at']
						snake_case        =     job['completed_at']

						snake_case        =     date_parser.parse(_UpperCamelCase   )
						snake_case        =     date_parser.parse(_UpperCamelCase   )

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

						snake_case        =     start
						snake_case        =     end
						snake_case        =     duration_in_min

						return job_info





def 				lowerCAmelCase__      (     _UpperCamelCase    :			Dict	,     _UpperCamelCase    :			Any=None   )   ->			Union[str, Any]:





						"""simple docstring"""






						snake_case        =     None
						if token is not None:
												snake_case        =     {'Accept': 'application/vnd.github+json', 'Authorization': f"""Bearer {token}"""}

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

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

												for i in range(_UpperCamelCase   ):
																		snake_case        =     requests.get(url + f"""&page={i + 2}"""	,     headers=_UpperCamelCase   ).json()
																		job_time.update({job['name']: extract_time_from_single_job(_UpperCamelCase   ) 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__":
					SCREAMING_SNAKE_CASE__   =					argparse.ArgumentParser()
					# Required parameters
					parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.")
					SCREAMING_SNAKE_CASE__   =					parser.parse_args()

					SCREAMING_SNAKE_CASE__   =					get_job_time(args.workflow_run_id)
					SCREAMING_SNAKE_CASE__   =					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']}""")


