Download code/module/maskgit.py from rcell233/magvits_data: direct link, hf CLI and curl.
- Browser
- Download file 18.1 kB
-
https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/module/maskgit.py
- Command line
-
hf download hf://datasets/rcell233/magvits_data/code/module/maskgit.py
-
curl -L -o maskgit.py https://huggingface.co/datasets/rcell233/magvits_data/resolve/main/code/module/maskgit.py
18.1 kB
| """This file contains implementation for MaskGIT model. | |
| Copyright (2024) Bytedance Ltd. and/or its affiliates | |
| Licensed under the Apache License, Version 2.0 (the "License"); | |
| you may not use this file except in compliance with the License. | |
| You may obtain a copy of the License at | |
| http://www.apache.org/licenses/LICENSE-2.0 | |
| Unless required by applicable law or agreed to in writing, software | |
| distributed under the License is distributed on an "AS IS" BASIS, | |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| See the License for the specific language governing permissions and | |
| limitations under the License. | |
| Reference: | |
| https://github.com/huggingface/open-muse | |
| https://github.com/baaivision/MUSE-Pytorch | |
| https://github.com/sail-sg/MDT/blob/main/masked_diffusion/models.py | |
| """ | |
| import torch | |
| from torch import nn | |
| import numpy as np | |
| import math | |
| import torch.utils.checkpoint | |
| from tqdm import tqdm | |
| from transformers import BertConfig, BertModel | |
| from einops import rearrange | |
| import json | |
| from huggingface_hub import PyTorchModelHubMixin | |
| from omegaconf import OmegaConf | |
| from pathlib import Path | |
| """This file contains some base class implementation for models. | |
| This file may have been modified by Bytedance Ltd. and/or its affiliates (“Bytedance's Modifications”). | |
| All Bytedance's Modifications are Copyright (year) Bytedance Ltd. and/or its affiliates. | |
| Reference: | |
| https://github.com/huggingface/open-muse/blob/main/muse/modeling_utils.py | |
| """ | |
| import os | |
| from typing import Union, Callable, Dict, Optional | |
| import torch | |
| from transformer.embedding import SinePositionalEmbedding | |
| from transformer.transformer import LayerNorm, TransformerEncoder, TransformerEncoderLayer | |
| class BaseModel(torch.nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| def save_pretrained_weight( | |
| self, | |
| save_directory: Union[str, os.PathLike], | |
| save_function: Callable = None, | |
| state_dict: Optional[Dict[str, torch.Tensor]] = None, | |
| ): | |
| """Saves a model and its configuration file to a directory. | |
| Args: | |
| save_directory: A string or os.PathLike, directory to which to save. | |
| Will be created if it doesn't exist. | |
| save_function: A Callable function, the function to use to save the state dictionary. | |
| Useful on distributed training like TPUs when one need to replace `torch.save` by | |
| another method. Can be configured with the environment variable `DIFFUSERS_SAVE_MODE`. | |
| state_dict: A dictionary from str to torch.Tensor, the state dictionary to save. | |
| If `None`, the model's state dictionary will be saved. | |
| """ | |
| if os.path.isfile(save_directory): | |
| print(f"Provided path ({save_directory}) should be a directory, not a file") | |
| return | |
| if save_function is None: | |
| save_function = torch.save | |
| os.makedirs(save_directory, exist_ok=True) | |
| model_to_save = self | |
| if state_dict is None: | |
| state_dict = model_to_save.state_dict() | |
| weights_name = "pytorch_model.bin" | |
| save_function(state_dict, os.path.join(save_directory, weights_name)) | |
| print(f"Model weights saved in {os.path.join(save_directory, weights_name)}") | |
| def load_pretrained_weight( | |
| self, | |
| pretrained_model_path: Union[str, os.PathLike], | |
| strict_loading: bool = True, | |
| torch_dtype: Optional[torch.dtype] = None | |
| ): | |
| r"""Instantiates a pretrained pytorch model from a pre-trained model configuration. | |
| The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train | |
| the model, you should first set it back in training mode with `model.train()`. | |
| Args: | |
| pretrained_model_path: A string or os.PathLike, a path to a *directory* or *file* containing model weights. | |
| Raises: | |
| ValueError: If pretrained_model_path does not exist. | |
| """ | |
| # If pretrained_model_path is a file, set model_file to this file. | |
| if os.path.isfile(pretrained_model_path): | |
| model_file = pretrained_model_path | |
| # If pretrained_model_path is a directory, set model_file to the path of the | |
| # file "pytorch_model.bin" in this directory. | |
| elif os.path.isdir(pretrained_model_path): | |
| pretrained_model_path = os.path.join(pretrained_model_path, "pytorch_model.bin") | |
| if os.path.isfile(pretrained_model_path): | |
| model_file = pretrained_model_path | |
| else: | |
| raise ValueError(f"{pretrained_model_path} does not exist") | |
| else: | |
| raise ValueError(f"{pretrained_model_path} does not exist") | |
| # Load model state from checkpoint. | |
| checkpoint = torch.load(model_file, map_location="cpu") | |
| # Load state dictionary into self. | |
| msg = self.load_state_dict(checkpoint, strict=strict_loading) | |
| # Print information about loading weights. | |
| print(f"loading weight from {model_file}, msg: {msg}") | |
| # If torch_dtype is specified and is a valid torch.dtype, convert self to this dtype. | |
| if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype): | |
| raise ValueError( | |
| f"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}." | |
| ) | |
| elif torch_dtype is not None: | |
| self.to(torch_dtype) | |
| # Set model in evaluation mode to deactivate DropOut modules by default. | |
| self.eval() | |
| def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int: | |
| """Gets the number of parameters in the module. | |
| Args: | |
| only_trainable: A boolean, whether to only include trainable parameters. | |
| exclude_embeddings: A boolean, whether to exclude parameters associated with embeddings. | |
| Returns: | |
| An integer, the number of parameters. | |
| """ | |
| if exclude_embeddings: | |
| embedding_param_names = [ | |
| f"{name}.weight" | |
| for name, module_type in self.named_modules() | |
| if isinstance(module_type, torch.nn.Embedding) | |
| ] | |
| non_embedding_parameters = [ | |
| parameter for name, parameter in self.named_parameters() if name not in embedding_param_names | |
| ] | |
| return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable) | |
| else: | |
| return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable) | |
| class ImageBert(BaseModel, PyTorchModelHubMixin, tags=["arxiv:2304.12244"], pipeline_tag="text_to_image", | |
| license="mit"): | |
| def __init__(self, config): | |
| super().__init__() | |
| self.config = config | |
| self.target_codebook_size = config.model.vq_model.codebook_size | |
| self.condition_dim = config.model.generator.condition_dim | |
| self.image_seq_len = config.model.generator.image_seq_len | |
| self.mask_token_id = self.target_codebook_size | |
| self.hidden_size = config.model.generator.hidden_size | |
| self.num_hidden_layers = config.model.generator.num_hidden_layers | |
| self.num_attention_heads = config.model.generator.num_attention_heads | |
| self.intermediate_size = config.model.generator.intermediate_size | |
| self.cond_proj = nn.Linear(self.condition_dim, self.hidden_size) | |
| self.word_embeddings = nn.Embedding(self.target_codebook_size+1, self.hidden_size) | |
| norm_first = False | |
| self.encoder = TransformerEncoder( | |
| TransformerEncoderLayer( | |
| d_model=self.hidden_size, | |
| nhead=16, | |
| dim_feedforward=2048, | |
| dropout=0.1, | |
| batch_first=True, | |
| norm_first=False, ), | |
| num_layers=12, | |
| norm=LayerNorm(self.hidden_size) if norm_first else None, ) | |
| self.num_head = 16 | |
| self.position = SinePositionalEmbedding( | |
| self.hidden_size, dropout=0.1, scale=False, alpha=True) | |
| self.lm_head = nn.Linear(self.hidden_size, self.target_codebook_size, bias=True) | |
| def _save_pretrained(self, save_directory: Path) -> None: | |
| """Save weights and config to a local directory.""" | |
| # Assume 'self.config' is your DictConfig object | |
| # Convert to a regular dictionary | |
| dict_config = OmegaConf.to_container(self.config) | |
| # Save as JSON | |
| file_path = Path(save_directory) / "config.json" | |
| with open(file_path, 'w') as json_file: | |
| json.dump(dict_config, json_file, indent=4) | |
| super()._save_pretrained(save_directory) | |
| def forward(self, input_ids=None, condition=None, cond_drop_prob=0.1): | |
| # Token space: | |
| # [0, codebook_size - 1] : those are the learned quantized image tokens | |
| # codebook_size : the mask token used to mask image tokens | |
| # [codebook_size + 1, codebook_size + nclass] : the imagenet class tokens | |
| # codebook_size + 1 + nclass : the class drop label | |
| drop_label_mask = torch.rand(condition.shape[0], dtype=torch.float) < cond_drop_prob | |
| condition[drop_label_mask] = 0 | |
| condition = self.cond_proj(condition) | |
| inputs_embeds = self.word_embeddings(input_ids) | |
| inputs_embeds = inputs_embeds + condition | |
| x = self.position(inputs_embeds) | |
| model_output, _ = self.encoder( | |
| (x, None), src_key_padding_mask=None) | |
| return self.lm_head(model_output) # remove cond | |
| # ref: https://github.com/baaivision/MUSE-Pytorch/blob/master/libs/muse.py#L40 | |
| def generate(self, | |
| condition, | |
| guidance_scale=3.0, | |
| guidance_decay="constant", | |
| guidance_scale_pow=3.0, | |
| randomize_temperature=4.5, | |
| softmax_temperature_annealing=False, | |
| num_sample_steps=8): | |
| if guidance_decay not in ["constant", "linear", "power-cosine"]: | |
| # contstant: constant guidance scale | |
| # linear: linear increasing the guidance scale as in MUSE | |
| # power-cosine: the guidance schedule from MDT | |
| raise ValueError(f"Unsupported guidance decay {guidance_decay}") | |
| device = condition.device | |
| image_seq_len = condition.shape[1] | |
| ids = torch.full((condition.shape[0], image_seq_len), | |
| self.mask_token_id, device=device) | |
| cfg_scale = guidance_scale if guidance_decay == "constant" else 0. | |
| for step in tqdm(range(num_sample_steps)): | |
| ratio = 1. * (step + 1) / num_sample_steps | |
| annealed_temp = randomize_temperature * (1.0 - ratio) | |
| is_mask = (ids == self.mask_token_id) | |
| if guidance_decay == "power-cosine": | |
| # ref: https://github.com/sail-sg/MDT/blob/main/masked_diffusion/models.py#L501 | |
| guidance_scale_pow = torch.ones((1), device=device) * guidance_scale_pow | |
| scale_step = (1 - torch.cos(((step / num_sample_steps) ** guidance_scale_pow) * torch.pi)) * 1 / 2 | |
| cfg_scale = (guidance_scale - 1) * scale_step + 1 | |
| if cfg_scale != 0: | |
| cond_logits = self.forward( | |
| ids, condition, cond_drop_prob=0.0 | |
| ) | |
| uncond_logits = self.forward( | |
| ids, condition, cond_drop_prob=1.0 | |
| ) | |
| if guidance_decay == "power-cosine": | |
| logits = uncond_logits + (cond_logits - uncond_logits) * cfg_scale | |
| else: | |
| logits = cond_logits + (cond_logits - uncond_logits) * cfg_scale | |
| else: | |
| logits = self.forward( | |
| ids, condition, cond_drop_prob=0.0 | |
| ) | |
| if softmax_temperature_annealing: | |
| softmax_temperature = 0.5 + 0.8 * (1 - ratio) | |
| logits = logits / softmax_temperature | |
| # Add gumbel noise | |
| def log(t, eps=1e-20): | |
| return torch.log(t.clamp(min=eps)) | |
| def gumbel_noise(t): | |
| noise = torch.zeros_like(t).uniform_(0, 1) | |
| return -log(-log(noise)) | |
| def add_gumbel_noise(t, temperature): | |
| return t + temperature * gumbel_noise(t) | |
| sampled_ids = add_gumbel_noise(logits, annealed_temp).argmax(dim=-1) | |
| sampled_logits = torch.squeeze( | |
| torch.gather(logits, dim=-1, index=torch.unsqueeze(sampled_ids, -1)), -1) | |
| sampled_ids = torch.where(is_mask, sampled_ids, ids) | |
| sampled_logits = torch.where(is_mask, sampled_logits, +np.inf).float() | |
| # masking | |
| mask_ratio = np.arccos(ratio) / (math.pi * 0.5) | |
| mask_len = torch.Tensor([np.floor(image_seq_len * mask_ratio)]).to(device) | |
| mask_len = torch.maximum(torch.Tensor([1]).to(device), | |
| torch.minimum(torch.sum(is_mask, dim=-1, keepdims=True) - 1, | |
| mask_len))[0].squeeze() | |
| confidence = add_gumbel_noise(sampled_logits, annealed_temp) | |
| sorted_confidence, _ = torch.sort(confidence, axis=-1) | |
| cut_off = sorted_confidence[:, mask_len.long() - 1:mask_len.long()] | |
| masking = (confidence <= cut_off) | |
| if step == num_sample_steps - 1: | |
| ids = sampled_ids | |
| else: | |
| ids = torch.where(masking, self.mask_token_id, sampled_ids) | |
| if guidance_decay == "linear": | |
| cfg_scale = ratio * guidance_scale | |
| return ids | |
| def masking_input_tokens(self, input_tokens): | |
| batch_size, seq_len = input_tokens.shape | |
| device = input_tokens.device | |
| timesteps = torch.zeros((batch_size,), device=device).float().uniform_(0, 1.0) | |
| mask_ratio = torch.acos(timesteps) / (math.pi * 0.5) # arccos schedule | |
| mask_ratio = torch.clamp(mask_ratio, min=1e-6, max=1.) | |
| num_token_masked = (seq_len * mask_ratio).round().clamp(min=1) | |
| batch_randperm = torch.rand(batch_size, seq_len, device=device).argsort(dim=-1) | |
| masks = batch_randperm < rearrange(num_token_masked, 'b -> b 1') | |
| masked_tokens = torch.where(masks, self.mask_token_id, input_tokens) | |
| return masked_tokens, masks | |
| class MLMLoss(torch.nn.Module): | |
| def __init__(self, | |
| config): | |
| super().__init__() | |
| self.label_smoothing = config.losses.label_smoothing | |
| self.loss_weight_unmasked_token = config.losses.loss_weight_unmasked_token | |
| self.criterion = torch.nn.CrossEntropyLoss(label_smoothing=self.label_smoothing, | |
| reduction="none") | |
| def forward(self, inputs: torch.Tensor, targets: torch.Tensor, | |
| weights=None): | |
| inputs = rearrange(inputs, "b n c -> b c n") | |
| loss = self.criterion(inputs, targets) | |
| weights = weights.to(loss) | |
| loss_weights = ( | |
| 1.0 - weights) * self.loss_weight_unmasked_token + weights # set 0 to self.loss_weight_unasked_token | |
| loss = (loss * loss_weights).sum() / (loss_weights.sum() + 1e-8) | |
| # we only compute correct tokens on masked tokens | |
| correct_tokens = ((torch.argmax(inputs, dim=1) == targets) * weights).sum(dim=1) / (weights.sum(1) + 1e-8) | |
| return loss, {"loss": loss, "correct_tokens": correct_tokens.mean()} | |
| if __name__ == '__main__': | |
| # "generator": { | |
| # "model_type": "ViT", | |
| # "hidden_size": 768, | |
| # "num_hidden_layers": 24, | |
| # "num_attention_heads": 16, | |
| # "intermediate_size": 3072, | |
| # "dropout": 0.1, | |
| # "attn_drop": 0.1, | |
| # "num_steps": 8, | |
| # "class_label_dropout": 0.1, | |
| # "image_seq_len": 100, | |
| # "condition_num_classes": 1000, | |
| # "randomize_temperature": 1.0, | |
| # "guidance_scale": 4.5, | |
| # "guidance_decay": "constant" | |
| # } | |
| conf = { | |
| "model": { | |
| "vq_model": { | |
| "codebook_size": 512, | |
| "token_size": 12, | |
| "use_l2_norm": True, | |
| "commitment_cost": 0.25, | |
| "vit_enc_model_size": "base", | |
| "vit_dec_model_size": "base", | |
| "vit_enc_patch_size": 16, | |
| "vit_dec_patch_size": 16, | |
| "num_latent_tokens": 64, | |
| "finetune_decoder": True | |
| }, | |
| "generator": { | |
| "model_type": "ViT", | |
| "hidden_size": 512, | |
| "num_hidden_layers": 12, | |
| "num_attention_heads": 16, | |
| "intermediate_size": 2048, | |
| "dropout": 0.1, | |
| "attn_drop": 0.1, | |
| "num_steps": 8, | |
| "class_label_dropout": 0.1, | |
| "image_seq_len": 100, | |
| "condition_dim": 192, | |
| "randomize_temperature": 1.0, | |
| "guidance_scale": 4.5, | |
| "guidance_decay": "constant" | |
| } | |
| }, | |
| "losses": { | |
| "label_smoothing": 0.1, | |
| "loss_weight_unmasked_token": 0.1 | |
| } | |
| } | |
| config = OmegaConf.create(conf) | |
| loss_module = MLMLoss(config) | |
| model = ImageBert(config) | |
| print(model) | |
| print("n params", sum(p.numel() for p in model.parameters() if p.requires_grad)/1e6, "M") | |
| input_tokens = torch.randint(0, 512, (2, 100)) | |
| masked_tokens, masks = model.masking_input_tokens( | |
| input_tokens) | |
| conditions = torch.randn(2, 100, 192) | |
| logits = model(masked_tokens, conditions, | |
| cond_drop_prob=0.1) | |
| print(logits.shape) | |
| loss, loss_dict = loss_module(logits, input_tokens, weights=masks) | |
| print(loss, loss_dict) | |
| ids = model.generate( | |
| conditions | |
| ) | |
| print(ids) |