

'''simple docstring'''



import time
from contextlib import contextmanager
from pathlib import Path

import pytest
import requests
from huggingface_hub.hf_api import HfApi, HfFolder


__snake_case			:     Optional[int]										=      '__DUMMY_TRANSFORMERS_USER__'
__snake_case			:     List[Any]										=      'Dummy User'
__snake_case			:     List[str]										=      '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'

__snake_case			:     List[str]										=      'https://hub-ci.huggingface.co'
__snake_case			:     Optional[int]										=      CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}'
__snake_case			:     Any										=      CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}'
__snake_case			:     str										=      Path('~/.huggingface/hub_ci_token').expanduser()
@pytest.fixture
def 						__lowerCamelCase	(       __snake_case					:		Any	)	->							Union[str, Any]:
						monkeypatch.setattr(
						    """huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE""",		__snake_case	)
@pytest.fixture
def 						__lowerCamelCase	(       __snake_case					:		str	)	->							str:
						monkeypatch.setattr("""datasets.config.HF_ENDPOINT""",		__snake_case	)
						monkeypatch.setattr("""datasets.config.HUB_DATASETS_URL""",		__snake_case	)
@pytest.fixture
def 						__lowerCamelCase	(       __snake_case					:		Any	)	->							Optional[int]:
						monkeypatch.setattr("""huggingface_hub.hf_api.HfFolder.path_token""",		__snake_case	)
@pytest.fixture
def 						__lowerCamelCase	(       __snake_case					:		Union[str, Any],		__snake_case					:		Tuple	)	->							Optional[Any]:
						HfFolder.save_token(__snake_case	)
						yield
						HfFolder.delete_token()
@pytest.fixture(scope="""session"""	)
def 						__lowerCamelCase	(       )	->							List[str]:
						return HfApi(endpoint=__snake_case	)
@pytest.fixture(scope="""session"""	)
def 						__lowerCamelCase	(       __snake_case					:		HfApi	)	->							List[Any]:
						A__					:       Optional[int]     =HfFolder.get_token()
						HfFolder.save_token(__snake_case	)
						yield CI_HUB_USER_TOKEN
						if previous_token is not None:
												HfFolder.save_token(__snake_case	)
@pytest.fixture
def 						__lowerCamelCase	(       __snake_case					:		Any	)	->							Optional[Any]:





						def _cleanup_repo(__snake_case					:		Optional[int]	):
												hf_api.delete_repo(__snake_case,		token=__snake_case,		repo_type="""dataset"""	)

						return _cleanup_repo
@pytest.fixture
def 						__lowerCamelCase	(       __snake_case					:		List[str]	)	->							str:





						@contextmanager
						def _temporary_repo(__snake_case					:		int	):
												try:
																		yield repo_id
												finally:
																		cleanup_repo(__snake_case	)

						return _temporary_repo
@pytest.fixture(scope="""session"""	)
def 						__lowerCamelCase	(       __snake_case					:		HfApi,		__snake_case					:		int,		__snake_case					:		Optional[int]	)	->							Union[str, Any]:
						A__					:       Optional[int]     =f"repo_txt_data-{int(time.time() * 10E3	)}"
						A__					:       Tuple     =f"{CI_HUB_USER}/{repo_name}"
						hf_api.create_repo(__snake_case,		token=__snake_case,		repo_type="""dataset""",		private=__snake_case	)
						hf_api.upload_file(
						    token=__snake_case,		path_or_fileobj=str(__snake_case	),		path_in_repo="""data/text_data.txt""",		repo_id=__snake_case,		repo_type="""dataset""",		)
						yield repo_id
						try:
												hf_api.delete_repo(__snake_case,		token=__snake_case,		repo_type="""dataset"""	)
						except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
												pass
@pytest.fixture()
def 						__lowerCamelCase	(       __snake_case					:		Optional[Any],		__snake_case					:		List[Any],		__snake_case					:		Dict	)	->							Optional[int]:
						return hf_private_dataset_repo_txt_data_
