




from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
		import tensorflow as tf

		from ..tf_utils import stable_softmax


if is_torch_available():
		import torch


__lowerCAmelCase		:				List[str]       			=		logging.get_logger(__name__)




@add_end_docstrings(
    _UpperCamelCase    ,       r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """    ,       )
class     snake_case__							(_UpperCamelCase   ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(      self				:     Dict					,      __lowerCamelCase				:     GenericTensor							)					->     np.ndarray:
							if self.framework == "tf":
										a    =			tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()
							elif self.framework == "pt":
										a    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id					,      as_tuple=__lowerCamelCase							)
							else:
										raise ValueError("Unsupported framework"							)
							return masked_index





				def 							__UpperCAmelCase							(      self				:     Any					,      __lowerCamelCase				:     GenericTensor							)					->     np.ndarray:
							a    =			self.get_masked_index(__lowerCamelCase							)
							a    =			np.prod(masked_index.shape							)
							if numel < 1:
										raise PipelineException(
										    "fill-mask"					,      self.model.base_model_prefix					,      f"""No mask_token ({self.tokenizer.mask_token}) found on the input"""					,      )





				def 							__UpperCAmelCase							(      self				:     Any					,      __lowerCamelCase				:     GenericTensor							)					->     Union[str, Any]:
							if isinstance(__lowerCamelCase					,      __lowerCamelCase							):
										for model_input in model_inputs:
													self._ensure_exactly_one_mask_token(model_input["input_ids"][0]							)
							else:
										for input_ids in model_inputs["input_ids"]:
													self._ensure_exactly_one_mask_token(__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     List[Any]					,      __lowerCamelCase				:     Union[str, Any]					,      __lowerCamelCase				:     Union[str, Any]=None					,      **__lowerCamelCase				:     List[Any]							)					->     Dict[str, GenericTensor]:
							if return_tensors is None:
										a    =			self.framework
							a    =			self.tokenizer(__lowerCamelCase					,      return_tensors=__lowerCamelCase							)
							self.ensure_exactly_one_mask_token(__lowerCamelCase							)
							return model_inputs





				def 							__UpperCAmelCase							(      self				:     Tuple					,      __lowerCamelCase				:     List[Any]							)					->     Dict:
							a    =			self.model(**__lowerCamelCase							)
							a    =			model_inputs["input_ids"]
							return model_outputs





				def 							__UpperCAmelCase							(      self				:     Dict					,      __lowerCamelCase				:     Union[str, Any]					,      __lowerCamelCase				:     Any=5					,      __lowerCamelCase				:     List[Any]=None							)					->     List[str]:
							# Cap top_k if there are targets
							if target_ids is not None and target_ids.shape[0] < top_k:
										a    =			target_ids.shape[0]
							a    =			model_outputs["input_ids"][0]
							a    =			model_outputs["logits"]

							if self.framework == "tf":
										a    =			tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()[:, 0]

										a    =			outputs.numpy()

										a    =			outputs[0, masked_index, :]
										a    =			stable_softmax(__lowerCamelCase					,      axis=-1							)
										if target_ids is not None:
													a    =			tf.gather_nd(tf.squeeze(__lowerCamelCase					,      0							)					,      target_ids.reshape(-1					,      1							)							)
													a    =			tf.expand_dims(__lowerCamelCase					,      0							)

										a    =			tf.math.top_k(__lowerCamelCase					,      k=__lowerCamelCase							)
										a    ,		a    =			topk.values.numpy(), topk.indices.numpy()
							else:
										a    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id					,      as_tuple=__lowerCamelCase							).squeeze(-1							)
										# Fill mask pipeline supports only one ${mask_token} per sample

										a    =			outputs[0, masked_index, :]
										a    =			logits.softmax(dim=-1							)
										if target_ids is not None:
													a    =			probs[..., target_ids]

										a    ,		a    =			probs.topk(__lowerCamelCase							)

							a    =			[]
							a    =			values.shape[0] == 1
							for i, (_values, _predictions) in enumerate(zip(values.tolist()					,      predictions.tolist()							)							):
										a    =			[]
										for v, p in zip(_values					,      _predictions							):
													# Copy is important since we're going to modify this array in place
													a    =			input_ids.numpy().copy()
													if target_ids is not None:
																a    =			target_ids[p].tolist()

													a    =			p
													# Filter padding out:
													a    =			tokens[np.where(tokens != self.tokenizer.pad_token_id							)]
													# Originally we skip special tokens to give readable output.
													# For multi masks though, the other [MASK] would be removed otherwise
													# making the output look odd, so we add them back
													a    =			self.tokenizer.decode(__lowerCamelCase					,      skip_special_tokens=__lowerCamelCase							)
													a    =			{"score": v, "token": p, "token_str": self.tokenizer.decode([p]							), "sequence": sequence}
													row.append(__lowerCamelCase							)
										result.append(__lowerCamelCase							)
							if single_mask:
										return result[0]
							return result





				def 							__UpperCAmelCase							(      self				:     Tuple					,      __lowerCamelCase				:     Any					,      __lowerCamelCase				:     int=None							)					->     Optional[Any]:
							if isinstance(__lowerCamelCase					,      __lowerCamelCase							):
										a    =			[targets]
							try:
										a    =			self.tokenizer.get_vocab()
							except Exception:
										a    =			{}
							a    =			[]
							for target in targets:
										a    =			vocab.get(__lowerCamelCase					,      __lowerCamelCase							)
										if id_ is None:
													a    =			self.tokenizer(
													    __lowerCamelCase					,      add_special_tokens=__lowerCamelCase					,      return_attention_mask=__lowerCamelCase					,      return_token_type_ids=__lowerCamelCase					,      max_length=1					,      truncation=__lowerCamelCase					,      )["input_ids"]
													if len(__lowerCamelCase							) == 0:
																logger.warning(
																    f"""The specified target token `{target}` does not exist in the model vocabulary. """
																    "We cannot replace it with anything meaningful, ignoring it"							)
																continue
													a    =			input_ids[0]
													# XXX: If users encounter this pass
													# it becomes pretty slow, so let's make sure
													# The warning enables them to fix the input to
													# get faster performance.
													logger.warning(
													    f"""The specified target token `{target}` does not exist in the model vocabulary. """
													    f"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_							)}`."""							)
										target_ids.append(id_							)
							a    =			list(set(__lowerCamelCase							)							)
							if len(__lowerCamelCase							) == 0:
										raise ValueError("At least one target must be provided when passed."							)
							a    =			np.array(__lowerCamelCase							)
							return target_ids





				def 							__UpperCAmelCase							(      self				:     Dict					,      __lowerCamelCase				:     Optional[int]=None					,      __lowerCamelCase				:     int=None							)					->     List[str]:
							a    =			{}

							if targets is not None:
										a    =			self.get_target_ids(__lowerCamelCase					,      __lowerCamelCase							)
										a    =			target_ids

							if top_k is not None:
										a    =			top_k

							if self.tokenizer.mask_token_id is None:
										raise PipelineException(
										    "fill-mask"					,      self.model.base_model_prefix					,      "The tokenizer does not define a `mask_token`."							)
							return {}, {}, postprocess_params





				def __call__(      self				:     Union[str, Any]					,      __lowerCamelCase				:     Optional[int]					,      *__lowerCamelCase				:     int					,      **__lowerCamelCase				:     Optional[int]							)					->     Union[str, Any]:
							a    =			super().__call__(__lowerCamelCase					,      **__lowerCamelCase							)
							if isinstance(__lowerCamelCase					,      __lowerCamelCase							) and len(__lowerCamelCase							) == 1:
										return outputs[0]
							return outputs












