






UpperCamelCase        =				range(2, 20 + 1)
UpperCamelCase        =				[10**k for k in range(ks[-1] + 1)]
UpperCamelCase        =				{}




def 				A		(					lowercase__  :  List[Any] ,		lowercase__  :  Tuple ,		lowercase__  :  str ,		lowercase__  :  Optional[Any]  )		-> Any:
	UpperCamelCase__ :List[Any]						=      sum(a_i[j] for j in range(lowercase__ ,		len(lowercase__  )  )  )
	UpperCamelCase__ :str						=      sum(a_i[j] * base[j] for j in range(min(len(lowercase__  ) ,		lowercase__  )  )  )

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

	UpperCamelCase__ :str						=      memo.get(lowercase__  )

	if sub_memo is not None:
		UpperCamelCase__ :Tuple						=      sub_memo.get(lowercase__  )

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

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

		else:
			UpperCamelCase__ :Dict						=      []
	else:
		UpperCamelCase__ :int						=      {c: []}
		UpperCamelCase__ :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
			UpperCamelCase__				,		UpperCamelCase__ :Dict						=      next_term(lowercase__ ,		k - 1 ,		i + dn ,		lowercase__  )
			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
		UpperCamelCase__				,		UpperCamelCase__ :Dict						=      compute(lowercase__ ,		lowercase__ ,		i + dn ,		lowercase__  )
		diff += _diff
		dn += terms_jumped

	UpperCamelCase__ :Union[str, Any]						=      sub_memo[c]

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

	# cache the jump for this value digitsum(b) and c
	sub_memo[c].insert(lowercase__ ,		(diff, dn, k)  )
	return (diff, dn)




def 				A		(					lowercase__  :  List[str] ,		lowercase__  :  Optional[int] ,		lowercase__  :  Tuple ,		lowercase__  :  int  )		-> Tuple:
	if i >= n:
		return 0, i
	if k > len(lowercase__  ):
		a_i.extend([0 for _ in range(k - len(lowercase__  )  )]  )

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

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

			ds_c += a_i[j]

		if addend > 0:
			break

	if addend > 0:
		add(lowercase__ ,		lowercase__ ,		lowercase__  )
	return diff, i - start_i




def 				A		(					lowercase__  :  Optional[Any] ,		lowercase__  :  Tuple ,		lowercase__  :  List[str]  )		-> Any:
	for j in range(lowercase__ ,		len(lowercase__  )  ):
		UpperCamelCase__ :Union[str, Any]						=      digits[j] + addend
		if s >= 10:
			UpperCamelCase__				,		UpperCamelCase__ :int						=      divmod(lowercase__ ,		10  )
			UpperCamelCase__ :Optional[int]						=      addend // 10 + quotient
		else:
			UpperCamelCase__ :Union[str, Any]						=      s
			UpperCamelCase__ :Dict						=      addend // 10

		if addend == 0:
			break

	while addend > 0:
		UpperCamelCase__				,		UpperCamelCase__ :Union[str, Any]						=      divmod(lowercase__ ,		10  )
		digits.append(lowercase__  )




def 				A		(					lowercase__  :  int = 10**15  )		-> int:
	UpperCamelCase__ :Any						=      [1]
	UpperCamelCase__ :Any						=      1
	UpperCamelCase__ :Dict						=      0
	while True:
		UpperCamelCase__				,		UpperCamelCase__ :Union[str, Any]						=      next_term(lowercase__ ,		20 ,		i + dn ,		lowercase__  )
		dn += terms_jumped
		if dn == n - i:
			break

	UpperCamelCase__ :Tuple						=      0
	for j in range(len(lowercase__  )  ):
		a_n += digits[j] * 10**j
	return a_n


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



import argparse

import torch
from safetensors.torch import load_file

from diffusers import StableDiffusionPipeline






