freecontrol icon indicating copy to clipboard operation
freecontrol copied to clipboard

How to achieve the results of Fig.2?

Open Hongbin98 opened this issue 2 years ago • 2 comments

I have tried to get the similar results of figure 2.

  1. Download pre-computed bases from your google link
  2. Visualize them via the following code:
import matplotlib.pyplot as plt
import torch

# 加载保存的 pca_info
pca_info = torch.load('/code/freecontrol/pca_info.pt')

# 要处理的block名称列表
block_names = [
    'up_blocks.1.attentions.0.transformer_blocks.0.attn1',
    'up_blocks.1.attentions.1.transformer_blocks.0.attn1',
    'up_blocks.1.attentions.2.transformer_blocks.0.attn1'
]

# 假设你有多步的 pca_info,最后五步是从倒数第 5 步开始到最后一步
steps_to_visualize = 5  # 要可视化的步数
starting_step = max(0, len(pca_info) - steps_to_visualize)  # 获取倒数第5步开始的索引

# 遍历每一步进行可视化
for i in range(starting_step, len(pca_info)):
    
    for block_name in block_names:
        if 'attn_key' in pca_info[i] and block_name in pca_info[i]['attn_key']:
            basis = pca_info[i]['attn_key'][block_name]['basis']  # 形状为 (64, 1280)
            mean = pca_info[i]['attn_key'][block_name]['mean']    # 形状为 (1280,)

            # 确保 basis 和 mean 已正确加载
            print("Basis shape:", basis.shape)
            print("Mean shape:", mean.shape)

            height, width = 8, 8  # 根据实际图像大小调整

            # 提取前 3 个主成分 (top 3 principal components)
            pc1 = basis[:, 0].reshape(height, width)
            pc2 = basis[:, 1].reshape(height, width)
            pc3 = basis[:, 2].reshape(height, width)

            # 归一化到 [0, 1] 之间
            pc1 = (pc1 - pc1.min()) / (pc1.max() - pc1.min())
            pc2 = (pc2 - pc2.min()) / (pc2.max() - pc2.min())
            pc3 = (pc3 - pc3.min()) / (pc3.max() - pc3.min())

            # 将 tensor 转换为 numpy 数组
            pc1 = pc1.cpu().numpy()
            pc2 = pc2.cpu().numpy()
            pc3 = pc3.cpu().numpy()

            # 将主成分的值缩放到 [0, 255] 并转换为 uint8
            pc1 = (pc1 * 255).astype(np.uint8)
            pc2 = (pc2 * 255).astype(np.uint8)
            pc3 = (pc3 * 255).astype(np.uint8)

            # 将前三个主成分伪彩色化为 RGB 通道
            rgb_image = np.stack([pc1, pc2, pc3], axis=-1)

            # 可视化 RGB 图片
            plt.imshow(rgb_image)
            plt.title(f"PCA Components Visualized in RGB for {block_name} - Step {i}")
            plt.axis('off')

            # 保存每一步的图片,文件名区分不同步和不同的 block
            plt.savefig(f'PCA_res_step_{i}_{block_name.replace(".", "_")}.png')
            plt.close()  # 关闭当前图以节省内存
        else:
            print(f"Step {i} does not contain 'attn_key' or {block_name} data.")
  1. However, the visualizations seem incorrect

Looking forward for any suggestion or help image

Hongbin98 avatar Oct 09 '24 09:10 Hongbin98

Hi, this is my naive code to get the PCA visualization. The variable names might be mismatched with our released code but you can start from this to do the visualization.