from copy import deepcopy

import torch
import torch.nn.functional as F
from torch.optim import AdamW
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader

from accelerate.accelerator import Accelerator
from accelerate.state import GradientState
from accelerate.test_utils import RegressionDataset, RegressionModel
from accelerate.utils import DistributedType, is_torch_version, set_seed




def 			__magic_name__				( A		:					Tuple,  A		:					List[Any],  A		:					List[Any],  A		:					Dict   ):






			'''simple docstring'''







			for param, grad_param in zip(model_a.parameters(),  model_b.parameters()   ):
						if not param.requires_grad:
									continue
						if not did_step:
									# Grads should not be in sync
									assert (
									    torch.allclose(param.grad,  grad_param.grad   ) is False
									), F"""Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})"""
						else:
									# Grads should be in sync
									assert (
									    torch.allclose(param.grad,  grad_param.grad   ) is True
									), F"""Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})"""




def 			__magic_name__				( A		:					List[Any],  A		:					int,  A		:					Optional[Any],  A		:					Optional[int],  A		:					Any=True   ):






			'''simple docstring'''







			model.train()
			a    =			model(A   )
			a    =			F.mse_loss(A,  target.to(output.device   )   )
			if not do_backward:
						loss /= accelerator.gradient_accumulation_steps
						loss.backward()
			else:
						accelerator.backward(A   )




