



'''simple docstring'''




import gc
import unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
 import jax
 import jax.numpy as jnp
 from flax.jax_utils import replicate
 from flax.training.common_utils import shard


@slow
@require_flax
class       UpperCAmelCase__  (       unittest.TestCase			):






   """simple docstring"""
   def 		_lowerCamelCase (self				)    ->     Optional[Any]:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
   def 		_lowerCamelCase (self				)    ->     int:
        lowercase_				,lowercase_					:       List[Any]     				=					FlaxStableDiffusionPipeline.from_pretrained(
            'stabilityai/stable-diffusion-2'       ,				revision='bf16'       ,				dtype=jnp.bfloataa       ,				)

        lowercase_					:       Optional[int]     				=					'A painting of a squirrel eating a burger'
        lowercase_					:       str     				=					jax.device_count()
        lowercase_					:       Optional[Any]     				=					num_samples * [prompt]
        lowercase_					:       List[Any]     				=					sd_pipe.prepare_inputs(_a				)

        lowercase_					:       str     				=					replicate(_a				)
        lowercase_					:       Optional[Any]     				=					shard(_a				)

        lowercase_					:       Union[str, Any]     				=					jax.random.PRNGKey(0				)
        lowercase_					:       Optional[Any]     				=					jax.random.split(_a       ,				jax.device_count()				)

        lowercase_					:       str     				=					sd_pipe(_a       ,				_a       ,				_a       ,				num_inference_steps=25       ,				jit=_a				)[0]
        assert images.shape == (jax.device_count(), 1, 768, 768, 3)

        lowercase_					:       List[str]     				=					images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]				)
        lowercase_					:       List[str]     				=					images[0, 253:256, 253:256, -1]

        lowercase_					:       Tuple     				=					jnp.asarray(jax.device_get(image_slice.flatten()				)				)
        lowercase_					:       str     				=					jnp.array([0.42_38, 0.44_14, 0.43_95, 0.44_53, 0.46_29, 0.45_90, 0.45_31, 0.4_55_08, 0.45_12]				)
        print(f'''output_slice: {output_slice}'''				)
        assert jnp.abs(output_slice - expected_slice				).max() < 1e-2





   def 		_lowerCamelCase (self				)    ->     List[str]:
        lowercase_					:       Optional[Any]     				=					'stabilityai/stable-diffusion-2'
        lowercase_				,lowercase_					:       Dict     				=					FlaxDPMSolverMultistepScheduler.from_pretrained(_a       ,				subfolder='scheduler'				)
        lowercase_				,lowercase_					:       List[Any]     				=					FlaxStableDiffusionPipeline.from_pretrained(
            _a       ,				scheduler=_a       ,				revision='bf16'       ,				dtype=jnp.bfloataa       ,				)
        lowercase_					:       List[Any]     				=					scheduler_params

        lowercase_					:       List[Any]     				=					'A painting of a squirrel eating a burger'
        lowercase_					:       List[str]     				=					jax.device_count()
        lowercase_					:       str     				=					num_samples * [prompt]
        lowercase_					:       Optional[Any]     				=					sd_pipe.prepare_inputs(_a				)

        lowercase_					:       List[Any]     				=					replicate(_a				)
        lowercase_					:       Tuple     				=					shard(_a				)

        lowercase_					:       str     				=					jax.random.PRNGKey(0				)
        lowercase_					:       Optional[int]     				=					jax.random.split(_a       ,				jax.device_count()				)

        lowercase_					:       Tuple     				=					sd_pipe(_a       ,				_a       ,				_a       ,				num_inference_steps=25       ,				jit=_a				)[0]
        assert images.shape == (jax.device_count(), 1, 768, 768, 3)

        lowercase_					:       Dict     				=					images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]				)
        lowercase_					:       Any     				=					images[0, 253:256, 253:256, -1]

        lowercase_					:       Union[str, Any]     				=					jnp.asarray(jax.device_get(image_slice.flatten()				)				)
        lowercase_					:       List[Any]     				=					jnp.array([0.43_36, 0.4_29_69, 0.44_53, 0.41_99, 0.42_97, 0.45_31, 0.44_34, 0.44_34, 0.42_97]				)
        print(f'''output_slice: {output_slice}'''				)
        assert jnp.abs(output_slice - expected_slice				).max() < 1e-2