@torch.no_grad()
    def compute_score(
            self,
            prompt: Union[str, List[str]] = None,
            height: Optional[int] = None,
            width: Optional[int] = None,
            num_inference_steps: int = 50,
            guidance_scale: float = 7.5,
            negative_prompt: Optional[Union[str, List[str]]] = None,
            num_images_per_prompt: Optional[int] = 1,
            eta: float = 0.0,
            generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
            latents: Optional[torch.FloatTensor] = None,
            prompt_embeds: Optional[torch.FloatTensor] = None,
            negative_prompt_embeds: Optional[torch.FloatTensor] = None,
            output_type: Optional[str] = "pil",
            return_dict: bool = True,
            callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
            callback_steps: int = 1,
            cross_attention_kwargs: Optional[Dict[str, Any]] = None,
            guidance_rescale: float = 0.0,
            config: Optional[Union[Dict[str, Any], omegaconf.DictConfig]] = None,
            data_samples=None,
    ):
        assert config is not None, "config is required for FreeControl pipeline"
        self.sampling_config = config
        self.input_config = config

        self.unet = prep_unet(self.unet)
        self.unet = prep_conv_layer(self.unet)

        self.load_pca_info()
        self.running_device = 'cuda'
        self.ref_mask_record = None

        # 0. Default height and width to unet
        height = self.img_size[1] or self.unet.config.sample_size * self.vae_scale_factor
        width = self.img_size[0] or self.unet.config.sample_size * self.vae_scale_factor

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
        )

        # Compute the mapping token relation
        # inversion prompt need to be a list of prompt

        inversion_prompt = self.input_config.data.inversion.prompt
        obj_pairs = self.input_config.sd_config.obj_pairs
        generate_prompt = prompt

        self.cross_attn_probs: Dict = {'channels': 0, 'probs': None}

        # 2. Define call parameters
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        device = self._execution_device
        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
        # corresponds to doing no classifier free guidance.
        do_classifier_free_guidance = False

        # 3. Encode input prompt
        text_encoder_lora_scale = (
            cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
        )

        # For classifier free guidance, we need to do two forward passes.
        # Here we concatenate the unconditional and text embeddings into a single batch
        # to avoid doing two forward passes
        if do_classifier_free_guidance:
            prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])

        # 4. Prepare timesteps
        self.scheduler.set_timesteps(num_inference_steps, device=device)
        timesteps = self.scheduler.timesteps

        same_latent = config.sd_config.same_latent
        # 5. Prepare latent variables
        num_channels_latents = self.unet.config.in_channels
        latents = None
        # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
        # Prepare guidance configs
        self.guidance_config = config.guidance
        # 7. Denoising loop
        self.pca_dict = dict()
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        with self.progress_bar(total=num_inference_steps) as progress_bar:
            for i, t in enumerate(timesteps):
                # Process the latent
                step_timestep: int = t.detach().cpu().item()
                assert step_timestep in data_samples['examplar'][0][
                    'all_latents'].keys(), f"timestep {step_timestep} not in inverse samples keys"
                data_samples_latent: torch.Tensor = data_samples['examplar'][0]['all_latents'][step_timestep]
                data_samples_latent = data_samples_latent.to(device=self.running_device, dtype=self.unet.dtype)
                latent_model_input: torch.Tensor = data_samples_latent
                latent_model_input = self.scheduler.scale_model_input(latent_model_input, t).detach()

                # process the prompt embedding
                if config.data.inversion.method == 'DDIM':
                    ref_prompt_embeds = data_samples['examplar'][0]['prompt_embeds'].to('cuda')
                else:
                    raise NotImplementedError("Currently only support DDIM method")

                step_prompt_embeds = ref_prompt_embeds.detach().to('cuda')

                require_grad_flag = False
                # Check if the current step is in the guidance step
                if _in_step(self.guidance_config.pca_guidance, i) or _in_step(self.guidance_config.cross_attn, i):
                    require_grad_flag = True

                noise_pred = self.unet(
                    latent_model_input,
                    t,
                    encoder_hidden_states=step_prompt_embeds,
                    cross_attention_kwargs=cross_attention_kwargs,
                    return_dict=False,
                )[0]

                # Get self attention features
                hidden_state_dict, query_dict, key_dict, value_dict = get_selt_attn_feat_info(self.unet,
                                                                                              self.sampling_config.guidance.pca_guidance)

                def get_pca_score(feat,pca_info):
                    feat = feat.detach().to("cuda")
                    feat_mean: torch.Tensor = pca_info['mean'].to("cuda")
                    feat_basis: torch.Tensor = pca_info['basis'].to("cuda")
                    n_components: int = 3
                    bs, channels, h, w = feat.shape
                    feat = feat.permute(0, 2, 3, 1).reshape(-1, channels)
                    centered_feat = feat - feat_mean
                    # Compute the projection
                    feat_proj = torch.matmul(centered_feat, feat_basis.T)[:, :n_components].detach().cpu()
                    feat_proj = feat_proj.reshape(bs, h, w, n_components).permute(0, 3, 1, 2)
                    return feat_proj

                step_pca_info = self.loaded_pca_info[i]
                key_pca_info = step_pca_info['attn_key']
                key_pca_score_dict = dict()
                for block_name in key_pca_info.keys():
                    try:
                        key_pca_score_dict[block_name] = {
                            "score" :get_pca_score(key_dict[block_name], key_pca_info[block_name])
                        }
                    except:
                        a = 1
                self.pca_dict[i] = {
                    'key': key_pca_score_dict,
                }
                progress_bar.update()

        return self.pca_dict

SichengMo avatar Oct 09 '24 22:10 SichengMo

Thanks for your reply on time!

Hongbin98 avatar Oct 10 '24 01:10 Hongbin98