'''simple docstring'''

__a:			int	       =       range(2, 20 + 1)
__a:			Optional[int]	       =       [10**k for k in range(ks[-1] + 1)]
__a:			dict[int, dict[int, list[list[int]]]]	       =       {}
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase					):
 lowercase__    :   List[str]						= sum(a_i[j] for j in range(UpperCAmelCase		,					len(UpperCAmelCase					)					)					)
 lowercase__    :   Tuple						= sum(a_i[j] * base[j] for j in range(min(len(UpperCAmelCase					)		,					UpperCAmelCase					)					)					)

 lowercase__			,							lowercase__    :   List[str]						= 0, 0
 lowercase__    :   Union[str, Any]						= n - i

 lowercase__    :   Optional[Any]						= memo.get(UpperCAmelCase					)

 if sub_memo is not None:
  lowercase__    :   Dict						= sub_memo.get(UpperCAmelCase					)

  if jumps is not None and len(UpperCAmelCase					) > 0:
   # find and make the largest jump without going over
   lowercase__    :   Tuple						= -1
   for _k in range(len(UpperCAmelCase					) - 1		,					-1		,					-1					):
    if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
     lowercase__    :   Optional[int]						= _k
     break

   if max_jump >= 0:
    lowercase__			,							lowercase__			,							lowercase__    :   Dict						= jumps[max_jump]
    # since the difference between jumps is cached, add c
    lowercase__    :   str						= diff + c
    for j in range(min(UpperCAmelCase		,					len(UpperCAmelCase					)					)					):
     lowercase__			,							lowercase__    :   str						= divmod(UpperCAmelCase		,					10					)
    if new_c > 0:
     add(UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase					)

  else:
   lowercase__    :   Union[str, Any]						= []
 else:
  lowercase__    :   List[Any]						= {c: []}
  lowercase__    :   Optional[int]						= sub_memo

 if dn >= max_dn or c + diff >= base[k]:
  return diff, dn

 if k > ks[0]:
  while True:
   # keep doing smaller jumps
   lowercase__			,							lowercase__    :   List[Any]						= next_term(UpperCAmelCase		,					k - 1		,					i + dn		,					UpperCAmelCase					)
   diff += _diff
   dn += terms_jumped

   if dn >= max_dn or c + diff >= base[k]:
    break
 else:
  # would be too small a jump, just compute sequential terms instead
  lowercase__			,							lowercase__    :   List[str]						= compute(UpperCAmelCase		,					UpperCAmelCase		,					i + dn		,					UpperCAmelCase					)
  diff += _diff
  dn += terms_jumped

 lowercase__    :   Tuple						= sub_memo[c]

 # keep jumps sorted by # of terms skipped
 lowercase__    :   Optional[int]						= 0
 while j < len(UpperCAmelCase					):
  if jumps[j][1] > dn:
   break
  j += 1

 # cache the jump for this value digitsum(b) and c
 sub_memo[c].insert(UpperCAmelCase		,					(diff, dn, k)					)
 return (diff, dn)
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase					):
 if i >= n:
  return 0, i
 if k > len(UpperCAmelCase					):
  a_i.extend([0 for _ in range(k - len(UpperCAmelCase					)					)]					)

 # note: a_i -> b * 10^k + c
 # ds_b -> digitsum(b)
 # ds_c -> digitsum(c)
 lowercase__    :   Any						= i
 lowercase__			,							lowercase__			,							lowercase__    :   Dict						= 0, 0, 0
 for j in range(len(UpperCAmelCase					)					):
  if j >= k:
   ds_b += a_i[j]
  else:
   ds_c += a_i[j]

 while i < n:
  i += 1
  lowercase__    :   List[Any]						= ds_c + ds_b
  diff += addend
  lowercase__    :   str						= 0
  for j in range(UpperCAmelCase					):
   lowercase__    :   Tuple						= a_i[j] + addend
   lowercase__			,							lowercase__    :   List[Any]						= divmod(UpperCAmelCase		,					10					)

   ds_c += a_i[j]

  if addend > 0:
   break

 if addend > 0:
  add(UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase					)
 return diff, i - start_i
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase					):
 for j in range(UpperCAmelCase		,					len(UpperCAmelCase					)					):
  lowercase__    :   Optional[int]						= digits[j] + addend
  if s >= 10:
   lowercase__			,							lowercase__    :   int						= divmod(UpperCAmelCase		,					10					)
   lowercase__    :   Dict						= addend // 10 + quotient
  else:
   lowercase__    :   Any						= s
   lowercase__    :   Union[str, Any]						= addend // 10

  if addend == 0:
   break

 while addend > 0:
  lowercase__			,							lowercase__    :   Tuple						= divmod(UpperCAmelCase		,					10					)
  digits.append(UpperCAmelCase					)
def       __UpperCamelCase	(       UpperCAmelCase = 10**15					):
 lowercase__    :   Dict						= [1]
 lowercase__    :   Any						= 1
 lowercase__    :   List[Any]						= 0
 while True:
  lowercase__			,							lowercase__    :   int						= next_term(UpperCAmelCase		,					20		,					i + dn		,					UpperCAmelCase					)
  dn += terms_jumped
  if dn == n - i:
   break

 lowercase__    :   List[str]						= 0
 for j in range(len(UpperCAmelCase					)					):
  a_n += digits[j] * 10**j
 return a_n


