



import torch
from torch import autograd





class 							lowerCAmelCase_		(		autograd.Function     ):







		@staticmethod
		def 					a_  (    UpperCAmelCase_  :   List[Any]       ,		UpperCAmelCase_  :   Optional[int]       ,		UpperCAmelCase_  :   Optional[int]       ,		UpperCAmelCase_  :   List[str]					)       ->		List[Any]:


						'''simple docstring'''







						_UpperCAmelCase						:  List[Any]     					=	inputs.numel()
						_UpperCAmelCase						:  int     					=	int(0.005 * nb_elems					) + 1
						if sigmoid:
										_UpperCAmelCase						:  Union[str, Any]     					=	(torch.sigmoid(__lowercase					) > threshold).type(inputs.type()					)
						else:
										_UpperCAmelCase						:  int     					=	(inputs > threshold).type(inputs.type()					)
						if mask.sum() < nb_min:
										# We limit the pruning so that at least 0.5% (half a percent) of the weights are remaining
										_UpperCAmelCase						:  str     					=	inputs.flatten().kthvalue(max(nb_elems - nb_min       ,		1					)					).values
										_UpperCAmelCase						:  Optional[Any]     					=	(inputs > k_threshold).type(inputs.type()					)
						return mask







		@staticmethod
		def 					a_  (    UpperCAmelCase_  :   List[Any]       ,		UpperCAmelCase_  :   Tuple					)       ->		Any:


						'''simple docstring'''







						return gradOutput, None, None





class 							lowerCAmelCase_		(		autograd.Function     ):







		@staticmethod
		def 					a_  (    UpperCAmelCase_  :   str       ,		UpperCAmelCase_  :   List[str]       ,		UpperCAmelCase_  :   Any					)       ->		Union[str, Any]:


						'''simple docstring'''







						_UpperCAmelCase						:  Optional[int]     					=	inputs.clone()
						_UpperCAmelCase						:  str     					=	inputs.flatten().sort(descending=__lowercase					)
						_UpperCAmelCase						:  Union[str, Any]     					=	int(threshold * inputs.numel()					)

						# flat_out and mask access the same memory.
						_UpperCAmelCase						:  Optional[Any]     					=	mask.flatten()
						_UpperCAmelCase						:  Optional[int]     					=	0
						_UpperCAmelCase						:  Tuple     					=	1
						return mask







		@staticmethod
		def 					a_  (    UpperCAmelCase_  :   Optional[int]       ,		UpperCAmelCase_  :   Any					)       ->		Optional[int]:


						'''simple docstring'''







						return gradOutput, None





class 							lowerCAmelCase_		(		UpperCAmelCase__     ):







		@staticmethod
		def 					a_  (    UpperCAmelCase_  :   Union[str, Any]       ,		UpperCAmelCase_  :   Optional[Any]					)       ->		Dict:


						'''simple docstring'''







						_UpperCAmelCase						:  Optional[int]     					=	inputs.clone()
						_UpperCAmelCase						:  int     					=	inputs.abs().flatten().sort(descending=__lowercase					)
						_UpperCAmelCase						:  str     					=	int(threshold * inputs.numel()					)

						# flat_out and mask access the same memory.
						_UpperCAmelCase						:  List[Any]     					=	mask.flatten()
						_UpperCAmelCase						:  Optional[int]     					=	0
						_UpperCAmelCase						:  List[str]     					=	1
						return mask




import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
						import transformer_engine.pytorch as te



def       lowerCAmelCase			(		lowerCAmelCase_			, lowerCAmelCase_=True			, lowerCAmelCase_=True			, lowerCAmelCase_=True			)->			Union[str, Any]:
				if not is_fpa_available():
								raise ImportError('''Using `convert_model` requires transformer_engine to be installed.'''			)
				for name, module in model.named_children():
								if isinstance(lowerCAmelCase_			, nn.Linear			) and to_transformer_engine and _convert_linear:
												# Return early if the linear layer weights are not multiples of 16
												if any(p % 16 != 0 for p in module.weight.shape			):
																return
												lowerCAmelCase_			:   Optional[int]     					=					module.bias is not None
												lowerCAmelCase_			:   Any     					=					te.Linear(
												    module.in_features			, module.out_features			, bias=lowerCAmelCase_			, params_dtype=module.weight.dtype			)
												lowerCAmelCase_			:   Dict     					=					module.weight.data.clone()
												if has_bias:
																lowerCAmelCase_			:   Any     					=					module.bias.data.clone()

												setattr(lowerCAmelCase_			, lowerCAmelCase_			, lowerCAmelCase_			)
								elif isinstance(lowerCAmelCase_			, nn.LayerNorm			) and to_transformer_engine and _convert_ln:
												lowerCAmelCase_			:   List[str]     					=					te.LayerNorm(module.normalized_shape[0]			, eps=module.eps			, params_dtype=module.weight.dtype			)
												lowerCAmelCase_			:   Union[str, Any]     					=					module.weight.data.clone()
												lowerCAmelCase_			:   List[Any]     					=					module.bias.data.clone()

												setattr(lowerCAmelCase_			, lowerCAmelCase_			, lowerCAmelCase_			)
								elif isinstance(lowerCAmelCase_			, te.Linear			) and not to_transformer_engine and _convert_linear:
												lowerCAmelCase_			:   Dict     					=					module.bias is not None
												lowerCAmelCase_			:   Union[str, Any]     					=					nn.Linear(
												    module.in_features			, module.out_features			, bias=lowerCAmelCase_			, params_dtype=module.weight.dtype			)
												lowerCAmelCase_			:   Optional[Any]     					=					module.weight.data.clone()
												if has_bias:
																lowerCAmelCase_			:   Union[str, Any]     					=					module.bias.data.clone()

												setattr(lowerCAmelCase_			, lowerCAmelCase_			, lowerCAmelCase_			)
								elif isinstance(lowerCAmelCase_			, te.LayerNorm			) and not to_transformer_engine and _convert_ln:
												lowerCAmelCase_			:   Union[str, Any]     					=					nn.LayerNorm(module.normalized_shape[0]			, eps=module.eps			, params_dtype=module.weight.dtype			)
												lowerCAmelCase_			:   List[str]     					=					module.weight.data.clone()
												lowerCAmelCase_			:   List[Any]     					=					module.bias.data.clone()

												setattr(lowerCAmelCase_			, lowerCAmelCase_			, lowerCAmelCase_			)
								else:
												convert_model(
												    lowerCAmelCase_			, to_transformer_engine=lowerCAmelCase_			, _convert_linear=_convert_linear			, _convert_ln=_convert_ln			, )




def       lowerCAmelCase			(		lowerCAmelCase_			)->			str:
				if not is_fpa_available():
								raise ImportError('''Using `has_transformer_engine_layers` requires transformer_engine to be installed.'''			)
				for m in model.modules():
								if isinstance(lowerCAmelCase_			, (te.LayerNorm, te.Linear)			):
												return True
				return False