


import numpy as np
import torch
from imwatermark import WatermarkEncoder


# Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66
__snake_case            =   0B101_100_111_110_110_010_010_000_011_110_111_011_000_110_011_110
# bin(x)[2:] gives bits of x as str, use int to convert them to 0/1
__snake_case            =   [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]]




class    UpperCAmelCase					:




			def __init__(						self							:		Tuple						):







						"""simple docstring"""







						UpperCamelCase         =					WATERMARK_BITS
						UpperCamelCase         =					WatermarkEncoder()

						self.encoder.set_watermark("""bits"""       ,       self.watermark						)





			def   lowerCamelCase_					(						self							:		Tuple       ,       __magic_name__							:		torch.FloatTensor						):







						"""simple docstring"""







						if images.shape[-1] < 2_5_6:
									return images

						UpperCamelCase         =					(2_5_5 * (images / 2 + 0.5)).cpu().permute(0       ,       2       ,       3       ,       1						).float().numpy()

						UpperCamelCase         =					[self.encoder.encode(__magic_name__       ,       """dwtDct"""						) for image in images]

						UpperCamelCase         =					torch.from_numpy(np.array(__magic_name__						)						).permute(0       ,       3       ,       1       ,       2						)

						UpperCamelCase         =					torch.clamp(2 * (images / 2_5_5 - 0.5)       ,       min=-1.0       ,       max=1.0						)
						return images








import logging
import os

import quant_trainer
import torch
from torch.utils.data import DataLoader

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput


__snake_case            =   logging.getLogger(__name__)

if is_torch_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm
			import torch_xla.debug.metrics as met