def 					UpperCamelCase   (      __magic_name__	:				Union[str, Any]       ,       __magic_name__	:				Any       ,       __magic_name__	:				List[str]       ,       __magic_name__	:				Optional[int]       ,       __magic_name__	:				Tuple	)  ->    List[Any]:
		"""simple docstring"""




		lowercase__	     =						StableDiffusionPipeline.from_pretrained(__magic_name__       ,       torch_dtype=torch.floataa	)

		# load LoRA weight from .safetensors
		lowercase__	     =						load_file(__magic_name__	)

		lowercase__	     =						[]

		# directly update weight in diffusers model
		for key in state_dict:
				# it is suggested to print out the key, it usually will be something like below
				# "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight"

				# as we have set the alpha beforehand, so just skip
				if ".alpha" in key or key in visited:
						continue

				if "text" in key:
						lowercase__	     =						key.split("""."""	)[0].split(LORA_PREFIX_TEXT_ENCODER + """_"""	)[-1].split("""_"""	)
						lowercase__	     =						pipeline.text_encoder
				else:
						lowercase__	     =						key.split("""."""	)[0].split(LORA_PREFIX_UNET + """_"""	)[-1].split("""_"""	)
						lowercase__	     =						pipeline.unet

				# find the target layer
				lowercase__	     =						layer_infos.pop(0	)
				while len(__magic_name__	) > -1:
						try:
								lowercase__	     =						curr_layer.__getattr__(__magic_name__	)
								if len(__magic_name__	) > 0:
										lowercase__	     =						layer_infos.pop(0	)
								elif len(__magic_name__	) == 0:
										break
						except Exception:
								if len(__magic_name__	) > 0:
										temp_name += "_" + layer_infos.pop(0	)
								else:
										lowercase__	     =						layer_infos.pop(0	)

				lowercase__	     =						[]
				if "lora_down" in key:
						pair_keys.append(key.replace("""lora_down"""       ,       """lora_up"""	)	)
						pair_keys.append(__magic_name__	)
				else:
						pair_keys.append(__magic_name__	)
						pair_keys.append(key.replace("""lora_up"""       ,       """lora_down"""	)	)

				# update weight
				if len(state_dict[pair_keys[0]].shape	) == 4:
						lowercase__	     =						state_dict[pair_keys[0]].squeeze(3	).squeeze(2	).to(torch.floataa	)
						lowercase__	     =						state_dict[pair_keys[1]].squeeze(3	).squeeze(2	).to(torch.floataa	)
						curr_layer.weight.data += alpha * torch.mm(__magic_name__       ,       __magic_name__	).unsqueeze(2	).unsqueeze(3	)
				else:
						lowercase__	     =						state_dict[pair_keys[0]].to(torch.floataa	)
						lowercase__	     =						state_dict[pair_keys[1]].to(torch.floataa	)
						curr_layer.weight.data += alpha * torch.mm(__magic_name__       ,       __magic_name__	)

				# update visited list
				for item in pair_keys:
						visited.append(__magic_name__	)

		return pipeline


if __name__ == "__main__":
	A			:						int        =  argparse.ArgumentParser()

	parser.add_argument(
	    '--base_model_path', default=None, type=str, required=True, help='Path to the base model in diffusers format.'
	)
	parser.add_argument(
	    '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
	)
	parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
	parser.add_argument(
	    '--lora_prefix_unet', default='lora_unet', type=str, help='The prefix of UNet weight in safetensors'
	)
	parser.add_argument(
	    '--lora_prefix_text_encoder',
	    default='lora_te',
	    type=str,
	    help='The prefix of text encoder weight in safetensors',
	)
	parser.add_argument('--alpha', default=0.75, type=float, help='The merging ratio in W = W0 + alpha * deltaW')
	parser.add_argument(
	    '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.'
	)
	parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')

	A			:						str        =  parser.parse_args()

	A			:						Tuple        =  args.base_model_path
	A			:						List[str]        =  args.checkpoint_path
	A			:						Optional[int]        =  args.dump_path
	A			:						Optional[int]        =  args.lora_prefix_unet
	A			:						Any        =  args.lora_prefix_text_encoder
	A			:						Any        =  args.alpha

	A			:						List[str]        =  convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha)

	A			:						int        =  pipe.to(args.device)
	pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)

