






from manim import *



class 				_UpperCamelCase      (a_      ):


      def 			__UpperCAmelCase		(						self						)->						Dict:
           __lowerCAmelCase             =       Rectangle(height=0.5       ,    width=0.5						)
           __lowerCAmelCase             =       Rectangle(height=0.4_6       ,    width=0.4_6						).set_stroke(width=0						)

           __lowerCAmelCase             =       [mem.copy() for i in range(6						)]
           __lowerCAmelCase             =       [mem.copy() for i in range(6						)]
           __lowerCAmelCase             =       VGroup(*__UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0						)
           __lowerCAmelCase             =       VGroup(*__UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0						)
           __lowerCAmelCase             =       VGroup(__UpperCamelCase       ,    __UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0						)
           __lowerCAmelCase             =       Text("CPU"       ,    font_size=2_4						)
           __lowerCAmelCase             =       Group(__UpperCamelCase       ,    __UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0.5       ,    aligned_edge=__UpperCamelCase						)
           cpu.move_to([-2.5, -0.5, 0]						)
           self.add(__UpperCamelCase						)

           __lowerCAmelCase             =       [mem.copy() for i in range(4						)]
           __lowerCAmelCase             =       VGroup(*__UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0						)
           __lowerCAmelCase             =       Text("GPU"       ,    font_size=2_4						)
           __lowerCAmelCase             =       Group(__UpperCamelCase       ,    __UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0.5       ,    aligned_edge=__UpperCamelCase						)
           gpu.move_to([-1, -1, 0]						)
           self.add(__UpperCamelCase						)

           __lowerCAmelCase             =       [mem.copy() for i in range(6						)]
           __lowerCAmelCase             =       VGroup(*__UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0						)

           __lowerCAmelCase             =       Text("Model"       ,    font_size=2_4						)
           __lowerCAmelCase             =       Group(__UpperCamelCase       ,    __UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0.5       ,    aligned_edge=__UpperCamelCase						)
           model.move_to([3, -1.0, 0]						)
           self.add(__UpperCamelCase						)

           __lowerCAmelCase             =       []
           for i, rect in enumerate(__UpperCamelCase						):
                rect.set_stroke(__UpperCamelCase						)
                # target = fill.copy().set_fill(YELLOW, opacity=0.7)
                # target.move_to(rect)
                # self.add(target)

                __lowerCAmelCase             =       Rectangle(height=0.4_6 / 4       ,    width=0.4_6 / 3						).set_stroke(width=0.0						).set_fill(__UpperCamelCase       ,    opacity=0.7						)

                if i == 0:
                     cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT						)       ,    buff=0.0_2       ,    direction=__UpperCamelCase						)
                     cpu_target.set_x(cpu_target.get_x() + 0.1						)
                elif i == 3:
                     cpu_target.next_to(cpu_targs[0]       ,    direction=__UpperCamelCase       ,    buff=0.0						)
                else:
                     cpu_target.next_to(cpu_targs[i - 1]       ,    direction=__UpperCamelCase       ,    buff=0.0						)
                self.add(__UpperCamelCase						)
                cpu_targs.append(__UpperCamelCase						)

           __lowerCAmelCase             =       [mem.copy() for i in range(6						)]
           __lowerCAmelCase             =       VGroup(*__UpperCamelCase						).arrange(__UpperCamelCase       ,    buff=0						)

           __lowerCAmelCase             =       Text("Loaded Checkpoint"       ,    font_size=2_4						)
           __lowerCAmelCase             =       Group(__UpperCamelCase       ,    __UpperCamelCase						).arrange(__UpperCamelCase       ,    aligned_edge=__UpperCamelCase       ,    buff=0.4						)
           checkpoint.move_to([3, 0.5, 0]						)

           __lowerCAmelCase             =       Square(side_length=2.2						)
           key.move_to([-5, 2, 0]						)

           __lowerCAmelCase             =       MarkupText(
               F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"""       ,    font_size=1_8       ,    )

           key_text.move_to([-5, 2.4, 0]						)

           self.add(__UpperCamelCase       ,    __UpperCamelCase						)

           __lowerCAmelCase             =       MarkupText(
               F"""<span fgcolor='{BLUE}'>●</span> Checkpoint"""       ,    font_size=1_8       ,    )

           blue_text.next_to(__UpperCamelCase       ,    DOWN * 2.4       ,    aligned_edge=key_text.get_left()						)

           __lowerCAmelCase             =       MarkupText(
               F"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>."""       ,    font_size=2_4       ,    )
           step_a.move_to([2, 2, 0]						)
           self.play(Write(__UpperCamelCase						)       ,    Write(__UpperCamelCase						)						)

           self.play(Write(__UpperCamelCase       ,    run_time=1						)       ,    Create(__UpperCamelCase       ,    run_time=1						)						)

           __lowerCAmelCase             =       []
           __lowerCAmelCase             =       []
           for i, rect in enumerate(__UpperCamelCase						):
                __lowerCAmelCase             =       fill.copy().set_fill(__UpperCamelCase       ,    opacity=0.7						)
                target.move_to(__UpperCamelCase						)
                first_animations.append(GrowFromCenter(__UpperCamelCase       ,    run_time=1						)						)

                __lowerCAmelCase             =       target.copy()
                cpu_target.generate_target()
                if i < 5:
                     cpu_target.target.move_to(cpu_left_col_base[i + 1]						)
                else:
                     cpu_target.target.move_to(cpu_right_col_base[i - 5]						)
                second_animations.append(MoveToTarget(__UpperCamelCase       ,    run_time=1.5						)						)

           self.play(*__UpperCamelCase						)
           self.play(*__UpperCamelCase						)
           self.wait()














