


import argparse
import os

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to properly calculate the metrics on the
# validation dataset when in a distributed system, and builds off the
# `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


SCREAMING_SNAKE_CASE       :      Optional[int]												= 16
SCREAMING_SNAKE_CASE       :      List[Any]												= 32



def 				UpperCamelCase_(      lowerCamelCase_							, lowerCamelCase_ = 16 )    ->						Dict:
    _lowercase       :							Any      		=		AutoTokenizer.from_pretrained('bert-base-cased' )
    _lowercase       :							int      		=		load_dataset('glue'							, 'mrpc' )

    def tokenize_function(lowerCamelCase_ ):
        # max_length=None => use the model max length (it's actually the default)
        _lowercase       :							Any      		=		tokenizer(examples['sentence1']							, examples['sentence2']							, truncation=lowerCamelCase_							, max_length=lowerCamelCase_ )
        return outputs

    # Apply the method we just defined to all the examples in all the splits of the dataset
    # starting with the main process first:
    with accelerator.main_process_first():
        _lowercase       :							int      		=		datasets.map(
            lowerCamelCase_							, batched=lowerCamelCase_							, remove_columns=['idx', 'sentence1', 'sentence2']							, )

    # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
    # transformers library
    _lowercase       :							Any      		=		tokenized_datasets.rename_column('label'							, 'labels' )

    def collate_fn(lowerCamelCase_ ):
        # On TPU it's best to pad everything to the same length or training will be very slow.
        _lowercase       :							Optional[Any]      		=		128 if accelerator.distributed_type == DistributedType.TPU else None
        # When using mixed precision we want round multiples of 8/16
        if accelerator.mixed_precision == "fp8":
            _lowercase       :							Tuple      		=		16
        elif accelerator.mixed_precision != "no":
            _lowercase       :							Tuple      		=		8
        else:
            _lowercase       :							Optional[int]      		=		None

        return tokenizer.pad(
            lowerCamelCase_							, padding='longest'							, max_length=lowerCamelCase_							, pad_to_multiple_of=lowerCamelCase_							, return_tensors='pt'							, )

    # Instantiate dataloaders.
    _lowercase       :							Dict      		=		DataLoader(
        tokenized_datasets['train']							, shuffle=lowerCamelCase_							, collate_fn=lowerCamelCase_							, batch_size=lowerCamelCase_ )
    _lowercase       :							Optional[Any]      		=		DataLoader(
        tokenized_datasets['validation']							, shuffle=lowerCamelCase_							, collate_fn=lowerCamelCase_							, batch_size=lowerCamelCase_ )

    return train_dataloader, eval_dataloader


# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
 from accelerate.test_utils.training import mocked_dataloaders

 SCREAMING_SNAKE_CASE       :      Tuple												= mocked_dataloaders  # noqa: F811