def 			__magic_name__				( A		:					Any,  A		:					Any=False   ):






			'''simple docstring'''







			set_seed(42   )
			a    =			RegressionModel()
			a    =			deepcopy(A   )
			a    =			RegressionDataset(length=80   )
			a    =			DataLoader(A,  batch_size=16   )
			model.to(accelerator.device   )
			if sched:
						a    =			AdamW(params=model.parameters(),  lr=1E-3   )
						a    =			AdamW(params=ddp_model.parameters(),  lr=1E-3   )
						a    =			LambdaLR(A,  lr_lambda=lambda A   : epoch**0.65   )
						a    =			LambdaLR(A,  lr_lambda=lambda A   : epoch**0.65   )
			# Make a copy of `model`
			if sched:
						a    ,		a    ,		a    ,		a    =			accelerator.prepare(A,  A,  A,  A   )
			else:
						a    ,		a    =			accelerator.prepare(A,  A   )
			if sched:
						return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched)
			return model, ddp_model, dataloader




def 			__magic_name__				( A		:					List[Any]   ):






			'''simple docstring'''







			a    ,		a    ,		a    =			get_training_setup(A   )
			# Use a single batch
			a    ,		a    =			next(iter(A   )   ).values()
			for iteration in range(3   ):
						# Gather the distributed inputs and targs for the base model
						a    ,		a    =			accelerator.gather((ddp_input, ddp_target)   )
						a    ,		a    =			input.to(accelerator.device   ), target.to(accelerator.device   )
						# Perform our initial ground truth step in non "DDP"
						step_model(A,  A,  A,  A   )
						# Do "gradient accumulation" (noop)
						if iteration % 2 == 0:
									# Accumulate grads locally
									with accelerator.no_sync(A   ):
												step_model(A,  A,  A,  A   )
						else:
									# Sync grads
									step_model(A,  A,  A,  A   )

						# Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync
						check_model_parameters(A,  A,  A,  A   )
						for param, ddp_param in zip(model.parameters(),  ddp_model.parameters()   ):
									if not param.requires_grad:
												continue
									assert torch.allclose(
									    param.grad,  ddp_param.grad   ), F"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})"""

						# Shuffle ddp_input on each iteration
						torch.manual_seed(1337 + iteration   )
						a    =			ddp_input[torch.randperm(len(A   )   )]