if __name__ == "__main__":
  print(F'{solution() = }')


'''simple docstring'''

import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class       UpperCAmelCase  (						a__   ,						unittest.TestCase ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   DDIMPipeline
       SCREAMING_SNAKE_CASE 		=   UNCONDITIONAL_IMAGE_GENERATION_PARAMS
       SCREAMING_SNAKE_CASE 		=   PipelineTesterMixin.required_optional_params - {
           "num_images_per_prompt",
           "latents",
           "callback",
           "callback_steps",
       }
       SCREAMING_SNAKE_CASE 		=   UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
       SCREAMING_SNAKE_CASE 		=   False

       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        torch.manual_seed(0			)
        lowercase__    :   Optional[int]						= UNetaDModel(
            block_out_channels=(32, 64)     ,       layers_per_block=2     ,       sample_size=32     ,       in_channels=3     ,       out_channels=3     ,       down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')     ,       up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')     ,       )
        lowercase__    :   Any						= DDIMScheduler()
        lowercase__    :   Union[str, Any]						= {'''unet''': unet, '''scheduler''': scheduler}
        return components

       def _lowerCAmelCase(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase=0			)  ->  int:
        if str(__lowerCAmelCase			).startswith('''mps'''			):
         lowercase__    :   Optional[Any]						= torch.manual_seed(__lowerCAmelCase			)
        else:
         lowercase__    :   int						= torch.Generator(device=__lowerCAmelCase			).manual_seed(__lowerCAmelCase			)
        lowercase__    :   List[Any]						= {
            '''batch_size''': 1,
            '''generator''': generator,
            '''num_inference_steps''': 2,
            '''output_type''': '''numpy''',
        }
        return inputs

       def _lowerCAmelCase(						self			)  ->  Optional[Any]:
        lowercase__    :   int						= '''cpu'''

        lowercase__    :   Optional[Any]						= self.get_dummy_components()
        lowercase__    :   str						= self.pipeline_class(**__lowerCAmelCase			)
        pipe.to(__lowerCAmelCase			)
        pipe.set_progress_bar_config(disable=__lowerCAmelCase			)

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

        self.assertEqual(image.shape     ,       (1, 32, 32, 3)			)
        lowercase__    :   Optional[int]						= np.array(
            [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04]			)
        lowercase__    :   Optional[Any]						= np.abs(image_slice.flatten() - expected_slice			).max()
        self.assertLessEqual(__lowerCAmelCase     ,       1E-3			)

       def _lowerCAmelCase(						self			)  ->  str:
        super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3			)

       def _lowerCAmelCase(						self			)  ->  List[str]:
        super().test_save_load_local(expected_max_difference=3E-3			)

       def _lowerCAmelCase(						self			)  ->  Tuple:
        super().test_save_load_optional_components(expected_max_difference=3E-3			)


       def _lowerCAmelCase(						self			)  ->  int:
        super().test_inference_batch_single_identical(expected_max_diff=3E-3			)



@slow
@require_torch_gpu
class       UpperCAmelCase  (						unittest.TestCase ):





       '''simple docstring'''



       def _lowerCAmelCase(						self			)  ->  List[Any]:
        lowercase__    :   List[str]						= '''google/ddpm-cifar10-32'''

        lowercase__    :   List[Any]						= UNetaDModel.from_pretrained(__lowerCAmelCase			)
        lowercase__    :   str						= DDIMScheduler()

        lowercase__    :   List[Any]						= DDIMPipeline(unet=__lowerCAmelCase     ,       scheduler=__lowerCAmelCase			)
        ddim.to(__lowerCAmelCase			)
        ddim.set_progress_bar_config(disable=__lowerCAmelCase			)

        lowercase__    :   Dict						= torch.manual_seed(0			)
        lowercase__    :   Optional[int]						= ddim(generator=__lowerCAmelCase     ,       eta=0.0     ,       output_type='''numpy'''			).images

        lowercase__    :   List[str]						= image[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)
        lowercase__    :   Optional[int]						= np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3]			)

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


       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        lowercase__    :   Optional[Any]						= '''google/ddpm-ema-bedroom-256'''

        lowercase__    :   Tuple						= UNetaDModel.from_pretrained(__lowerCAmelCase			)
        lowercase__    :   Union[str, Any]						= DDIMScheduler.from_pretrained(__lowerCAmelCase			)

        lowercase__    :   List[Any]						= DDIMPipeline(unet=__lowerCAmelCase     ,       scheduler=__lowerCAmelCase			)
        ddpm.to(__lowerCAmelCase			)
        ddpm.set_progress_bar_config(disable=__lowerCAmelCase			)

        lowercase__    :   Union[str, Any]						= torch.manual_seed(0			)
        lowercase__    :   Optional[Any]						= ddpm(generator=__lowerCAmelCase     ,       output_type='''numpy'''			).images

        lowercase__    :   List[Any]						= image[0, -3:, -3:, -1]

        assert image.shape == (1, 256, 256, 3)
        lowercase__    :   Union[str, Any]						= np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9]			)

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