def 				UpperCamelCase_(      lowerCamelCase_							, lowerCamelCase_ )    ->						List[Any]:
    # For testing only
    if os.environ.get('TESTING_MOCKED_DATALOADERS'							, lowerCamelCase_ ) == "1":
        _lowercase       :							int      		=		2
    # Initialize accelerator
    _lowercase       :							List[Any]      		=		Accelerator(cpu=args.cpu							, mixed_precision=args.mixed_precision )
    # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
    _lowercase       :							Dict      		=		config['lr']
    _lowercase       :							Optional[Any]      		=		int(config['num_epochs'] )
    _lowercase       :							Optional[Any]      		=		int(config['seed'] )
    _lowercase       :							List[str]      		=		int(config['batch_size'] )

    _lowercase       :							int      		=		evaluate.load('glue'							, 'mrpc' )

    # If the batch size is too big we use gradient accumulation
    _lowercase       :							Optional[int]      		=		1
    if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
        _lowercase       :							Any      		=		batch_size // MAX_GPU_BATCH_SIZE
        _lowercase       :							List[str]      		=		MAX_GPU_BATCH_SIZE

    set_seed(lowerCamelCase_ )
    _lowercase		,				_lowercase       :							Any      		=		get_dataloaders(lowerCamelCase_							, lowerCamelCase_ )
    # Instantiate the model (we build the model here so that the seed also control new weights initialization)
    _lowercase       :							Union[str, Any]      		=		AutoModelForSequenceClassification.from_pretrained('bert-base-cased'							, return_dict=lowerCamelCase_ )

    # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
    # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
    # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
    _lowercase       :							List[str]      		=		model.to(accelerator.device )

    # Instantiate optimizer
    _lowercase       :							int      		=		AdamW(params=model.parameters()							, lr=lowerCamelCase_ )

    # Instantiate scheduler
    _lowercase       :							Union[str, Any]      		=		get_linear_schedule_with_warmup(
        optimizer=lowerCamelCase_							, num_warmup_steps=100							, num_training_steps=(len(lowerCamelCase_ ) * num_epochs) // gradient_accumulation_steps							, )

    # Prepare everything
    # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
    # prepare method.
    _lowercase		,				_lowercase		,				_lowercase		,				_lowercase		,				_lowercase       :							int      		=		accelerator.prepare(
        lowerCamelCase_							, lowerCamelCase_							, lowerCamelCase_							, lowerCamelCase_							, lowerCamelCase_ )

    # Now we train the model
    for epoch in range(lowerCamelCase_ ):
        model.train()
        for step, batch in enumerate(lowerCamelCase_ ):
            # We could avoid this line since we set the accelerator with `device_placement=True`.
            batch.to(accelerator.device )
            _lowercase       :							List[Any]      		=		model(**lowerCamelCase_ )
            _lowercase       :							Tuple      		=		outputs.loss
            _lowercase       :							int      		=		loss / gradient_accumulation_steps
            accelerator.backward(lowerCamelCase_ )
            if step % gradient_accumulation_steps == 0:
                optimizer.step()
                lr_scheduler.step()
                optimizer.zero_grad()

        model.eval()
        _lowercase       :							Tuple      		=		0
        for step, batch in enumerate(lowerCamelCase_ ):
            # We could avoid this line since we set the accelerator with `device_placement=True`.
            batch.to(accelerator.device )
            with torch.no_grad():
                _lowercase       :							List[str]      		=		model(**lowerCamelCase_ )
            _lowercase       :							Union[str, Any]      		=		outputs.logits.argmax(dim=-1 )
            _lowercase		,				_lowercase       :							Optional[Any]      		=		accelerator.gather((predictions, batch['labels']) )
            # New Code #
            # First we check if it's a distributed system
            if accelerator.use_distributed:
                # Then see if we're on the last batch of our eval dataloader
                if step == len(lowerCamelCase_ ) - 1:
                    # Last batch needs to be truncated on distributed systems as it contains additional samples
                    _lowercase       :							List[Any]      		=		predictions[: len(eval_dataloader.dataset ) - samples_seen]
                    _lowercase       :							Dict      		=		references[: len(eval_dataloader.dataset ) - samples_seen]
                else:
                    # Otherwise we add the number of samples seen
                    samples_seen += references.shape[0]
            # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
            # accelerator.gather_for_metrics((predictions, batch["labels"]))
            metric.add_batch(
                predictions=lowerCamelCase_							, references=lowerCamelCase_							, )

        _lowercase       :							List[str]      		=		metric.compute()
        # Use accelerator.print to print only on the main process.
        accelerator.print(F'''epoch {epoch}:'''							, lowerCamelCase_ )



def 				UpperCamelCase_(      )    ->						Union[str, Any]:
    _lowercase       :							List[Any]      		=		argparse.ArgumentParser(description='Simple example of training script.' )
    parser.add_argument(
        '--mixed_precision'							, type=lowerCamelCase_							, default=lowerCamelCase_							, choices=['no', 'fp16', 'bf16', 'fp8']							, help='Whether to use mixed precision. Choose'
        'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'
        'and an Nvidia Ampere GPU.'							, )
    parser.add_argument('--cpu'							, action='store_true'							, help='If passed, will train on the CPU.' )
    _lowercase       :							str      		=		parser.parse_args()
    _lowercase       :							Dict      		=		{'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16}
    training_function(lowerCamelCase_							, lowerCamelCase_ )


if __name__ == "__main__":
 main()






import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
 import onnxruntime as ort






class _lowerCamelCase(						_a, unittest.TestCase   ):
       # TODO: is there an appropriate internal test set?
       lowercase_ :	int     =			"""ssube/stable-diffusion-x4-upscaler-onnx"""
       def 			UpperCamelCase     (					self,      lowerCamelCase=0)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Dict      		=		floats_tensor((1, 3, 1_28, 1_28),      rng=random.Random(lowerCamelCase))
           _lowercase       :							Union[str, Any]      		=		torch.manual_seed(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		{
               'prompt': 'A painting of a squirrel eating a burger',
               'image': image,
               'generator': generator,
               'num_inference_steps': 3,
               'guidance_scale': 7.5,
               'output_type': 'numpy',
           }
           return inputs
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Tuple      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Dict      		=		self.get_dummy_inputs()
           _lowercase       :							Optional[int]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							Optional[int]      		=		image[0, -3:, -3:, -1].flatten()

           # started as 128, should now be 512
           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3])
           assert np.abs(image_slice - expected_slice).max() < 1E-1
       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							int      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							str      		=		PNDMScheduler.from_config(pipe.scheduler.config,      skip_prk_steps=lowerCamelCase)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							List[str]      		=		self.get_dummy_inputs()
           _lowercase       :							List[Any]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							str      		=		image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							int      		=		np.array(
               [0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4])
           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1
       def 			UpperCamelCase     (					self)       ->   Optional[Any]:




           """simple docstring"""

           _lowercase       :							Dict      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							Optional[int]      		=		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Optional[int]      		=		self.get_dummy_inputs()
           _lowercase       :							Union[str, Any]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							str      		=		image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Optional[int]      		=		np.array(
               [0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							List[str]      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							List[str]      		=		EulerDiscreteScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Dict      		=		self.get_dummy_inputs()
           _lowercase       :							Optional[Any]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							Optional[int]      		=		image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3])
           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1




       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

           _lowercase       :							Tuple      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint,      provider='CPUExecutionProvider')
           _lowercase       :							Any      		=		EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Any      		=		self.get_dummy_inputs()
           _lowercase       :							List[str]      		=		pipe(**lowerCamelCase).images
           _lowercase       :							Any      		=		image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-1