@pytest.fixture(scope="""session"""	)
def 						__lowerCamelCase	(       __snake_case					:		HfApi,		__snake_case					:		Any,		__snake_case					:		str	)	->							Union[str, Any]:
						A__					:       Union[str, Any]     =f"repo_zipped_txt_data-{int(time.time() * 10E3	)}"
						A__					:       Dict     =f"{CI_HUB_USER}/{repo_name}"
						hf_api.create_repo(__snake_case,		token=__snake_case,		repo_type="""dataset""",		private=__snake_case	)
						hf_api.upload_file(
						    token=__snake_case,		path_or_fileobj=str(__snake_case	),		path_in_repo="""data.zip""",		repo_id=__snake_case,		repo_type="""dataset""",		)
						yield repo_id
						try:
												hf_api.delete_repo(__snake_case,		token=__snake_case,		repo_type="""dataset"""	)
						except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
												pass
@pytest.fixture()
def 						__lowerCamelCase	(       __snake_case					:		Optional[int],		__snake_case					:		Dict,		__snake_case					:		str	)	->							List[Any]:
						return hf_private_dataset_repo_zipped_txt_data_
@pytest.fixture(scope="""session"""	)
def 						__lowerCamelCase	(       __snake_case					:		HfApi,		__snake_case					:		str,		__snake_case					:		Union[str, Any]	)	->							str:
						A__					:       Tuple     =f"repo_zipped_img_data-{int(time.time() * 10E3	)}"
						A__					:       Optional[Any]     =f"{CI_HUB_USER}/{repo_name}"
						hf_api.create_repo(__snake_case,		token=__snake_case,		repo_type="""dataset""",		private=__snake_case	)
						hf_api.upload_file(
						    token=__snake_case,		path_or_fileobj=str(__snake_case	),		path_in_repo="""data.zip""",		repo_id=__snake_case,		repo_type="""dataset""",		)
						yield repo_id
						try:
												hf_api.delete_repo(__snake_case,		token=__snake_case,		repo_type="""dataset"""	)
						except (requests.exceptions.HTTPError, ValueError):  # catch http error and token invalid error
												pass
@pytest.fixture()
def 						__lowerCamelCase	(       __snake_case					:		Optional[int],		__snake_case					:		str,		__snake_case					:		List[str]	)	->							Union[str, Any]:
						return hf_private_dataset_repo_zipped_img_data_




'''simple docstring'''



import torch
from torch import nn