class    UpperCAmelCase					(       __snake_case    ):




			def __init__(						self							:		Dict       ,       *__magic_name__							:		Union[str, Any]       ,       __magic_name__							:		Any=None       ,       __magic_name__							:		Union[str, Any]=None       ,       __magic_name__							:		Any=None       ,       **__magic_name__							:		Optional[Any]						):







						"""simple docstring"""







						super().__init__(*__magic_name__       ,       **__magic_name__						)
						UpperCamelCase         =					eval_examples
						UpperCamelCase         =					post_process_function
						UpperCamelCase         =					quant_trainer_args
						UpperCamelCase         =					1_2_8  # default number of calibration samples




			def   lowerCamelCase_					(						self							:		str       ,       __magic_name__							:		List[Any]=None						):







						"""simple docstring"""







						if calib_dataset is None and self.calib_dataset is None:
									raise ValueError("""Trainer: calibration requires an calib_dataset."""						)
						UpperCamelCase         =					calib_dataset if calib_dataset is not None else self.calib_dataset

						UpperCamelCase         =					self._remove_unused_columns(__magic_name__       ,       description="""Calibration"""						)

						return DataLoader(
						    __magic_name__       ,       batch_size=self.args.eval_batch_size       ,       collate_fn=self.data_collator       ,       drop_last=self.args.dataloader_drop_last       ,       num_workers=self.args.dataloader_num_workers       ,       pin_memory=self.args.dataloader_pin_memory       ,       shuffle=__magic_name__       ,       )




			def   lowerCamelCase_					(						self							:		Tuple       ,       __magic_name__							:		List[str]=None						):







						"""simple docstring"""







						UpperCamelCase         =					self.train_dataset if calib_dataset is None else calib_dataset
						UpperCamelCase         =					self.get_calib_dataloader(__magic_name__						)

						UpperCamelCase         =					self.model
						quant_trainer.configure_model(__magic_name__       ,       self.quant_trainer_args       ,       calib=__magic_name__						)
						model.eval()
						quant_trainer.enable_calibration(__magic_name__						)

						logger.info("""***** Running calibration *****"""						)
						logger.info(F'  Num examples = {self.calib_num}'						)
						logger.info(F'  Batch size = {calib_dataloader.batch_size}'						)

						for step, inputs in enumerate(__magic_name__						):
									# Prediction step
									UpperCamelCase  ,  UpperCamelCase  ,  UpperCamelCase         =					self.prediction_step(__magic_name__       ,       __magic_name__       ,       prediction_loss_only=__magic_name__						)
									if (step + 1) * calib_dataloader.batch_size >= self.calib_num:
												break

						quant_trainer.finish_calibration(__magic_name__       ,       self.quant_trainer_args						)
						UpperCamelCase         =					model




			def   lowerCamelCase_					(						self							:		Any       ,       __magic_name__							:		Optional[int]=None       ,       __magic_name__							:		Optional[Any]=None       ,       __magic_name__							:		Union[str, Any]=None       ,       __magic_name__							:		str = "eval"						):







						"""simple docstring"""







						UpperCamelCase         =					self.eval_dataset if eval_dataset is None else eval_dataset
						UpperCamelCase         =					self.get_eval_dataloader(__magic_name__						)
						UpperCamelCase         =					self.eval_examples if eval_examples is None else eval_examples

						# Temporarily disable metric computation, we will do it in the loop here.
						UpperCamelCase         =					self.compute_metrics
						UpperCamelCase         =					None
						UpperCamelCase         =					self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
						try:
									UpperCamelCase         =					eval_loop(
									    __magic_name__       ,       description="""Evaluation"""       ,       prediction_loss_only=True if compute_metrics is None else None       ,       ignore_keys=__magic_name__       ,       )
						finally:
									UpperCamelCase         =					compute_metrics

						if self.post_process_function is not None and self.compute_metrics is not None:
									UpperCamelCase         =					self.post_process_function(__magic_name__       ,       __magic_name__       ,       output.predictions						)
									UpperCamelCase         =					self.compute_metrics(__magic_name__						)

									# Prefix all keys with metric_key_prefix + '_'
									for key in list(metrics.keys()						):
												if not key.startswith(F'{metric_key_prefix}_'						):
															UpperCamelCase         =					metrics.pop(__magic_name__						)

									self.log(__magic_name__						)
						else:
									UpperCamelCase         =					{}

						if self.args.tpu_metrics_debug or self.args.debug:
									# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
									xm.master_print(met.metrics_report()						)

						UpperCamelCase         =					self.callback_handler.on_evaluate(self.args       ,       self.state       ,       self.control       ,       __magic_name__						)
						return metrics




			def   lowerCamelCase_					(						self							:		Dict       ,       __magic_name__							:		List[str]       ,       __magic_name__							:		List[Any]       ,       __magic_name__							:		List[Any]=None       ,       __magic_name__							:		str = "test"						):







						"""simple docstring"""







						UpperCamelCase         =					self.get_test_dataloader(__magic_name__						)

						# Temporarily disable metric computation, we will do it in the loop here.
						UpperCamelCase         =					self.compute_metrics
						UpperCamelCase         =					None
						UpperCamelCase         =					self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
						try:
									UpperCamelCase         =					eval_loop(
									    __magic_name__       ,       description="""Prediction"""       ,       prediction_loss_only=True if compute_metrics is None else None       ,       ignore_keys=__magic_name__       ,       )
						finally:
									UpperCamelCase         =					compute_metrics

						if self.post_process_function is None or self.compute_metrics is None:
									return output

						UpperCamelCase         =					self.post_process_function(__magic_name__       ,       __magic_name__       ,       output.predictions       ,       """predict"""						)
						UpperCamelCase         =					self.compute_metrics(__magic_name__						)

						# Prefix all keys with metric_key_prefix + '_'
						for key in list(metrics.keys()						):
									if not key.startswith(F'{metric_key_prefix}_'						):
												UpperCamelCase         =					metrics.pop(__magic_name__						)

						return PredictionOutput(predictions=predictions.predictions       ,       label_ids=predictions.label_ids       ,       metrics=__magic_name__						)





			def   lowerCamelCase_					(						self							:		List[str]       ,       __magic_name__							:		Optional[Any]="./"						):







						"""simple docstring"""







						UpperCamelCase         =					self.eval_dataset
						UpperCamelCase         =					self.get_eval_dataloader(__magic_name__						)

						UpperCamelCase         =					next(iter(__magic_name__						)						)

						# saving device - to make it consistent
						UpperCamelCase         =					torch.device("""cuda""" if torch.cuda.is_available() else """cpu"""						)

						# convert to tuple
						UpperCamelCase         =					tuple(v.to(__magic_name__						) for k, v in batch.items()						)

						logger.info("""Converting model to be onnx compatible"""						)
						from pytorch_quantization.nn import TensorQuantizer

						UpperCamelCase         =					True

						UpperCamelCase         =					self.model.to(__magic_name__						)

						model.eval()
						model.float()

						UpperCamelCase         =					model.module if hasattr(__magic_name__       ,       """module"""						) else model
						quant_trainer.configure_model(__magic_name__       ,       self.quant_trainer_args						)

						UpperCamelCase         =					os.path.join(__magic_name__       ,       """model.onnx"""						)
						logger.info(F'exporting model to {output_model_file}'						)

						UpperCamelCase         =					{0: """batch_size""", 1: """seq_len"""}

						torch.onnx.export(
						    __magic_name__       ,       __magic_name__       ,       __magic_name__       ,       export_params=__magic_name__       ,       opset_version=1_3       ,       do_constant_folding=__magic_name__       ,       input_names=["""input_ids""", """attention_mask""", """token_type_ids"""]       ,       output_names=["""output_start_logits""", """output_end_logits"""]       ,       dynamic_axes={
						        """input_ids""": axes,
						        """attention_mask""": axes,
						        """token_type_ids""": axes,
						        """output_start_logits""": axes,
						        """output_end_logits""": axes,
						    }       ,       verbose=__magic_name__       ,       )
						logger.info("""onnx export finished"""						)




