



from __future__ import absolute_import, division, print_function, unicode_literals

from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers import RobertaConfig
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.roberta.modeling_roberta import (
    ROBERTA_INPUTS_DOCSTRING,
    ROBERTA_START_DOCSTRING,
    RobertaEmbeddings,
)

from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy




@add_start_docstrings(
    'The RoBERTa Model transformer with early exiting (DeeRoBERTa). '					,							UpperCamelCase					,							)
class 							lowerCAmelCase__  (	UpperCamelCase						):
					__A     :    Optional[Any]           =						RobertaConfig
					__A     :    Tuple           =						'roberta'







					def __init__(       self      :     Optional[int]			,		_A      :     int):
											super().__init__(_A)

											A__	:							Optional[int]						    = RobertaEmbeddings(_A)
											self.init_weights()




@add_start_docstrings(
    'RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n    also takes care of multi-layer training. '					,							UpperCamelCase					,							)
class 							lowerCAmelCase__  (	UpperCamelCase						):
					__A     :    int           =						RobertaConfig
					__A     :    Dict           =						'roberta'







					def __init__(       self      :     Tuple			,		_A      :     List[Any]):
											super().__init__(_A)
											A__	:							str						    = config.num_labels
											A__	:							List[Any]						    = config.num_hidden_layers

											A__	:							Any						    = DeeRobertaModel(_A)
											A__	:							Optional[int]						    = nn.Dropout(config.hidden_dropout_prob)
											A__	:							List[Any]						    = nn.Linear(config.hidden_size			,		self.config.num_labels)







					@add_start_docstrings_to_model_forward(_A)
					def  _lowercase			(       self      :     Dict			,		_A      :     Optional[Any]=None			,		_A      :     Any=None			,		_A      :     List[Any]=None			,		_A      :     Any=None			,		_A      :     List[Any]=None			,		_A      :     Any=None			,		_A      :     Optional[Any]=None			,		_A      :     List[str]=-1			,		_A      :     str=False			,		):
											A__	:							Any						    = self.num_layers
											try:
																	A__	:							List[str]						    = self.roberta(
																	    _A			,		attention_mask=_A			,		token_type_ids=_A			,		position_ids=_A			,		head_mask=_A			,		inputs_embeds=_A			,		)

																	A__	:							List[str]						    = outputs[1]

																	A__	:							Optional[int]						    = self.dropout(_A)
																	A__	:							Dict						    = self.classifier(_A)
																	A__	:							Union[str, Any]						    = (logits,) + outputs[2:]  # add hidden states and attention if they are here
											except HighwayException as e:
																	A__	:							Optional[Any]						    = e.message
																	A__	:							List[Any]						    = e.exit_layer
																	A__	:							int						    = outputs[0]

											if not self.training:
																	A__	:							str						    = entropy(_A)
																	A__	:							Union[str, Any]						    = []
																	A__	:							Optional[int]						    = []
											if labels is not None:
																	if self.num_labels == 1:
																							#  We are doing regression
																							A__	:							List[Any]						    = MSELoss()
																							A__	:							Tuple						    = loss_fct(logits.view(-1)			,		labels.view(-1))
																	else:
																							A__	:							str						    = CrossEntropyLoss()
																							A__	:							Optional[int]						    = loss_fct(logits.view(-1			,		self.num_labels)			,		labels.view(-1))

																	# work with highway exits
																	A__	:							Tuple						    = []
																	for highway_exit in outputs[-1]:
																							A__	:							Any						    = highway_exit[0]
																							if not self.training:
																													highway_logits_all.append(_A)
																													highway_entropy.append(highway_exit[2])
																							if self.num_labels == 1:
																													#  We are doing regression
																													A__	:							Optional[Any]						    = MSELoss()
																													A__	:							List[Any]						    = loss_fct(highway_logits.view(-1)			,		labels.view(-1))
																							else:
																													A__	:							Union[str, Any]						    = CrossEntropyLoss()
																													A__	:							str						    = loss_fct(highway_logits.view(-1			,		self.num_labels)			,		labels.view(-1))
																							highway_losses.append(_A)

																	if train_highway:
																							A__	:							Any						    = (sum(highway_losses[:-1]),) + outputs
																							# exclude the final highway, of course
																	else:
																							A__	:							Tuple						    = (loss,) + outputs
											if not self.training:
																	A__	:							Any						    = outputs + ((original_entropy, highway_entropy), exit_layer)
																	if output_layer >= 0:
																							A__	:							Union[str, Any]						    = (
																							    (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
																							)  # use the highway of the last layer

											return outputs  # (loss), logits, (hidden_states), (attentions), entropy




import multiprocessing
import os
from typing import BinaryIO, Optional, Union

import fsspec

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader




class 							lowerCAmelCase__  (	UpperCamelCase						):







					def __init__(       self      :     Dict			,		_A      :     NestedDataStructureLike[PathLike]			,		_A      :     Optional[NamedSplit] = None			,		_A      :     Optional[Features] = None			,		_A      :     str = None			,		_A      :     bool = False			,		_A      :     bool = False			,		_A      :     Optional[str] = None			,		_A      :     Optional[int] = None			,		**_A      :     Dict			,		):
											super().__init__(
											    _A			,		split=_A			,		features=_A			,		cache_dir=_A			,		keep_in_memory=_A			,		streaming=_A			,		num_proc=_A			,		**_A			,		)
											A__	:							Optional[int]						    = field
											A__	:							Dict						    = path_or_paths if isinstance(_A			,		_A) else {self.split: path_or_paths}
											A__	:							int						    = Json(
											    cache_dir=_A			,		data_files=_A			,		features=_A			,		field=_A			,		**_A			,		)







					def  _lowercase			(       self      :     Dict):
											# Build iterable dataset
											if self.streaming:
																	A__	:							Union[str, Any]						    = self.builder.as_streaming_dataset(split=self.split)
											# Build regular (map-style) dataset
											else:
																	A__	:							Optional[Any]						    = None
																	A__	:							Any						    = None
																	A__	:							Tuple						    = None
																	A__	:							Tuple						    = None

																	self.builder.download_and_prepare(
																	    download_config=_A			,		download_mode=_A			,		verification_mode=_A			,		base_path=_A			,		num_proc=self.num_proc			,		)
																	A__	:							Any						    = self.builder.as_dataset(
																	    split=self.split			,		verification_mode=_A			,		in_memory=self.keep_in_memory)
											return dataset




class 							lowerCAmelCase__  :







					def __init__(       self      :     Union[str, Any]			,		_A      :     Dataset			,		_A      :     Union[PathLike, BinaryIO]			,		_A      :     Optional[int] = None			,		_A      :     Optional[int] = None			,		**_A      :     Any			,		):
											if num_proc is not None and num_proc <= 0:
																	raise ValueError(F'num_proc {num_proc} must be an integer > 0.')

											A__	:							Tuple						    = dataset
											A__	:							Tuple						    = path_or_buf
											A__	:							int						    = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
											A__	:							Tuple						    = num_proc
											A__	:							Any						    = "utf-8"
											A__	:							Optional[int]						    = to_json_kwargs







					def  _lowercase			(       self      :     Union[str, Any]):
											A__	:							Any						    = self.to_json_kwargs.pop("path_or_buf"			,		_A)
											A__	:							Union[str, Any]						    = self.to_json_kwargs.pop("orient"			,		"records")
											A__	:							List[Any]						    = self.to_json_kwargs.pop("lines"			,		True if orient == "records" else False)
											A__	:							List[Any]						    = self.to_json_kwargs.pop("index"			,		False if orient in ["split", "table"] else True)
											A__	:							int						    = self.to_json_kwargs.pop("compression"			,		_A)

											if compression not in [None, "infer", "gzip", "bz2", "xz"]:
																	raise NotImplementedError(F'`datasets` currently does not support {compression} compression')

											if isinstance(self.path_or_buf			,		(str, bytes, os.PathLike)):
																	with fsspec.open(self.path_or_buf			,		"wb"			,		compression=_A) as buffer:
																							A__	:							int						    = self._write(file_obj=_A			,		orient=_A			,		lines=_A			,		index=_A			,		**self.to_json_kwargs)
											else:
																	if compression:
																							raise NotImplementedError(
																							    F'The compression parameter is not supported when writing to a buffer, but compression={compression}'
																							    " was passed. Please provide a local path instead.")
																	A__	:							Optional[Any]						    = self._write(
																	    file_obj=self.path_or_buf			,		orient=_A			,		lines=_A			,		index=_A			,		**self.to_json_kwargs)
											return written







					def  _lowercase			(       self      :     List[Any]			,		_A      :     int):
											A__    ,       A__    ,       A__    ,       A__    ,       A__	:							Union[str, Any]						    = args

											A__	:							Dict						    = query_table(
											    table=self.dataset.data			,		key=slice(_A			,		offset + self.batch_size)			,		indices=self.dataset._indices			,		)
											A__	:							Dict						    = batch.to_pandas().to_json(
											    path_or_buf=_A			,		orient=_A			,		lines=_A			,		index=_A			,		**_A)
											if not json_str.endswith("\n"):
																	json_str += "\n"
											return json_str.encode(self.encoding)







					def  _lowercase			(       self      :     List[str]			,		_A      :     BinaryIO			,		_A      :     str			,		_A      :     List[Any]			,		_A      :     Optional[Any]			,		**_A      :     Optional[Any]			,		):
											A__	:							Any						    = 0

											if self.num_proc is None or self.num_proc == 1:
																	for offset in logging.tqdm(
																	    range(0			,		len(self.dataset)			,		self.batch_size)			,		unit="ba"			,		disable=not logging.is_progress_bar_enabled()			,		desc="Creating json from Arrow format"			,		):
																							A__	:							List[str]						    = self._batch_json((offset, orient, lines, index, to_json_kwargs))
																							written += file_obj.write(_A)
											else:
																	A__    ,       A__	:							Union[str, Any]						    = len(self.dataset), self.batch_size
																	with multiprocessing.Pool(self.num_proc) as pool:
																							for json_str in logging.tqdm(
																							    pool.imap(
																							        self._batch_json			,		[(offset, orient, lines, index, to_json_kwargs) for offset in range(0			,		_A			,		_A)]			,		)			,		total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size			,		unit="ba"			,		disable=not logging.is_progress_bar_enabled()			,		desc="Creating json from Arrow format"			,		):
																													written += file_obj.write(_A)

											return written