class lowerCamelCase			(  nn.Module						):



			'''simple docstring'''






			def __init__(				self	:						Any		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						List[Any]		,      lowerCAmelCase_	:						Dict		,      lowerCAmelCase_	:						str		,      lowerCAmelCase_	:						Optional[int]=1		,      lowerCAmelCase_	:						str=False			)      ->		List[str]:





									'''simple docstring'''
									super().__init__()

									A__					:       Any     =n_token
									A__					:       int     =d_embed
									A__					:       Any     =d_proj

									A__					:       Tuple     =cutoffs + [n_token]
									A__					:       Optional[Any]     =[0] + self.cutoffs
									A__					:       Dict     =div_val

									A__					:       str     =self.cutoffs[0]
									A__					:       Optional[Any]     =len(self.cutoffs			) - 1
									A__					:       List[Any]     =self.shortlist_size + self.n_clusters

									if self.n_clusters > 0:
															A__					:       Any     =nn.Parameter(torch.zeros(self.n_clusters		,      self.d_embed			)			)
															A__					:       str     =nn.Parameter(torch.zeros(self.n_clusters			)			)

									A__					:       Union[str, Any]     =nn.ModuleList()
									A__					:       Optional[int]     =nn.ParameterList()

									if div_val == 1:
															for i in range(len(self.cutoffs			)			):
																					if d_proj != d_embed:
																											self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_		,      lowerCAmelCase_			)			)			)
																					else:
																											self.out_projs.append(lowerCAmelCase_			)

															self.out_layers.append(nn.Linear(lowerCAmelCase_		,      lowerCAmelCase_			)			)
									else:
															for i in range(len(self.cutoffs			)			):
																					A__   ,						A__					:       Optional[int]     =self.cutoff_ends[i], self.cutoff_ends[i + 1]
																					A__					:       Tuple     =d_embed // (div_val**i)

																					self.out_projs.append(nn.Parameter(torch.FloatTensor(lowerCAmelCase_		,      lowerCAmelCase_			)			)			)

																					self.out_layers.append(nn.Linear(lowerCAmelCase_		,      r_idx - l_idx			)			)

									A__					:       Optional[int]     =keep_order


			def lowercase__						(				self	:						Dict		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Union[str, Any]		,      lowerCAmelCase_	:						Any			)      ->		Union[str, Any]:





									'''simple docstring'''
									if proj is None:
															A__					:       Optional[int]     =nn.functional.linear(lowerCAmelCase_		,      lowerCAmelCase_		,      bias=lowerCAmelCase_			)
									else:
															# if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
															A__					:       Optional[int]     =nn.functional.linear(lowerCAmelCase_		,      proj.t().contiguous()			)
															A__					:       Union[str, Any]     =nn.functional.linear(lowerCAmelCase_		,      lowerCAmelCase_		,      bias=lowerCAmelCase_			)
															# else:
															#     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
															#     if bias is not None:
															#         logit = logit + bias

									return logit


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						List[str]		,      lowerCAmelCase_	:						List[Any]=None		,      lowerCAmelCase_	:						Dict=False			)      ->		Optional[int]:





									'''simple docstring'''

									if labels is not None:
															# Shift so that tokens < n predict n
															A__					:       Optional[Any]     =hidden[..., :-1, :].contiguous()
															A__					:       List[Any]     =labels[..., 1:].contiguous()
															A__					:       Optional[int]     =hidden.view(-1		,      hidden.size(-1			)			)
															A__					:       str     =labels.view(-1			)
															if hidden.size(0			) != labels.size(0			):
																					raise RuntimeError("""Input and labels should have the same size in the batch dimension."""			)
									else:
															A__					:       Optional[int]     =hidden.view(-1		,      hidden.size(-1			)			)

									if self.n_clusters == 0:
															A__					:       Optional[Any]     =self._compute_logit(lowerCAmelCase_		,      self.out_layers[0].weight		,      self.out_layers[0].bias		,      self.out_projs[0]			)
															if labels is not None:
																					A__					:       Tuple     =labels != -1_00
																					A__					:       int     =torch.zeros_like(lowerCAmelCase_		,      dtype=hidden.dtype		,      device=hidden.device			)
																					A__					:       Union[str, Any]     =(
																					    -nn.functional.log_softmax(lowerCAmelCase_		,      dim=-1			)[mask].gather(1		,      labels[mask].unsqueeze(1			)			).squeeze(1			)
																					)
															else:
																					A__					:       List[Any]     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=-1			)
									else:
															# construct weights and biases
															A__   ,						A__					:       Any     =[], []
															for i in range(len(self.cutoffs			)			):
																					if self.div_val == 1:
																											A__   ,						A__					:       Optional[int]     =self.cutoff_ends[i], self.cutoff_ends[i + 1]
																											A__					:       int     =self.out_layers[0].weight[l_idx:r_idx]
																											A__					:       List[str]     =self.out_layers[0].bias[l_idx:r_idx]
																					else:
																											A__					:       List[str]     =self.out_layers[i].weight
																											A__					:       Union[str, Any]     =self.out_layers[i].bias

																					if i == 0:
																											A__					:       Tuple     =torch.cat([weight_i, self.cluster_weight]		,      dim=0			)
																											A__					:       List[str]     =torch.cat([bias_i, self.cluster_bias]		,      dim=0			)

																					weights.append(lowerCAmelCase_			)
																					biases.append(lowerCAmelCase_			)

															A__   ,						A__   ,						A__					:       Tuple     =weights[0], biases[0], self.out_projs[0]

															A__					:       List[Any]     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)
															A__					:       int     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)

															if labels is None:
																					A__					:       Union[str, Any]     =hidden.new_empty((head_logit.size(0			), self.n_token)			)
															else:
																					A__					:       Union[str, Any]     =torch.zeros_like(lowerCAmelCase_		,      dtype=hidden.dtype		,      device=hidden.device			)

															A__					:       Any     =0
															A__					:       Tuple     =[0] + self.cutoffs
															for i in range(len(lowerCAmelCase_			) - 1			):
																					A__   ,						A__					:       Tuple     =cutoff_values[i], cutoff_values[i + 1]

																					if labels is not None:
																											A__					:       Tuple     =(labels >= l_idx) & (labels < r_idx)
																											A__					:       Any     =mask_i.nonzero().squeeze()

																											if indices_i.numel() == 0:
																																	continue

																											A__					:       int     =labels.index_select(0		,      lowerCAmelCase_			) - l_idx
																											A__					:       List[str]     =head_logprob.index_select(0		,      lowerCAmelCase_			)
																											A__					:       str     =hidden.index_select(0		,      lowerCAmelCase_			)
																					else:
																											A__					:       Optional[Any]     =hidden

																					if i == 0:
																											if labels is not None:
																																	A__					:       Optional[Any]     =head_logprob_i.gather(1		,      target_i[:, None]			).squeeze(1			)
																											else:
																																	A__					:       Union[str, Any]     =head_logprob[:, : self.cutoffs[0]]
																					else:
																											A__   ,						A__   ,						A__					:       Dict     =weights[i], biases[i], self.out_projs[i]

																											A__					:       List[Any]     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)
																											A__					:       List[Any]     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)
																											A__					:       Optional[Any]     =self.cutoffs[0] + i - 1  # No probability for the head cluster
																											if labels is not None:
																																	A__					:       Union[str, Any]     =head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
																																	    1		,      target_i[:, None]			).squeeze(1			)
																											else:
																																	A__					:       List[str]     =head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
																																	A__					:       Tuple     =logprob_i

																					if labels is not None:
																											if (hasattr(self		,      """keep_order"""			) and self.keep_order) or keep_order:
																																	out.index_copy_(0		,      lowerCAmelCase_		,      -logprob_i			)
																											else:
																																	out[offset : offset + logprob_i.size(0			)].copy_(-logprob_i			)
																											offset += logprob_i.size(0			)

									return out



			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						Optional[Any]			)      ->		Any:





									'''simple docstring'''
									if self.n_clusters == 0:
															A__					:       List[str]     =self._compute_logit(lowerCAmelCase_		,      self.out_layers[0].weight		,      self.out_layers[0].bias		,      self.out_projs[0]			)
															return nn.functional.log_softmax(lowerCAmelCase_		,      dim=-1			)
									else:
															# construct weights and biases
															A__   ,						A__					:       List[str]     =[], []
															for i in range(len(self.cutoffs			)			):
																					if self.div_val == 1:
																											A__   ,						A__					:       int     =self.cutoff_ends[i], self.cutoff_ends[i + 1]
																											A__					:       List[str]     =self.out_layers[0].weight[l_idx:r_idx]
																											A__					:       List[Any]     =self.out_layers[0].bias[l_idx:r_idx]
																					else:
																											A__					:       Dict     =self.out_layers[i].weight
																											A__					:       Any     =self.out_layers[i].bias

																					if i == 0:
																											A__					:       List[str]     =torch.cat([weight_i, self.cluster_weight]		,      dim=0			)
																											A__					:       Tuple     =torch.cat([bias_i, self.cluster_bias]		,      dim=0			)

																					weights.append(lowerCAmelCase_			)
																					biases.append(lowerCAmelCase_			)

															A__   ,						A__   ,						A__					:       Optional[int]     =weights[0], biases[0], self.out_projs[0]
															A__					:       Any     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)

															A__					:       Dict     =hidden.new_empty((head_logit.size(0			), self.n_token)			)
															A__					:       Dict     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)

															A__					:       Tuple     =[0] + self.cutoffs
															for i in range(len(lowerCAmelCase_			) - 1			):
																					A__   ,						A__					:       List[Any]     =cutoff_values[i], cutoff_values[i + 1]

																					if i == 0:
																											A__					:       Tuple     =head_logprob[:, : self.cutoffs[0]]
																					else:
																											A__   ,						A__   ,						A__					:       Any     =weights[i], biases[i], self.out_projs[i]

																											A__					:       Dict     =self._compute_logit(lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_		,      lowerCAmelCase_			)
																											A__					:       str     =nn.functional.log_softmax(lowerCAmelCase_		,      dim=1			)

																											A__					:       str     =head_logprob[:, -i] + tail_logprob_i
																											A__					:       List[Any]     =logprob_i

															return out