def 			__magic_name__				( A		:					Optional[int]   ):






			'''simple docstring'''







			a    ,		a    ,		a    =			get_training_setup(A   )
			# Use a single batch
			a    ,		a    =			next(iter(A   )   ).values()
			for iteration in range(3   ):
						# Gather the distributed inputs and targs for the base model
						a    ,		a    =			accelerator.gather((ddp_input, ddp_target)   )
						a    ,		a    =			input.to(accelerator.device   ), target.to(accelerator.device   )
						# Perform our initial ground truth step in non "DDP"
						step_model(A,  A,  A,  A   )
						# Do "gradient accumulation" (noop)
						if iteration % 2 == 0:
									# Accumulate grads locally
									with accelerator.no_sync(A   ):
												step_model(A,  A,  A,  A   )
						else:
									# Sync grads
									step_model(A,  A,  A,  A   )

						# DDP model and model should only be in sync when not (iteration % 2 == 0)
						for param, ddp_param in zip(model.parameters(),  ddp_model.parameters()   ):
									if not param.requires_grad:
												continue
									if iteration % 2 == 0:
												# Grads should not be in sync
												assert (
												    torch.allclose(param.grad,  ddp_param.grad   ) is False
												), F"""Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})"""
									else:
												# Grads should be in sync
												assert (
												    torch.allclose(param.grad,  ddp_param.grad   ) is True
												), F"""Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})"""

        # Shuffle ddp_input on each iteration
						torch.manual_seed(1337 + iteration   )
						a    =			ddp_input[torch.randperm(len(A   )   )]




def 			__magic_name__				( A		:					List[Any]=False,  A		:					List[Any]=False   ):






			'''simple docstring'''







			a    =			Accelerator(
			    split_batches=A,  dispatch_batches=A,  gradient_accumulation_steps=2   )
			# Test that context manager behaves properly
			a    ,		a    ,		a    =			get_training_setup(A   )
			for iteration, batch in enumerate(A   ):
						a    ,		a    =			batch.values()
						# Gather the distributed inputs and targs for the base model
						a    ,		a    =			accelerator.gather((ddp_input, ddp_target)   )
						a    ,		a    =			input.to(accelerator.device   ), target.to(accelerator.device   )
						# Perform our initial ground truth step in non "DDP"
						step_model(A,  A,  A,  A,  A   )
						# Do "gradient accumulation" (noop)
						with accelerator.accumulate(A   ):
									step_model(A,  A,  A,  A   )

						# DDP model and model should only be in sync when not (iteration % 2 == 0)
						for param, ddp_param in zip(model.parameters(),  ddp_model.parameters()   ):
									if not param.requires_grad:
												continue
									if ((iteration + 1) % 2 == 0) or (iteration == len(A   ) - 1):
												# Grads should be in sync
												assert (
												    torch.allclose(param.grad,  ddp_param.grad   ) is True
												), F"""Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})"""
									else:
												# Grads should not be in sync
												assert (
												    torch.allclose(param.grad,  ddp_param.grad   ) is False
												), F"""Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})"""

        # Shuffle ddp_input on each iteration
						torch.manual_seed(1337 + iteration   )
						a    =			ddp_input[torch.randperm(len(A   )   )]
			GradientState._reset_state()