@nightly
@require_onnxruntime
@require_torch_gpu
class _lowerCamelCase(						unittest.TestCase   ):
       @property
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           return (
               "CUDAExecutionProvider",
               {
                   "gpu_mem_limit": "15000000000",  # 15GB
                   "arena_extend_strategy": "kSameAsRequested",
               },
           )
       @property
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							Union[str, Any]      		=		ort.SessionOptions()
           _lowercase       :							str      		=		False
           return options
       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               '/img2img/sketch-mountains-input.jpg')
           _lowercase       :							int      		=		init_image.resize((1_28, 1_28))
           # using the PNDM scheduler by default
           _lowercase       :							Tuple      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(
               'ssube/stable-diffusion-x4-upscaler-onnx',      provider=self.gpu_provider,      sess_options=self.gpu_options,      )
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Optional[int]      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							List[Any]      		=		torch.manual_seed(0)
           _lowercase       :							str      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      guidance_scale=7.5,      num_inference_steps=10,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							List[Any]      		=		output.images
           _lowercase       :							List[Any]      		=		images[0, 2_55:2_58, 3_83:3_86, -1]

           assert images.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							List[Any]      		=		np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2])
           # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

           assert np.abs(image_slice.flatten() - expected_slice).max() < 2E-2




       def 			UpperCamelCase     (					self)       ->   Any:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		load_image(
               'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
               '/img2img/sketch-mountains-input.jpg')
           _lowercase       :							int      		=		init_image.resize((1_28, 1_28))
           _lowercase       :							str      		=		LMSDiscreteScheduler.from_pretrained(
               'ssube/stable-diffusion-x4-upscaler-onnx',      subfolder='scheduler')
           _lowercase       :							Dict      		=		OnnxStableDiffusionUpscalePipeline.from_pretrained(
               'ssube/stable-diffusion-x4-upscaler-onnx',      scheduler=lowerCamelCase,      provider=self.gpu_provider,      sess_options=self.gpu_options,      )
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase       :							Optional[int]      		=		'A fantasy landscape, trending on artstation'

           _lowercase       :							List[Any]      		=		torch.manual_seed(0)
           _lowercase       :							str      		=		pipe(
               prompt=lowerCamelCase,      image=lowerCamelCase,      guidance_scale=7.5,      num_inference_steps=20,      generator=lowerCamelCase,      output_type='np',      )
           _lowercase       :							str      		=		output.images
           _lowercase       :							str      		=		images[0, 2_55:2_58, 3_83:3_86, -1]

           assert images.shape == (1, 5_12, 5_12, 3)
           _lowercase       :							Union[str, Any]      		=		np.array(
               [0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6])
           # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

           assert np.abs(image_slice.flatten() - expected_slice).max() < 2E-2