'''simple docstring'''




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os

from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
    DYNAMO_BACKENDS,
    _ask_field,
    _ask_options,
    _convert_dynamo_backend,
    _convert_mixed_precision,
    _convert_sagemaker_distributed_mode,
    _convert_yes_no_to_bool,
)


if is_botoa_available():
 import botoa  # noqa: F401

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       str     				=					botoa.client('iam'							)

     lowercase_					:       Optional[int]     				=					{
         'Version': '2012-10-17',
         'Statement': [
             {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'}
         ],
     }
     try:
          # create the role, associated with the chosen trust policy
          iam_client.create_role(
              RoleName=SCREAMING_SNAKE_CASE_  ,       AssumeRolePolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_  ,       indent=2							)							)
          lowercase_					:       Optional[Any]     				=					{
              'Version': '2012-10-17',
              'Statement': [
                  {
                      'Effect': 'Allow',
                      'Action': [
                          'sagemaker:*',
                          'ecr:GetDownloadUrlForLayer',
                          'ecr:BatchGetImage',
                          'ecr:BatchCheckLayerAvailability',
                          'ecr:GetAuthorizationToken',
                          'cloudwatch:PutMetricData',
                          'cloudwatch:GetMetricData',
                          'cloudwatch:GetMetricStatistics',
                          'cloudwatch:ListMetrics',
                          'logs:CreateLogGroup',
                          'logs:CreateLogStream',
                          'logs:DescribeLogStreams',
                          'logs:PutLogEvents',
                          'logs:GetLogEvents',
                          's3:CreateBucket',
                          's3:ListBucket',
                          's3:GetBucketLocation',
                          's3:GetObject',
                          's3:PutObject',
                      ],
                      'Resource': '*',
                  }
              ],
          }
          # attach policy to role
          iam_client.put_role_policy(
              RoleName=SCREAMING_SNAKE_CASE_  ,       PolicyName=f'''{role_name}_policy_permission'''  ,       PolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_  ,       indent=2							)  ,       )
     except iam_client.exceptions.EntityAlreadyExistsException:
          print(f'''role {role_name} already exists. Using existing one'''							)

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       List[Any]     				=					botoa.client('iam'							)
     return iam_client.get_role(RoleName=SCREAMING_SNAKE_CASE_							)["Role"]["Arn"]