import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


lowerCamelCase      :       int    =						logging.get_logger(__name__)





def    __lowerCAmelCase   (    __snake_case							):
     __lowerCAmelCase             =       r"\w+[.]\d+"
     __lowerCAmelCase             =       re.findall(__snake_case       ,			__snake_case							)
     for pat in pats:
          __lowerCAmelCase             =       key.replace(__snake_case       ,			"_".join(pat.split("."							)							)							)
     return key





def    __lowerCAmelCase   (    __snake_case       ,			__snake_case       ,			__snake_case							):
     __lowerCAmelCase             =       pt_tuple_key[:-1] + ("scale",)
     if (
         any("norm" in str_ for str_ in pt_tuple_key							)
         and (pt_tuple_key[-1] == "bias")
         and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
         and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
     ):
          __lowerCAmelCase             =       pt_tuple_key[:-1] + ("scale",)
          return renamed_pt_tuple_key, pt_tensor
     elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
          __lowerCAmelCase             =       pt_tuple_key[:-1] + ("scale",)
          return renamed_pt_tuple_key, pt_tensor

     # embedding
     if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
          __lowerCAmelCase             =       pt_tuple_key[:-1] + ("embedding",)
          return renamed_pt_tuple_key, pt_tensor

     # conv layer
     __lowerCAmelCase             =       pt_tuple_key[:-1] + ("kernel",)
     if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
          __lowerCAmelCase             =       pt_tensor.transpose(2       ,			3       ,			1       ,			0							)
          return renamed_pt_tuple_key, pt_tensor

     # linear layer
     __lowerCAmelCase             =       pt_tuple_key[:-1] + ("kernel",)
     if pt_tuple_key[-1] == "weight":
          __lowerCAmelCase             =       pt_tensor.T
          return renamed_pt_tuple_key, pt_tensor

     # old PyTorch layer norm weight
     __lowerCAmelCase             =       pt_tuple_key[:-1] + ("weight",)
     if pt_tuple_key[-1] == "gamma":
          return renamed_pt_tuple_key, pt_tensor

     # old PyTorch layer norm bias
     __lowerCAmelCase             =       pt_tuple_key[:-1] + ("bias",)
     if pt_tuple_key[-1] == "beta":
          return renamed_pt_tuple_key, pt_tensor

     return pt_tuple_key, pt_tensor





def    __lowerCAmelCase   (    __snake_case       ,			__snake_case       ,			__snake_case=42							):
     # Step 1: Convert pytorch tensor to numpy
     __lowerCAmelCase             =       {k: v.numpy() for k, v in pt_state_dict.items()}

     # Step 2: Since the model is stateless, get random Flax params
     __lowerCAmelCase             =       flax_model.init_weights(PRNGKey(__snake_case							)							)

     __lowerCAmelCase             =       flatten_dict(__snake_case							)
     __lowerCAmelCase             =       {}

     # Need to change some parameters name to match Flax names
     for pt_key, pt_tensor in pt_state_dict.items():
          __lowerCAmelCase             =       rename_key(__snake_case							)
          __lowerCAmelCase             =       tuple(renamed_pt_key.split("."							)							)

          # Correctly rename weight parameters
          __lowerCAmelCase      ,			__lowerCAmelCase             =       rename_key_and_reshape_tensor(__snake_case       ,			__snake_case       ,			__snake_case							)

          if flax_key in random_flax_state_dict:
               if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
                    raise ValueError(
                        F"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
                        F"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."""							)

        # also add unexpected weight so that warning is thrown
          __lowerCAmelCase             =       jnp.asarray(__snake_case							)

     return unflatten_dict(__snake_case							)






