CoolFace
Apppublic

svjack/LatentSync

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
eval_syncnet_acc.py119 linesDownload Raw Back to eval
1# Copyright (c) 2024 Bytedance Ltd. and/or its affiliates2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14 15import argparse16from tqdm.auto import tqdm17import torch18import torch.nn as nn19from einops import rearrange20from latentsync.models.syncnet import SyncNet21from latentsync.data.syncnet_dataset import SyncNetDataset22from diffusers import AutoencoderKL23from omegaconf import OmegaConf24from accelerate.utils import set_seed25 26 27def main(config):28    set_seed(config.run.seed)29 30    device = "cuda" if torch.cuda.is_available() else "cpu"31 32    if config.data.latent_space:33        vae = AutoencoderKL.from_pretrained(34            "runwayml/stable-diffusion-inpainting", subfolder="vae", revision="fp16", torch_dtype=torch.float1635        )36        vae.requires_grad_(False)37        vae.to(device)38 39    # Dataset and Dataloader setup40    dataset = SyncNetDataset(config.data.val_data_dir, config.data.val_fileslist, config)41 42    test_dataloader = torch.utils.data.DataLoader(43        dataset,44        batch_size=config.data.batch_size,45        shuffle=False,46        num_workers=config.data.num_workers,47        drop_last=False,48        worker_init_fn=dataset.worker_init_fn,49    )50 51    # Model52    syncnet = SyncNet(OmegaConf.to_container(config.model)).to(device)53 54    print(f"Load checkpoint from: {config.ckpt.inference_ckpt_path}")55    checkpoint = torch.load(config.ckpt.inference_ckpt_path, map_location=device)56 57    syncnet.load_state_dict(checkpoint["state_dict"])58    syncnet.to(dtype=torch.float16)59    syncnet.requires_grad_(False)60    syncnet.eval()61 62    global_step = 063    num_val_batches = config.data.num_val_samples // config.data.batch_size64    progress_bar = tqdm(range(0, num_val_batches), initial=0, desc="Testing accuracy")65 66    num_correct_preds = 067    num_total_preds = 068 69    while True:70        for step, batch in enumerate(test_dataloader):71            ### >>>> Test >>>> ###72 73            frames = batch["frames"].to(device, dtype=torch.float16)74            audio_samples = batch["audio_samples"].to(device, dtype=torch.float16)75            y = batch["y"].to(device, dtype=torch.float16).squeeze(1)76 77            if config.data.latent_space:78                frames = rearrange(frames, "b f c h w -> (b f) c h w")79 80                with torch.no_grad():81                    frames = vae.encode(frames).latent_dist.sample() * 0.1821582 83                frames = rearrange(frames, "(b f) c h w -> b (f c) h w", f=config.data.num_frames)84            else:85                frames = rearrange(frames, "b f c h w -> b (f c) h w")86 87            if config.data.lower_half:88                height = frames.shape[2]89                frames = frames[:, :, height // 2 :, :]90 91            with torch.no_grad():92                vision_embeds, audio_embeds = syncnet(frames, audio_samples)93 94            sims = nn.functional.cosine_similarity(vision_embeds, audio_embeds)95 96            preds = (sims > 0.5).to(dtype=torch.float16)97            num_correct_preds += (preds == y).sum().item()98            num_total_preds += len(sims)99 100            progress_bar.update(1)101            global_step += 1102 103            if global_step >= num_val_batches:104                progress_bar.close()105                print(f"Accuracy score: {num_correct_preds / num_total_preds*100:.2f}%")106                return107 108 109if __name__ == "__main__":110    parser = argparse.ArgumentParser(description="Code to test the accuracy of expert lip-sync discriminator")111 112    parser.add_argument("--config_path", type=str, default="configs/syncnet/syncnet_16_latent.yaml")113    args = parser.parse_args()114 115    # Load a configuration file116    config = OmegaConf.load(args.config_path)117 118    main(config)119