def _UpperCamelCase   (       ):
     lowercase_					:       Dict     				=					_ask_options(
         'How do you want to authorize?'  ,       ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) ']  ,       SCREAMING_SNAKE_CASE_  ,       )
     lowercase_					:       List[Any]     				=					None
     if credentials_configuration == 0:
          lowercase_					:       List[Any]     				=					_ask_field('Enter your AWS Profile name: [default] '  ,       default='default'							)
          lowercase_					:       Optional[int]     				=					aws_profile
     else:
          print(
              'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,'
              '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`'							)
          lowercase_					:       Optional[Any]     				=					_ask_field('AWS Access Key ID: '							)
          lowercase_					:       Optional[int]     				=					aws_access_key_id

          lowercase_					:       Optional[Any]     				=					_ask_field('AWS Secret Access Key: '							)
          lowercase_					:       Optional[int]     				=					aws_secret_access_key

     lowercase_					:       Any     				=					_ask_field('Enter your AWS Region: [us-east-1]'  ,       default='us-east-1'							)
     lowercase_					:       Tuple     				=					aws_region

     lowercase_					:       int     				=					_ask_options(
         'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?'  ,       ['Provide IAM Role name', 'Create new IAM role using credentials']  ,       SCREAMING_SNAKE_CASE_  ,       )
     if role_management == 0:
          lowercase_					:       int     				=					_ask_field('Enter your IAM role name: '							)
     else:
          lowercase_					:       Any     				=					'accelerate_sagemaker_execution_role'
          print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials'''							)
          _create_iam_role_for_sagemaker(SCREAMING_SNAKE_CASE_							)

     lowercase_					:       List[Any]     				=					_ask_field(
         'Do you want to use custom Docker image? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       Optional[Any]     				=					None
     if is_custom_docker_image:
          lowercase_					:       List[Any]     				=					_ask_field('Enter your Docker image: '  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()							)

     lowercase_					:       Any     				=					_ask_field(
         'Do you want to provide SageMaker input channels with data locations? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       Optional[Any]     				=					None
     if is_sagemaker_inputs_enabled:
          lowercase_					:       Dict     				=					_ask_field(
              'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): '  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()  ,       )

     lowercase_					:       Dict     				=					_ask_field(
         'Do you want to enable SageMaker metrics? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       Optional[Any]     				=					None
     if is_sagemaker_metrics_enabled:
          lowercase_					:       Dict     				=					_ask_field(
              'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): '  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()  ,       )

     lowercase_					:       int     				=					_ask_options(
         'What is the distributed mode?'  ,       ['No distributed training', 'Data parallelism']  ,       _convert_sagemaker_distributed_mode  ,       )
     lowercase_					:       List[str]     				=					{}
     lowercase_					:       Optional[Any]     				=					_ask_field(
         'Do you wish to optimize your script with torch dynamo?[yes/NO]:'  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     if use_dynamo:
          lowercase_					:       List[Any]     				=					'dynamo_'
          lowercase_					:       List[Any]     				=					_ask_options(
              'Which dynamo backend would you like to use?'  ,       [x.lower() for x in DYNAMO_BACKENDS]  ,       _convert_dynamo_backend  ,       default=2  ,       )
          lowercase_					:       int     				=					_ask_field(
              'Do you want to customize the defaults sent to torch.compile? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )

          if use_custom_options:
               lowercase_					:       Union[str, Any]     				=					_ask_options(
                   'Which mode do you want to use?'  ,       SCREAMING_SNAKE_CASE_  ,       lambda SCREAMING_SNAKE_CASE_							: TORCH_DYNAMO_MODES[int(SCREAMING_SNAKE_CASE_							)]  ,       default='default'  ,       )
               lowercase_					:       Union[str, Any]     				=					_ask_field(
                   'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
               lowercase_					:       Tuple     				=					_ask_field(
                   'Do you want to enable dynamic shape tracing? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       List[str]     				=					'Which EC2 instance type you want to use for your training?'
     if distributed_type != SageMakerDistributedType.NO:
          lowercase_					:       Optional[Any]     				=					_ask_options(
              SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       lambda SCREAMING_SNAKE_CASE_							: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(SCREAMING_SNAKE_CASE_							)]							)
     else:
          eca_instance_query += "? [ml.p3.2xlarge]:"
          lowercase_					:       Tuple     				=					_ask_field(SCREAMING_SNAKE_CASE_  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()  ,       default='ml.p3.2xlarge'							)

     lowercase_					:       str     				=					1
     if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
          lowercase_					:       Union[str, Any]     				=					_ask_field(
              'How many machines do you want use? [1]: '  ,       SCREAMING_SNAKE_CASE_  ,       default=1  ,       )

     lowercase_					:       Any     				=					_ask_options(
         'Do you wish to use FP16 or BF16 (mixed precision)?'  ,       ['no', 'fp16', 'bf16', 'fp8']  ,       _convert_mixed_precision  ,       )

     if use_dynamo and mixed_precision == "no":
          print(
              'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.'							)

     return SageMakerConfig(
         image_uri=SCREAMING_SNAKE_CASE_  ,       compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER  ,       distributed_type=SCREAMING_SNAKE_CASE_  ,       use_cpu=SCREAMING_SNAKE_CASE_  ,       dynamo_config=SCREAMING_SNAKE_CASE_  ,       eca_instance_type=SCREAMING_SNAKE_CASE_  ,       profile=SCREAMING_SNAKE_CASE_  ,       region=SCREAMING_SNAKE_CASE_  ,       iam_role_name=SCREAMING_SNAKE_CASE_  ,       mixed_precision=SCREAMING_SNAKE_CASE_  ,       num_machines=SCREAMING_SNAKE_CASE_  ,       sagemaker_inputs_file=SCREAMING_SNAKE_CASE_  ,       sagemaker_metrics_file=SCREAMING_SNAKE_CASE_  ,       )