def 			__magic_name__				( A		:					List[Any]=False,  A		:					Any=False   ):






			'''simple docstring'''







			a    =			Accelerator(
			    split_batches=A,  dispatch_batches=A,  gradient_accumulation_steps=2   )
			# Test that context manager behaves properly
			a    ,		a    ,		a    ,		a    ,		a    ,		a    ,		a    =			get_training_setup(A,  A   )
			for iteration, batch in enumerate(A   ):
						a    ,		a    =			batch.values()
						# Gather the distributed inputs and targs for the base model
						a    ,		a    =			accelerator.gather((ddp_input, ddp_target)   )
						a    ,		a    =			input.to(accelerator.device   ), target.to(accelerator.device   )
						# Perform our initial ground truth step in non "DDP"
						model.train()
						ddp_model.train()
						step_model(A,  A,  A,  A,  A   )
						opt.step()

						if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(A   )):
									if split_batches:
												sched.step()
									else:
												for _ in range(accelerator.num_processes   ):
															sched.step()
						opt.zero_grad()
						# Perform gradient accumulation under wrapper
						with accelerator.accumulate(A   ):
									step_model(A,  A,  A,  A   )
									ddp_opt.step()
									ddp_sched.step()
									ddp_opt.zero_grad()

						# Learning rates should be the same
						assert (
						    opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"]
						), F"""Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n"""
						a    =			(((iteration + 1) % 2) == 0) or ((iteration + 1) == len(A   ))
						if accelerator.num_processes > 1:
									check_model_parameters(A,  A,  A,  A   )
						# Shuffle ddp_input on each iteration
						torch.manual_seed(1337 + iteration   )
			GradientState._reset_state()




def 			__magic_name__				( ):






			'''simple docstring'''







			a    =			Accelerator()

			a    =			RegressionDataset(length=80   )
			a    =			DataLoader(A,  batch_size=16   )
			a    =			RegressionDataset(length=96   )
			a    =			DataLoader(A,  batch_size=16   )
			a    ,		a    =			accelerator.prepare(A,  A   )
			assert accelerator.gradient_state.active_dataloader is None
			for iteration, _ in enumerate(A   ):
						assert id(accelerator.gradient_state.active_dataloader   ) == id(A   )
						if iteration < len(A   ) - 1:
									assert not accelerator.gradient_state.end_of_dataloader
									if iteration == 1:
												for batch_num, _ in enumerate(A   ):
															assert id(accelerator.gradient_state.active_dataloader   ) == id(A   )
															if batch_num < len(A   ) - 1:
																		assert not accelerator.gradient_state.end_of_dataloader
															else:
																		assert accelerator.gradient_state.end_of_dataloader
						else:
									assert accelerator.gradient_state.end_of_dataloader
			assert accelerator.gradient_state.active_dataloader is None




def 			__magic_name__				( ):






			'''simple docstring'''







			a    =			Accelerator()
			a    =			accelerator.state
			if state.local_process_index == 0:
						print("**Test `accumulate` gradient accumulation with dataloader break**"   )
			test_dataloader_break()
			if state.distributed_type == DistributedType.NO:
						if state.local_process_index == 0:
									print("**Test NOOP `no_sync` context manager**"   )
						test_noop_sync(A   )
			if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU):
						if state.local_process_index == 0:
									print("**Test Distributed `no_sync` context manager**"   )
						test_distributed_sync(A   )
			if state.distributed_type == DistributedType.MULTI_GPU:
						for split_batch in [True, False]:
									for dispatch_batches in [True, False]:
												if state.local_process_index == 0:
															print(
															    "**Test `accumulate` gradient accumulation, ",  F"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""",  )
												test_gradient_accumulation(A,  A   )

    # Currently will break on torch 2.0 +, need to investigate why
			if is_torch_version("<",  "2.0"   ) or state.distributed_type == DistributedType.NO:
						if state.local_process_index == 0:
									print(
									    "**Test `accumulate` gradient accumulation with optimizer and scheduler, ",  "`split_batches=False`, `dispatch_batches=False`**",  )
						test_gradient_accumulation_with_opt_and_scheduler()
						if state.distributed_type == DistributedType.MULTI_GPU:
									for split_batch in [True, False]:
												for dispatch_batches in [True, False]:
															if not split_batch and not dispatch_batches:
																		continue
															if state.local_process_index == 0:
																		print(
																		    "**Test `accumulate` gradient accumulation with optimizer and scheduler, ",  F"""`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**""",  )
															test_gradient_accumulation_with_opt_and_scheduler(A,  A   )




def 			__magic_name__				( A		:					Optional[int]   ):






			'''simple docstring'''







			main()


if __name__ == "__main__":
		main()






