repo_name
stringlengths
7
71
file_path
stringlengths
5
118
context
list
import_statement
stringlengths
45
12.5k
token_num
int64
641
99.4k
cropped_code
stringlengths
44
17k
all_code
stringlengths
43
754k
next_line
stringlengths
2
330
gold_snippet_index
int64
0
68
created_at
stringlengths
25
25
level
stringclasses
9 values
daveredrum/SceneTex
models/pipeline/texture_pipeline.py
[ { "identifier": "TextureMesh", "path": "models/modules/meshes.py", "snippet": "class TextureMesh(nn.Module):\n def __init__(self, \n config,\n device\n ): \n \n super().__init__()\n \n self.config = config\n self.device = device\n\n self.num_...
import random import wandb import json import os import time import torch import torch.nn as nn import torch.nn.functional as F import torchvision import numpy as np import pytorch_lightning as pl import matplotlib.pyplot as plt import sys import open_clip from torch.optim import Adam, AdamW from torch.optim.lr_scheduler import LinearLR from omegaconf import OmegaConf from tqdm import tqdm from omegaconf import OmegaConf from PIL import Image from copy import deepcopy from pathlib import Path from pytorch3d.io import ( load_obj, load_objs_as_meshes ) from pytorch3d.renderer import TexturesUV from pytorch3d.ops import interpolate_face_attributes from models.modules import TextureMesh, Studio, Guidance
10,818
# mat # customized sys.path.append("./lib") class TexturePipeline(nn.Module): def __init__(self, config, stamp, device ): super().__init__() self.config = config self.stamp = stamp self.prompt = config.prompt + ", " + config.a_prompt if config.a_prompt else config.prompt self.n_prompt = config.n_prompt self.device = device self.weights_dtype = torch.float16 if self.config.enable_half_precision else torch.float32 print("=> Use precision: {}".format(self.weights_dtype)) pl.seed_everything(self.config.seed) """call this after to(device)""" def configure(self, inference_mode=False): if not inference_mode: self.log_name = "_".join(self.config.prompt.split(' ')) self.log_stamp = self.stamp self.log_dir = os.path.join(self.config.log_dir, self.log_name, self.config.loss_type, self.log_stamp) # override config self.config.log_name = self.log_name self.config.log_stamp = self.log_stamp self.config.log_dir = self.log_dir # 3D assets self._init_mesh() # studio self._init_studio() # instances self._init_anchors() if not inference_mode: # diffusion self._init_guidance() # optimization self._configure_optimizers() self._init_logger() if self.config.enable_clip_benchmark: self.clip, _, self.clip_preprocess = open_clip.create_model_and_transforms('ViT-B-32', pretrained='laion2b_s34b_b79k') self.clip_tokenizer = open_clip.get_tokenizer('ViT-B-32') def _init_studio(self):
# mat # customized sys.path.append("./lib") class TexturePipeline(nn.Module): def __init__(self, config, stamp, device ): super().__init__() self.config = config self.stamp = stamp self.prompt = config.prompt + ", " + config.a_prompt if config.a_prompt else config.prompt self.n_prompt = config.n_prompt self.device = device self.weights_dtype = torch.float16 if self.config.enable_half_precision else torch.float32 print("=> Use precision: {}".format(self.weights_dtype)) pl.seed_everything(self.config.seed) """call this after to(device)""" def configure(self, inference_mode=False): if not inference_mode: self.log_name = "_".join(self.config.prompt.split(' ')) self.log_stamp = self.stamp self.log_dir = os.path.join(self.config.log_dir, self.log_name, self.config.loss_type, self.log_stamp) # override config self.config.log_name = self.log_name self.config.log_stamp = self.log_stamp self.config.log_dir = self.log_dir # 3D assets self._init_mesh() # studio self._init_studio() # instances self._init_anchors() if not inference_mode: # diffusion self._init_guidance() # optimization self._configure_optimizers() self._init_logger() if self.config.enable_clip_benchmark: self.clip, _, self.clip_preprocess = open_clip.create_model_and_transforms('ViT-B-32', pretrained='laion2b_s34b_b79k') self.clip_tokenizer = open_clip.get_tokenizer('ViT-B-32') def _init_studio(self):
self.studio = Studio(self.config, self.device)
1
2023-11-28 15:38:40+00:00
16k
Vchitect/VBench
vbench/third_party/umt/datasets/build.py
[ { "identifier": "TubeMaskingGenerator", "path": "vbench/third_party/umt/datasets/masking_generator.py", "snippet": "class TubeMaskingGenerator:\n def __init__(self, input_size, mask_ratio):\n self.frames, self.height, self.width = input_size\n self.num_patches_per_frame = self.height * ...
import os from torchvision import transforms from .transforms import * from .masking_generator import TubeMaskingGenerator, RandomMaskingGenerator from .mae import VideoMAE from .kinetics import VideoClsDataset from .kinetics_sparse import VideoClsDataset_sparse from .ssv2 import SSVideoClsDataset, SSRawFrameClsDataset
14,352
class DataAugmentationForVideoMAE(object): def __init__(self, args): self.input_mean = [0.485, 0.456, 0.406] # IMAGENET_DEFAULT_MEAN self.input_std = [0.229, 0.224, 0.225] # IMAGENET_DEFAULT_STD normalize = GroupNormalize(self.input_mean, self.input_std) self.train_augmentation = GroupMultiScaleCrop(args.input_size, [1, .875, .75, .66]) if args.color_jitter > 0: self.transform = transforms.Compose([ self.train_augmentation, GroupColorJitter(args.color_jitter), GroupRandomHorizontalFlip(flip=args.flip), Stack(roll=False), ToTorchFormatTensor(div=True), normalize, ]) else: self.transform = transforms.Compose([ self.train_augmentation, GroupRandomHorizontalFlip(flip=args.flip), Stack(roll=False), ToTorchFormatTensor(div=True), normalize, ]) if args.mask_type == 'tube':
class DataAugmentationForVideoMAE(object): def __init__(self, args): self.input_mean = [0.485, 0.456, 0.406] # IMAGENET_DEFAULT_MEAN self.input_std = [0.229, 0.224, 0.225] # IMAGENET_DEFAULT_STD normalize = GroupNormalize(self.input_mean, self.input_std) self.train_augmentation = GroupMultiScaleCrop(args.input_size, [1, .875, .75, .66]) if args.color_jitter > 0: self.transform = transforms.Compose([ self.train_augmentation, GroupColorJitter(args.color_jitter), GroupRandomHorizontalFlip(flip=args.flip), Stack(roll=False), ToTorchFormatTensor(div=True), normalize, ]) else: self.transform = transforms.Compose([ self.train_augmentation, GroupRandomHorizontalFlip(flip=args.flip), Stack(roll=False), ToTorchFormatTensor(div=True), normalize, ]) if args.mask_type == 'tube':
self.masked_position_generator = TubeMaskingGenerator(
0
2023-11-27 12:41:46+00:00
16k
HyeonHo99/Video-Motion-Customization
showone/models/unet_3d_condition.py
[ { "identifier": "TransformerTemporalModel", "path": "showone/models/transformer_temporal.py", "snippet": "class TransformerTemporalModel(ModelMixin, ConfigMixin):\n \"\"\"\n A Transformer model for video-like data.\n\n Parameters:\n num_attention_heads (`int`, *optional*, defaults to 16)...
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.loaders import UNet2DConditionLoadersMixin from diffusers.utils import BaseOutput, logging from diffusers.models.activations import get_activation from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor from diffusers.models.embeddings import ( GaussianFourierProjection, ImageHintTimeEmbedding, ImageProjection, ImageTimeEmbedding, TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps, ) from diffusers.models.modeling_utils import ModelMixin from .transformer_temporal import TransformerTemporalModel from .unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UNetMidBlock3DSimpleCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from diffusers.utils import WEIGHTS_NAME import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint import os, json
13,182
for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) return processors for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors) return processors def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): r""" Sets the attention processor to use to compute attention. Parameters: processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): The instantiated processor class or a dictionary of processor classes that will be set as the processor for **all** `Attention` layers. If `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors. """ # count = len(self.attn_processors.keys()) # ignore temporal attention count = len({k: v for k, v in self.attn_processors.items() if "temp_" not in k}.keys()) # Show-1 original line #count = len(self.attn_processors.keys()) # --> If BoxDiff: use this line if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): if hasattr(module, "set_processor") and "temp_" not in name: if not isinstance(processor, dict): module.set_processor(processor) else: module.set_processor(processor.pop(f"{name}.processor")) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) for name, module in self.named_children(): fn_recursive_attn_processor(name, module, processor) def set_default_attn_processor(self): """ Disables custom attention processors and sets the default attention implementation. """ self.set_attn_processor(AttnProcessor()) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module splits the input tensor in slices to compute attention in several steps. This is useful for saving some memory in exchange for a small decrease in speed. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_sliceable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_sliceable_dims(module) num_sliceable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_sliceable_layers * [1] slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, module, value=False):
# Copyright 2023 Alibaba DAMO-VILAB and The HuggingFace Team. All rights reserved. # Copyright 2023 The ModelScope Team. # # 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. # from diffusers.models.transformer_temporal import TransformerTemporalModel logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): """ Args: sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`): Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): r""" UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep and returns sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library implements for all the models (such as downloading or saving, etc.) Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): The number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`): The tuple of upsample blocks to use. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. If `None`, it will skip the normalization and activation layers in post-processing norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), mid_block_type: Optional[str] = "UNetMidBlock3DCrossAttn", up_block_types: Tuple[str] = ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: Union[int, Tuple[int]] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: Union[int, Tuple[int]] = 1280, transformer_layers_per_block: Union[int, Tuple[int]] = 1, encoder_hid_dim: Optional[int] = None, encoder_hid_dim_type: Optional[str] = None, attention_head_dim: Union[int, Tuple[int]] = 8, num_attention_heads: Optional[Union[int, Tuple[int]]] = None, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, addition_embed_type: Optional[str] = None, addition_time_embed_dim: Optional[int] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", resnet_skip_time_act: bool = False, resnet_out_scale_factor: int = 1.0, time_embedding_type: str = "positional", time_embedding_dim: Optional[int] = None, time_embedding_act_fn: Optional[str] = None, timestep_post_act: Optional[str] = None, time_cond_proj_dim: Optional[int] = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, projection_class_embeddings_input_dim: Optional[int] = None, class_embeddings_concat: bool = False, mid_block_only_cross_attention: Optional[bool] = None, cross_attention_norm: Optional[str] = None, addition_embed_type_num_heads=64, transfromer_in_opt: bool =False, ): super().__init__() self.sample_size = sample_size self.transformer_in_opt = transfromer_in_opt if num_attention_heads is not None: raise ValueError( "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19." ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. num_attention_heads = num_attention_heads or attention_head_dim # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." ) if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types): raise ValueError( f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}." ) if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): raise ValueError( f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." ) if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}." ) if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." ) if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): raise ValueError( f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." ) # input conv_in_padding = (conv_in_kernel - 1) // 2 self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding ) if self.transformer_in_opt: self.transformer_in = TransformerTemporalModel( num_attention_heads=8, attention_head_dim=64, in_channels=block_out_channels[0], num_layers=1, ) # time if time_embedding_type == "fourier": time_embed_dim = time_embedding_dim or block_out_channels[0] * 2 if time_embed_dim % 2 != 0: raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.") self.time_proj = GaussianFourierProjection( time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos ) timestep_input_dim = time_embed_dim elif time_embedding_type == "positional": time_embed_dim = time_embedding_dim or block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] else: raise ValueError( f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`." ) self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, post_act_fn=timestep_post_act, cond_proj_dim=time_cond_proj_dim, ) if encoder_hid_dim_type is None and encoder_hid_dim is not None: encoder_hid_dim_type = "text_proj" self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type) logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.") if encoder_hid_dim is None and encoder_hid_dim_type is not None: raise ValueError( f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}." ) if encoder_hid_dim_type == "text_proj": self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim) elif encoder_hid_dim_type == "text_image_proj": # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)` self.encoder_hid_proj = TextImageProjection( text_embed_dim=encoder_hid_dim, image_embed_dim=cross_attention_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type == "image_proj": # Kandinsky 2.2 self.encoder_hid_proj = ImageProjection( image_embed_dim=encoder_hid_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type is not None: raise ValueError( f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'." ) else: self.encoder_hid_proj = None # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) elif class_embed_type == "projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" ) # The projection `class_embed_type` is the same as the timestep `class_embed_type` except # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings # 2. it projects from an arbitrary input dimension. # # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. # As a result, `TimestepEmbedding` can be passed arbitrary vectors. self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif class_embed_type == "simple_projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" ) self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) else: self.class_embedding = None if addition_embed_type == "text": if encoder_hid_dim is not None: text_time_embedding_from_dim = encoder_hid_dim else: text_time_embedding_from_dim = cross_attention_dim self.add_embedding = TextTimeEmbedding( text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads ) elif addition_embed_type == "text_image": # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` self.add_embedding = TextImageTimeEmbedding( text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim ) elif addition_embed_type == "text_time": self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif addition_embed_type == "image": # Kandinsky 2.2 self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type == "image_hint": # Kandinsky 2.2 ControlNet self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type is not None: raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") if time_embedding_act_fn is None: self.time_embed_act = None else: self.time_embed_act = get_activation(time_embedding_act_fn) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): if mid_block_only_cross_attention is None: mid_block_only_cross_attention = only_cross_attention only_cross_attention = [only_cross_attention] * len(down_block_types) if mid_block_only_cross_attention is None: mid_block_only_cross_attention = False if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block[i], transformer_layers_per_block=transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, temb_channels=blocks_time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim[i], num_attention_heads=num_attention_heads[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn": self.mid_block = UNetMidBlock3DCrossAttn( transformer_layers_per_block=transformer_layers_per_block[-1], in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim[-1], num_attention_heads=num_attention_heads[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, ) elif mid_block_type == "UNetMidBlock3DSimpleCrossAttn": self.mid_block = UNetMidBlock3DSimpleCrossAttn( in_channels=block_out_channels[-1], temb_channels=blocks_time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, cross_attention_dim=cross_attention_dim[-1], attention_head_dim=attention_head_dim[-1], resnet_groups=norm_num_groups, resnet_time_scale_shift=resnet_time_scale_shift, skip_time_act=resnet_skip_time_act, only_cross_attention=mid_block_only_cross_attention, cross_attention_norm=cross_attention_norm, ) elif mid_block_type is None: self.mid_block = None else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the images self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_num_attention_heads = list(reversed(num_attention_heads)) reversed_layers_per_block = list(reversed(layers_per_block)) reversed_cross_attention_dim = list(reversed(cross_attention_dim)) reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=reversed_layers_per_block[i] + 1, transformer_layers_per_block=reversed_transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=blocks_time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=reversed_cross_attention_dim[i], num_attention_heads=reversed_num_attention_heads[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, resnet_skip_time_act=resnet_skip_time_act, resnet_out_scale_factor=resnet_out_scale_factor, cross_attention_norm=cross_attention_norm, attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out if norm_num_groups is not None: self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = get_activation(act_fn) else: self.conv_norm_out = None self.conv_act = None conv_out_padding = (conv_out_kernel - 1) // 2 self.conv_out = nn.Conv2d( block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding ) @property def attn_processors(self) -> Dict[str, AttentionProcessor]: r""" Returns: `dict` of attention processors: A dictionary containing all attention processors used in the model with indexed by its weight name. """ # set recursively processors = {} def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): if hasattr(module, "set_processor"): processors[f"{name}.processor"] = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) return processors for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors) return processors def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): r""" Sets the attention processor to use to compute attention. Parameters: processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): The instantiated processor class or a dictionary of processor classes that will be set as the processor for **all** `Attention` layers. If `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors. """ # count = len(self.attn_processors.keys()) # ignore temporal attention count = len({k: v for k, v in self.attn_processors.items() if "temp_" not in k}.keys()) # Show-1 original line #count = len(self.attn_processors.keys()) # --> If BoxDiff: use this line if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): if hasattr(module, "set_processor") and "temp_" not in name: if not isinstance(processor, dict): module.set_processor(processor) else: module.set_processor(processor.pop(f"{name}.processor")) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) for name, module in self.named_children(): fn_recursive_attn_processor(name, module, processor) def set_default_attn_processor(self): """ Disables custom attention processors and sets the default attention implementation. """ self.set_attn_processor(AttnProcessor()) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module splits the input tensor in slices to compute attention in several steps. This is useful for saving some memory in exchange for a small decrease in speed. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_sliceable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_sliceable_dims(module) num_sliceable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_sliceable_layers * [1] slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
2
2023-11-29 17:23:45+00:00
16k
xmu-xiaoma666/X-Dreamer
unet_2d_blocks.py
[ { "identifier": "AdaGroupNorm", "path": "attention.py", "snippet": "class AdaGroupNorm(nn.Module):\n \"\"\"\n GroupNorm layer modified to incorporate timestep embeddings.\n \"\"\"\n\n def __init__(\n self, embedding_dim: int, out_dim: int, num_groups: int, act_fn: Optional[str] = None...
from typing import Any, Dict, Optional, Tuple from torch import nn from diffusers.utils import is_torch_version, logging from diffusers.models.activations import get_activation from diffusers.models.dual_transformer_2d import DualTransformer2DModel from attention import AdaGroupNorm from attention_processor import Attention, AttnAddedKVProcessor, AttnAddedKVProcessor2_0 from diffusers.models.resnet import Downsample2D, FirDownsample2D, FirUpsample2D, KDownsample2D, KUpsample2D, ResnetBlock2D, Upsample2D from transformer_2d import Transformer2DModel import numpy as np import torch import torch.nn.functional as F
12,400
output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ) self.attentions = nn.ModuleList(attentions) self.resnets = nn.ModuleList(resnets) self.gradient_checkpointing = False def forward( self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, cross_attention_kwargs: Optional[Dict[str, Any]] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, ################################################### index: Optional[torch.FloatTensor] = None, came_posfeat: Optional[torch.FloatTensor] = None, ################################################### ) -> torch.FloatTensor: hidden_states = self.resnets[0](hidden_states, temb) for attn, resnet in zip(self.attentions, self.resnets[1:]): if self.training and self.gradient_checkpointing: def create_custom_forward(module, return_dict=None): def custom_forward(*inputs): if return_dict is not None: return module(*inputs, return_dict=return_dict) else: return module(*inputs) return custom_forward ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} hidden_states = attn( hidden_states, encoder_hidden_states=encoder_hidden_states, cross_attention_kwargs=cross_attention_kwargs, attention_mask=attention_mask, encoder_attention_mask=encoder_attention_mask, return_dict=False, )[0] hidden_states = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, temb, **ckpt_kwargs, ) else: hidden_states, attention_map = attn( hidden_states, encoder_hidden_states=encoder_hidden_states, cross_attention_kwargs=cross_attention_kwargs, attention_mask=attention_mask, encoder_attention_mask=encoder_attention_mask, return_dict=False, ######################### index=index, came_posfeat = came_posfeat, ############################# )#[0] ########################################## hidden_states = hidden_states[0] ############################################ hidden_states = resnet(hidden_states, temb) return hidden_states, attention_map class UNetMidBlock2DSimpleCrossAttn(nn.Module): def __init__( self, in_channels: int, temb_channels: int, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_time_scale_shift: str = "default", resnet_act_fn: str = "swish", resnet_groups: int = 32, resnet_pre_norm: bool = True, attention_head_dim=1, output_scale_factor=1.0, cross_attention_dim=1280, skip_time_act=False, only_cross_attention=False, cross_attention_norm=None, ): super().__init__() self.has_cross_attention = True self.attention_head_dim = attention_head_dim resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) self.num_heads = in_channels // self.attention_head_dim # there is always at least one resnet resnets = [ ResnetBlock2D( in_channels=in_channels, out_channels=in_channels, temb_channels=temb_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, time_embedding_norm=resnet_time_scale_shift, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, skip_time_act=skip_time_act, ) ] attentions = [] for _ in range(num_layers): processor = (
# Copyright 2023 The HuggingFace Team. All rights reserved. # # 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. # from ..utils import is_torch_version, logging # from .activations import get_activation # from .dual_transformer_2d import DualTransformer2DModel logger = logging.get_logger(__name__) # pylint: disable=invalid-name def get_down_block( down_block_type, num_layers, in_channels, out_channels, temb_channels, add_downsample, resnet_eps, resnet_act_fn, transformer_layers_per_block=1, num_attention_heads=None, resnet_groups=None, cross_attention_dim=None, downsample_padding=None, dual_cross_attention=False, use_linear_projection=False, only_cross_attention=False, upcast_attention=False, resnet_time_scale_shift="default", attention_type="default", resnet_skip_time_act=False, resnet_out_scale_factor=1.0, cross_attention_norm=None, attention_head_dim=None, downsample_type=None, ): # If attn head dim is not defined, we default it to the number of heads if attention_head_dim is None: logger.warn( f"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}." ) attention_head_dim = num_attention_heads down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type if down_block_type == "DownBlock2D": return DownBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, downsample_padding=downsample_padding, resnet_time_scale_shift=resnet_time_scale_shift, ) elif down_block_type == "ResnetDownsampleBlock2D": return ResnetDownsampleBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, resnet_time_scale_shift=resnet_time_scale_shift, skip_time_act=resnet_skip_time_act, output_scale_factor=resnet_out_scale_factor, ) elif down_block_type == "AttnDownBlock2D": if add_downsample is False: downsample_type = None else: downsample_type = downsample_type or "conv" # default to 'conv' return AttnDownBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, downsample_padding=downsample_padding, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, downsample_type=downsample_type, ) elif down_block_type == "CrossAttnDownBlock2D": if cross_attention_dim is None: raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock2D") return CrossAttnDownBlock2D( num_layers=num_layers, transformer_layers_per_block=transformer_layers_per_block, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, downsample_padding=downsample_padding, cross_attention_dim=cross_attention_dim, num_attention_heads=num_attention_heads, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention, upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, attention_type=attention_type, ) elif down_block_type == "SimpleCrossAttnDownBlock2D": if cross_attention_dim is None: raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnDownBlock2D") return SimpleCrossAttnDownBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, cross_attention_dim=cross_attention_dim, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, skip_time_act=resnet_skip_time_act, output_scale_factor=resnet_out_scale_factor, only_cross_attention=only_cross_attention, cross_attention_norm=cross_attention_norm, ) elif down_block_type == "SkipDownBlock2D": return SkipDownBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, downsample_padding=downsample_padding, resnet_time_scale_shift=resnet_time_scale_shift, ) elif down_block_type == "AttnSkipDownBlock2D": return AttnSkipDownBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, ) elif down_block_type == "DownEncoderBlock2D": return DownEncoderBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, downsample_padding=downsample_padding, resnet_time_scale_shift=resnet_time_scale_shift, ) elif down_block_type == "AttnDownEncoderBlock2D": return AttnDownEncoderBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, downsample_padding=downsample_padding, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, ) elif down_block_type == "KDownBlock2D": return KDownBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, ) elif down_block_type == "KCrossAttnDownBlock2D": return KCrossAttnDownBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_downsample=add_downsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, cross_attention_dim=cross_attention_dim, attention_head_dim=attention_head_dim, add_self_attention=True if not add_downsample else False, ) raise ValueError(f"{down_block_type} does not exist.") def get_up_block( up_block_type, num_layers, in_channels, out_channels, prev_output_channel, temb_channels, add_upsample, resnet_eps, resnet_act_fn, transformer_layers_per_block=1, num_attention_heads=None, resnet_groups=None, cross_attention_dim=None, dual_cross_attention=False, use_linear_projection=False, only_cross_attention=False, upcast_attention=False, resnet_time_scale_shift="default", attention_type="default", resnet_skip_time_act=False, resnet_out_scale_factor=1.0, cross_attention_norm=None, attention_head_dim=None, upsample_type=None, ): # If attn head dim is not defined, we default it to the number of heads if attention_head_dim is None: logger.warn( f"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}." ) attention_head_dim = num_attention_heads up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type if up_block_type == "UpBlock2D": return UpBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, prev_output_channel=prev_output_channel, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, resnet_time_scale_shift=resnet_time_scale_shift, ) elif up_block_type == "ResnetUpsampleBlock2D": return ResnetUpsampleBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, prev_output_channel=prev_output_channel, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, resnet_time_scale_shift=resnet_time_scale_shift, skip_time_act=resnet_skip_time_act, output_scale_factor=resnet_out_scale_factor, ) elif up_block_type == "CrossAttnUpBlock2D": if cross_attention_dim is None: raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock2D") return CrossAttnUpBlock2D( num_layers=num_layers, transformer_layers_per_block=transformer_layers_per_block, in_channels=in_channels, out_channels=out_channels, prev_output_channel=prev_output_channel, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, cross_attention_dim=cross_attention_dim, num_attention_heads=num_attention_heads, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention, upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, attention_type=attention_type, ) elif up_block_type == "SimpleCrossAttnUpBlock2D": if cross_attention_dim is None: raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnUpBlock2D") return SimpleCrossAttnUpBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, prev_output_channel=prev_output_channel, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, cross_attention_dim=cross_attention_dim, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, skip_time_act=resnet_skip_time_act, output_scale_factor=resnet_out_scale_factor, only_cross_attention=only_cross_attention, cross_attention_norm=cross_attention_norm, ) elif up_block_type == "AttnUpBlock2D": if add_upsample is False: upsample_type = None else: upsample_type = upsample_type or "conv" # default to 'conv' return AttnUpBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, prev_output_channel=prev_output_channel, temb_channels=temb_channels, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, upsample_type=upsample_type, ) elif up_block_type == "SkipUpBlock2D": return SkipUpBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, prev_output_channel=prev_output_channel, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_time_scale_shift=resnet_time_scale_shift, ) elif up_block_type == "AttnSkipUpBlock2D": return AttnSkipUpBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, prev_output_channel=prev_output_channel, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, ) elif up_block_type == "UpDecoderBlock2D": return UpDecoderBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, resnet_time_scale_shift=resnet_time_scale_shift, temb_channels=temb_channels, ) elif up_block_type == "AttnUpDecoderBlock2D": return AttnUpDecoderBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, resnet_groups=resnet_groups, attention_head_dim=attention_head_dim, resnet_time_scale_shift=resnet_time_scale_shift, temb_channels=temb_channels, ) elif up_block_type == "KUpBlock2D": return KUpBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, ) elif up_block_type == "KCrossAttnUpBlock2D": return KCrossAttnUpBlock2D( num_layers=num_layers, in_channels=in_channels, out_channels=out_channels, temb_channels=temb_channels, add_upsample=add_upsample, resnet_eps=resnet_eps, resnet_act_fn=resnet_act_fn, cross_attention_dim=cross_attention_dim, attention_head_dim=attention_head_dim, ) raise ValueError(f"{up_block_type} does not exist.") class AutoencoderTinyBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int, act_fn: str): super().__init__() act_fn = get_activation(act_fn) self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), act_fn, nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), act_fn, nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), ) self.skip = ( nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False) if in_channels != out_channels else nn.Identity() ) self.fuse = nn.ReLU() def forward(self, x): return self.fuse(self.conv(x) + self.skip(x)) class UNetMidBlock2D(nn.Module): def __init__( self, in_channels: int, temb_channels: int, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_time_scale_shift: str = "default", # default, spatial resnet_act_fn: str = "swish", resnet_groups: int = 32, resnet_pre_norm: bool = True, add_attention: bool = True, attention_head_dim=1, output_scale_factor=1.0, ): super().__init__() resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) self.add_attention = add_attention # there is always at least one resnet resnets = [ ResnetBlock2D( in_channels=in_channels, out_channels=in_channels, temb_channels=temb_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, time_embedding_norm=resnet_time_scale_shift, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ] attentions = [] if attention_head_dim is None: logger.warn( f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}." ) attention_head_dim = in_channels for _ in range(num_layers): if self.add_attention: attentions.append( Attention( in_channels, heads=in_channels // attention_head_dim, dim_head=attention_head_dim, rescale_output_factor=output_scale_factor, eps=resnet_eps, norm_num_groups=resnet_groups if resnet_time_scale_shift == "default" else None, spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None, residual_connection=True, bias=True, upcast_softmax=True, _from_deprecated_attn_block=True, ) ) else: attentions.append(None) resnets.append( ResnetBlock2D( in_channels=in_channels, out_channels=in_channels, temb_channels=temb_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, time_embedding_norm=resnet_time_scale_shift, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ) self.attentions = nn.ModuleList(attentions) self.resnets = nn.ModuleList(resnets) def forward(self, hidden_states, temb=None): hidden_states = self.resnets[0](hidden_states, temb) for attn, resnet in zip(self.attentions, self.resnets[1:]): if attn is not None: hidden_states = attn(hidden_states, temb=temb) hidden_states = resnet(hidden_states, temb) return hidden_states class UNetMidBlock2DCrossAttn(nn.Module): def __init__( self, in_channels: int, temb_channels: int, dropout: float = 0.0, num_layers: int = 1, transformer_layers_per_block: int = 1, resnet_eps: float = 1e-6, resnet_time_scale_shift: str = "default", resnet_act_fn: str = "swish", resnet_groups: int = 32, resnet_pre_norm: bool = True, num_attention_heads=1, output_scale_factor=1.0, cross_attention_dim=1280, dual_cross_attention=False, use_linear_projection=False, upcast_attention=False, attention_type="default", ): super().__init__() self.has_cross_attention = True self.num_attention_heads = num_attention_heads resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) # there is always at least one resnet resnets = [ ResnetBlock2D( in_channels=in_channels, out_channels=in_channels, temb_channels=temb_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, time_embedding_norm=resnet_time_scale_shift, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ] attentions = [] for _ in range(num_layers): if not dual_cross_attention: attentions.append( Transformer2DModel( num_attention_heads, in_channels // num_attention_heads, in_channels=in_channels, num_layers=transformer_layers_per_block, cross_attention_dim=cross_attention_dim, norm_num_groups=resnet_groups, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, attention_type=attention_type, ) ) else: attentions.append( DualTransformer2DModel( num_attention_heads, in_channels // num_attention_heads, in_channels=in_channels, num_layers=1, cross_attention_dim=cross_attention_dim, norm_num_groups=resnet_groups, ) ) resnets.append( ResnetBlock2D( in_channels=in_channels, out_channels=in_channels, temb_channels=temb_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, time_embedding_norm=resnet_time_scale_shift, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ) self.attentions = nn.ModuleList(attentions) self.resnets = nn.ModuleList(resnets) self.gradient_checkpointing = False def forward( self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, cross_attention_kwargs: Optional[Dict[str, Any]] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, ################################################### index: Optional[torch.FloatTensor] = None, came_posfeat: Optional[torch.FloatTensor] = None, ################################################### ) -> torch.FloatTensor: hidden_states = self.resnets[0](hidden_states, temb) for attn, resnet in zip(self.attentions, self.resnets[1:]): if self.training and self.gradient_checkpointing: def create_custom_forward(module, return_dict=None): def custom_forward(*inputs): if return_dict is not None: return module(*inputs, return_dict=return_dict) else: return module(*inputs) return custom_forward ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} hidden_states = attn( hidden_states, encoder_hidden_states=encoder_hidden_states, cross_attention_kwargs=cross_attention_kwargs, attention_mask=attention_mask, encoder_attention_mask=encoder_attention_mask, return_dict=False, )[0] hidden_states = torch.utils.checkpoint.checkpoint( create_custom_forward(resnet), hidden_states, temb, **ckpt_kwargs, ) else: hidden_states, attention_map = attn( hidden_states, encoder_hidden_states=encoder_hidden_states, cross_attention_kwargs=cross_attention_kwargs, attention_mask=attention_mask, encoder_attention_mask=encoder_attention_mask, return_dict=False, ######################### index=index, came_posfeat = came_posfeat, ############################# )#[0] ########################################## hidden_states = hidden_states[0] ############################################ hidden_states = resnet(hidden_states, temb) return hidden_states, attention_map class UNetMidBlock2DSimpleCrossAttn(nn.Module): def __init__( self, in_channels: int, temb_channels: int, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_time_scale_shift: str = "default", resnet_act_fn: str = "swish", resnet_groups: int = 32, resnet_pre_norm: bool = True, attention_head_dim=1, output_scale_factor=1.0, cross_attention_dim=1280, skip_time_act=False, only_cross_attention=False, cross_attention_norm=None, ): super().__init__() self.has_cross_attention = True self.attention_head_dim = attention_head_dim resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) self.num_heads = in_channels // self.attention_head_dim # there is always at least one resnet resnets = [ ResnetBlock2D( in_channels=in_channels, out_channels=in_channels, temb_channels=temb_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, time_embedding_norm=resnet_time_scale_shift, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, skip_time_act=skip_time_act, ) ] attentions = [] for _ in range(num_layers): processor = (
AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor()
3
2023-11-27 13:44:01+00:00
16k
zhenzhiwang/intercontrol
eval/eval_controlmdm.py
[ { "identifier": "ControlGaussianDiffusion", "path": "diffusion/control_diffusion.py", "snippet": "class ControlGaussianDiffusion(SpacedDiffusion):\n\n def inv_transform(self, data):\n assert self.std is not None and self.mean is not None\n #assert data.requires_grad == True\n std...
from diffusion.control_diffusion import ControlGaussianDiffusion from diffusion.respace import SpacedDiffusion from utils.parser_util import evaluation_inpainting_parser from utils.fixseed import fixseed from datetime import datetime from data_loaders.humanml.motion_loaders.model_motion_loaders import get_mdm_loader # get_motion_loader from data_loaders.humanml.utils.metrics import * from data_loaders.humanml.networks.evaluator_wrapper import EvaluatorMDMWrapper from collections import OrderedDict from data_loaders.humanml.scripts.motion_process import * from data_loaders.humanml.utils.utils import * from utils.model_util import load_controlmdm_and_diffusion from model.ControlMDM import ControlMDM from diffusion import logger from utils import dist_util from data_loaders.get_data import get_dataset_loader from model.cfg_sampler import wrap_model
14,366
all_metrics['Skating Ratio'][key] += [item] for key, item in mat_score_dict.items(): if key not in all_metrics['Matching Score']: all_metrics['Matching Score'][key] = [item] else: all_metrics['Matching Score'][key] += [item] for key, item in R_precision_dict.items(): if key not in all_metrics['R_precision']: all_metrics['R_precision'][key] = [item] else: all_metrics['R_precision'][key] += [item] for key, item in fid_score_dict.items(): if key not in all_metrics['FID']: all_metrics['FID'][key] = [item] else: all_metrics['FID'][key] += [item] for key, item in div_score_dict.items(): if key not in all_metrics['Diversity']: all_metrics['Diversity'][key] = [item] else: all_metrics['Diversity'][key] += [item] if run_mm: for key, item in mm_score_dict.items(): if key not in all_metrics['MultiModality']: all_metrics['MultiModality'][key] = [item] else: all_metrics['MultiModality'][key] += [item] # print(all_metrics['Diversity']) mean_dict = {} for metric_name, metric_dict in all_metrics.items(): print('========== %s Summary ==========' % metric_name) print('========== %s Summary ==========' % metric_name, file=f, flush=True) for model_name, values in metric_dict.items(): # print(metric_name, model_name) mean, conf_interval = get_metric_statistics(np.array(values), replication_times) mean_dict[metric_name + '_' + model_name] = mean # print(mean, mean.dtype) if isinstance(mean, np.float64) or isinstance(mean, np.float32): print(f'---> [{model_name}] Mean: {mean:.4f} CInterval: {conf_interval:.4f}') print(f'---> [{model_name}] Mean: {mean:.4f} CInterval: {conf_interval:.4f}', file=f, flush=True) elif metric_name == 'Trajectory Error': traj_err_key = ["traj_fail_20cm", "traj_fail_50cm", "loc_fail_20cm", "loc_fail_50cm", "avg_err(m)"] line = f'---> [{model_name}]' print(line) print(line, file=f, flush=True) line = '' for i in range(len(mean)): # zip(traj_err_key, mean): line += ' (%s): Mean: %.4f CInt: %.4f; \n' % (traj_err_key[i], mean[i], conf_interval[i]) print(line) print(line, file=f, flush=True) elif isinstance(mean, np.ndarray): line = f'---> [{model_name}]' for i in range(len(mean)): line += '(top %d) Mean: %.4f CInt: %.4f;' % (i+1, mean[i], conf_interval[i]) print(line) print(line, file=f, flush=True) return mean_dict if __name__ == '__main__': args = evaluation_inpainting_parser() assert args.multi_person == False, 'multi-person is not supported for this script' assert args.guidance_param == 2.5 fixseed(args.seed) args.batch_size = 32 # This must be 32! Don't change it! otherwise it will cause a bug in R precision calc! model_name = os.path.basename(os.path.dirname(args.model_path)) niter = os.path.basename(args.model_path).replace('model', '').replace('.pt', '') dataset_name = args.dataset #log_file = os.path.join(os.path.dirname(args.model_path), 'eval_{}_{}_{}'.format(dataset_name, model_name, niter)) log_file = os.path.join(os.path.dirname(args.model_path), 'eval_niter_' + str(int(niter)) +'_'+ args.control_joint) assert args.inpainting_mask == 'global_joint', "This script only supports global_joint inpainting!" log_file += f'_mask{args.mask_ratio}' log_file += f'_bfgs_first{args.bfgs_times_first}_last{args.bfgs_times_last}_skip{args.bfgs_interval}' if args.use_posterior: log_file += '_posterior' else: log_file += '_x0' log_file += f'_{args.eval_mode}' log_file += '.log' print(f'Will save to log file [{log_file}]') assert args.overwrite or not os.path.exists(log_file), "Log file already exists!" print(f'Eval mode [{args.eval_mode}]') if args.eval_mode == 'debug': num_samples_limit = 1000 # None means no limit (eval over all dataset) run_mm = False mm_num_samples = 0 mm_num_repeats = 0 mm_num_times = 0 diversity_times = 300 replication_times = 5 # about 3 Hrs elif args.eval_mode == 'wo_mm': num_samples_limit = 1000 run_mm = False mm_num_samples = 0 mm_num_repeats = 0 mm_num_times = 0 diversity_times = 300 replication_times = 20 # about 12 Hrs elif args.eval_mode == 'mm_short': num_samples_limit = 1000 run_mm = True mm_num_samples = 100 mm_num_repeats = 30 mm_num_times = 10 diversity_times = 300 replication_times = 5 # about 15 Hrs else: raise ValueError() replication_times = replication_times if args.replication_times is None else args.replication_times dist_util.setup_dist(args.device)
torch.multiprocessing.set_sharing_strategy('file_system') def evaluate_matching_score(eval_wrapper, motion_loaders, file): match_score_dict = OrderedDict({}) R_precision_dict = OrderedDict({}) activation_dict = OrderedDict({}) trajectory_score_dict = OrderedDict({}) skating_ratio_dict = OrderedDict({}) print('========== Evaluating Matching Score ==========') for motion_loader_name, motion_loader in motion_loaders.items(): all_motion_embeddings = [] score_list = [] all_size = 0 matching_score_sum = 0 top_k_count = 0 skate_ratio_sum = 0.0 traj_err = [] traj_err_key = ["traj_fail_20cm", "traj_fail_50cm", "loc_fail_20cm", "loc_fail_50cm", "avg_err(m)"] # print(motion_loader_name) with torch.no_grad(): for idx, batch in enumerate(motion_loader): if motion_loader_name == 'ground truth': word_embeddings, pos_one_hots, _, sent_lens, motions, m_lens, _, _ = batch else: assert motion_loader_name == 'vald' # tested method named vald as default word_embeddings, pos_one_hots, _, sent_lens, motions, m_lens, _, skate_ratio, err_np = batch text_embeddings, motion_embeddings = eval_wrapper.get_co_embeddings( word_embs=word_embeddings, pos_ohot=pos_one_hots, cap_lens=sent_lens, motions=motions, m_lens=m_lens) dist_mat = euclidean_distance_matrix(text_embeddings.cpu().numpy(),motion_embeddings.cpu().numpy()) matching_score_sum += dist_mat.trace() argsmax = np.argsort(dist_mat, axis=1) top_k_mat = calculate_top_k(argsmax, top_k=3) top_k_count += top_k_mat.sum(axis=0) all_size += text_embeddings.shape[0] all_motion_embeddings.append(motion_embeddings.cpu().numpy()) if motion_loader_name != 'ground truth': traj_err.append(err_np) skate_ratio_sum += skate_ratio.sum() all_motion_embeddings = np.concatenate(all_motion_embeddings, axis=0) matching_score = matching_score_sum / all_size R_precision = top_k_count / all_size match_score_dict[motion_loader_name] = matching_score R_precision_dict[motion_loader_name] = R_precision activation_dict[motion_loader_name] = all_motion_embeddings if motion_loader_name != 'ground truth': ### For trajecotry evaluation ### traj_err = np.concatenate(traj_err).mean(0) trajectory_score_dict[motion_loader_name] = traj_err line = f'---> [{motion_loader_name}] Traj Error: ' print(line) print(line, file=file, flush=True) line = '' for (k, v) in zip(traj_err_key, traj_err): line += ' (%s): %.4f \n' % (k, np.mean(v)) print(line) print(line, file=file, flush=True) # For skating evaluation skating_score = skate_ratio_sum / all_size skating_ratio_dict[motion_loader_name] = skating_score print(f'---> [{motion_loader_name}] Skating Ratio: {skating_score:.4f}') print(f'---> [{motion_loader_name}] Skating Ratio: {skating_score:.4f}', file=file, flush=True) print(f'---> [{motion_loader_name}] Matching Score: {matching_score:.4f}') print(f'---> [{motion_loader_name}] Matching Score: {matching_score:.4f}',file=file,flush=True) line = f'---> [{motion_loader_name}] R_precision: ' for i in range(len(R_precision)): line += '(top %d): %.4f ' % (i + 1, R_precision[i]) print(line) print(line, file=file, flush=True) return match_score_dict, R_precision_dict, activation_dict, trajectory_score_dict, skating_ratio_dict def evaluate_fid(eval_wrapper, groundtruth_loader, activation_dict, file): eval_dict = OrderedDict({}) gt_motion_embeddings = [] print('========== Evaluating FID ==========') with torch.no_grad(): for idx, batch in enumerate(groundtruth_loader): _, _, _, sent_lens, motions, m_lens, _, _ = batch motion_embeddings = eval_wrapper.get_motion_embeddings( motions=motions, m_lens=m_lens ) gt_motion_embeddings.append(motion_embeddings.cpu().numpy()) gt_motion_embeddings = np.concatenate(gt_motion_embeddings, axis=0) gt_mu, gt_cov = calculate_activation_statistics(gt_motion_embeddings) # print(gt_mu) for model_name, motion_embeddings in activation_dict.items(): mu, cov = calculate_activation_statistics(motion_embeddings) # print(mu) fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov) print(f'---> [{model_name}] FID: {fid:.4f}') print(f'---> [{model_name}] FID: {fid:.4f}', file=file, flush=True) eval_dict[model_name] = fid return eval_dict def evaluate_diversity(activation_dict, file, diversity_times): eval_dict = OrderedDict({}) print('========== Evaluating Diversity ==========') for model_name, motion_embeddings in activation_dict.items(): diversity = calculate_diversity(motion_embeddings, diversity_times) eval_dict[model_name] = diversity print(f'---> [{model_name}] Diversity: {diversity:.4f}') print(f'---> [{model_name}] Diversity: {diversity:.4f}', file=file, flush=True) return eval_dict def evaluate_multimodality(eval_wrapper, mm_motion_loaders, file, mm_num_times): eval_dict = OrderedDict({}) print('========== Evaluating MultiModality ==========') for model_name, mm_motion_loader in mm_motion_loaders.items(): mm_motion_embeddings = [] with torch.no_grad(): for idx, batch in enumerate(mm_motion_loader): # (1, mm_replications, dim_pos) motions, m_lens = batch motion_embedings = eval_wrapper.get_motion_embeddings(motions[0], m_lens[0]) mm_motion_embeddings.append(motion_embedings.unsqueeze(0)) if len(mm_motion_embeddings) == 0: multimodality = 0 else: mm_motion_embeddings = torch.cat(mm_motion_embeddings, dim=0).cpu().numpy() multimodality = calculate_multimodality(mm_motion_embeddings, mm_num_times) print(f'---> [{model_name}] Multimodality: {multimodality:.4f}') print(f'---> [{model_name}] Multimodality: {multimodality:.4f}', file=file, flush=True) eval_dict[model_name] = multimodality return eval_dict def get_metric_statistics(values, replication_times): mean = np.mean(values, axis=0) std = np.std(values, axis=0) conf_interval = 1.96 * std / np.sqrt(replication_times) return mean, conf_interval def evaluation(eval_wrapper, gt_loader, eval_motion_loaders, log_file, replication_times, diversity_times, mm_num_times, run_mm=False): with open(log_file, 'w') as f: all_metrics = OrderedDict({'Matching Score': OrderedDict({}), 'R_precision': OrderedDict({}), 'FID': OrderedDict({}), 'Diversity': OrderedDict({}), 'MultiModality': OrderedDict({}), 'Trajectory Error': OrderedDict({}), 'Skating Ratio': OrderedDict({}), }) for replication in range(replication_times): motion_loaders = {} mm_motion_loaders = {} for motion_loader_name, motion_loader_getter in eval_motion_loaders.items(): motion_loader, mm_motion_loader = motion_loader_getter() motion_loaders[motion_loader_name] = motion_loader mm_motion_loaders[motion_loader_name] = mm_motion_loader motion_loaders['ground truth'] = gt_loader print(f'==================== Replication {replication} ====================') print(f'==================== Replication {replication} ====================', file=f, flush=True) print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) mat_score_dict, R_precision_dict, acti_dict, trajectory_score_dict, skating_ratio_dict = evaluate_matching_score(eval_wrapper, motion_loaders, f) print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) fid_score_dict = evaluate_fid(eval_wrapper, gt_loader, acti_dict, f) print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) div_score_dict = evaluate_diversity(acti_dict, f, diversity_times) if run_mm: print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) mm_score_dict = evaluate_multimodality(eval_wrapper, mm_motion_loaders, f, mm_num_times) print(f'!!! DONE !!!') print(f'!!! DONE !!!', file=f, flush=True) for key, item in trajectory_score_dict.items(): if key not in all_metrics['Trajectory Error']: all_metrics['Trajectory Error'][key] = [item] else: all_metrics['Trajectory Error'][key] += [item] for key, item in skating_ratio_dict.items(): if key not in all_metrics['Skating Ratio']: all_metrics['Skating Ratio'][key] = [item] else: all_metrics['Skating Ratio'][key] += [item] for key, item in mat_score_dict.items(): if key not in all_metrics['Matching Score']: all_metrics['Matching Score'][key] = [item] else: all_metrics['Matching Score'][key] += [item] for key, item in R_precision_dict.items(): if key not in all_metrics['R_precision']: all_metrics['R_precision'][key] = [item] else: all_metrics['R_precision'][key] += [item] for key, item in fid_score_dict.items(): if key not in all_metrics['FID']: all_metrics['FID'][key] = [item] else: all_metrics['FID'][key] += [item] for key, item in div_score_dict.items(): if key not in all_metrics['Diversity']: all_metrics['Diversity'][key] = [item] else: all_metrics['Diversity'][key] += [item] if run_mm: for key, item in mm_score_dict.items(): if key not in all_metrics['MultiModality']: all_metrics['MultiModality'][key] = [item] else: all_metrics['MultiModality'][key] += [item] # print(all_metrics['Diversity']) mean_dict = {} for metric_name, metric_dict in all_metrics.items(): print('========== %s Summary ==========' % metric_name) print('========== %s Summary ==========' % metric_name, file=f, flush=True) for model_name, values in metric_dict.items(): # print(metric_name, model_name) mean, conf_interval = get_metric_statistics(np.array(values), replication_times) mean_dict[metric_name + '_' + model_name] = mean # print(mean, mean.dtype) if isinstance(mean, np.float64) or isinstance(mean, np.float32): print(f'---> [{model_name}] Mean: {mean:.4f} CInterval: {conf_interval:.4f}') print(f'---> [{model_name}] Mean: {mean:.4f} CInterval: {conf_interval:.4f}', file=f, flush=True) elif metric_name == 'Trajectory Error': traj_err_key = ["traj_fail_20cm", "traj_fail_50cm", "loc_fail_20cm", "loc_fail_50cm", "avg_err(m)"] line = f'---> [{model_name}]' print(line) print(line, file=f, flush=True) line = '' for i in range(len(mean)): # zip(traj_err_key, mean): line += ' (%s): Mean: %.4f CInt: %.4f; \n' % (traj_err_key[i], mean[i], conf_interval[i]) print(line) print(line, file=f, flush=True) elif isinstance(mean, np.ndarray): line = f'---> [{model_name}]' for i in range(len(mean)): line += '(top %d) Mean: %.4f CInt: %.4f;' % (i+1, mean[i], conf_interval[i]) print(line) print(line, file=f, flush=True) return mean_dict if __name__ == '__main__': args = evaluation_inpainting_parser() assert args.multi_person == False, 'multi-person is not supported for this script' assert args.guidance_param == 2.5 fixseed(args.seed) args.batch_size = 32 # This must be 32! Don't change it! otherwise it will cause a bug in R precision calc! model_name = os.path.basename(os.path.dirname(args.model_path)) niter = os.path.basename(args.model_path).replace('model', '').replace('.pt', '') dataset_name = args.dataset #log_file = os.path.join(os.path.dirname(args.model_path), 'eval_{}_{}_{}'.format(dataset_name, model_name, niter)) log_file = os.path.join(os.path.dirname(args.model_path), 'eval_niter_' + str(int(niter)) +'_'+ args.control_joint) assert args.inpainting_mask == 'global_joint', "This script only supports global_joint inpainting!" log_file += f'_mask{args.mask_ratio}' log_file += f'_bfgs_first{args.bfgs_times_first}_last{args.bfgs_times_last}_skip{args.bfgs_interval}' if args.use_posterior: log_file += '_posterior' else: log_file += '_x0' log_file += f'_{args.eval_mode}' log_file += '.log' print(f'Will save to log file [{log_file}]') assert args.overwrite or not os.path.exists(log_file), "Log file already exists!" print(f'Eval mode [{args.eval_mode}]') if args.eval_mode == 'debug': num_samples_limit = 1000 # None means no limit (eval over all dataset) run_mm = False mm_num_samples = 0 mm_num_repeats = 0 mm_num_times = 0 diversity_times = 300 replication_times = 5 # about 3 Hrs elif args.eval_mode == 'wo_mm': num_samples_limit = 1000 run_mm = False mm_num_samples = 0 mm_num_repeats = 0 mm_num_times = 0 diversity_times = 300 replication_times = 20 # about 12 Hrs elif args.eval_mode == 'mm_short': num_samples_limit = 1000 run_mm = True mm_num_samples = 100 mm_num_repeats = 30 mm_num_times = 10 diversity_times = 300 replication_times = 5 # about 15 Hrs else: raise ValueError() replication_times = replication_times if args.replication_times is None else args.replication_times dist_util.setup_dist(args.device)
logger.configure()
8
2023-11-27 05:28:02+00:00
16k
moonbow721/DPoser
run/motion_denoising.py
[ { "identifier": "save_obj", "path": "lib/body_model/visual.py", "snippet": "def save_obj(v, f, file_name='output.obj'):\n obj_file = open(file_name, 'w')\n for i in range(len(v)):\n obj_file.write('v ' + str(v[i][0]) + ' ' + str(v[i][1]) + ' ' + str(v[i][2]) + '\\n')\n for i in range(len...
import csv import os import cv2 import math import numpy as np import torch import torch.nn as nn from absl import flags, app from absl.flags import argparse_flags from ml_collections.config_flags import config_flags from tqdm import tqdm from lib.body_model.visual import save_obj, render_mesh, faster_render, vis_skeletons from lib.algorithms.advanced import sde_lib, sampling from lib.algorithms.advanced import utils as mutils from lib.algorithms.advanced.model import ScoreModelFC from lib.algorithms.ema import ExponentialMovingAverage from lib.body_model.body_model import BodyModel from lib.utils.misc import linear_interpolation, gaussian_smoothing from lib.utils.motion_video import seq_to_video from lib.dataset.AMASS import Posenormalizer, N_POSES
11,826
quan_t = torch.randint(self.sde.N, [1]) elif time_strategy == '2': quan_t = torch.tensor(sample_time) elif time_strategy == '3': quan_t = self.sde.N - math.floor(torch.tensor(total_steps - step - 1) * (self.sde.N / (sample_trun * total_steps))) - 2 else: raise NotImplementedError('unsupported time sampling strategy') t = timesteps[quan_t] vec_t = torch.ones(self.batch_size, device=self.device) * t loss_dict['dposer'] = self.DPoser_loss(poses, vec_t, quan_t) ''' *********** DPoser loss ************ ''' # calculate temporal loss between mesh vertices smpl_init = self.body_model(betas=smpl_init.betas, pose_body=smpl_init.pose_body) temp_term = smpl_init.v[:-1] - smpl_init.v[1:] loss_dict['temp'] = torch.mean(torch.sqrt(torch.sum(temp_term * temp_term, dim=2))) # calculate data term from inital noisy pose data_term = smpl_init.Jtr[:, :22] - init_joints data_term = torch.mean(torch.sqrt(torch.sum(data_term * data_term, dim=2))) if data_term > 0: # for nans loss_dict['data'] = data_term # Get total loss for backward pass tot_loss = self.backward_step(loss_dict, weight_dict, it) tot_loss.backward() optimizer.step() if verbose: # only for check joint_error = smpl_init.Jtr[:, :22] - smpl_gt.Jtr[:, :22] joint_error = torch.mean(torch.sqrt(torch.sum(joint_error * joint_error, dim=2))) * 100. l_str = 'Step: {} Iter: {}'.format(it, i) l_str += ' j2j : {:0.8f}'.format(joint_error) l_str += ' total : {:0.8f}'.format(tot_loss) for k in loss_dict: l_str += ', {}: {:0.8f}'.format(k, loss_dict[k].mean().item()) loop.set_description(l_str) # create final results, the smoothing can be used to create consistent demo videos # Note that we do not use the smoothing for evaluation in our paper smooth_pose = gaussian_smoothing(smpl_init.pose_body, window_size=3, sigma=2) idx = [0, -1] smooth_pose[idx] = smpl_init.pose_body[idx] smpl_init = self.body_model(betas=self.betas, pose_body=smooth_pose) if vis: self.visualize(smpl_init.v, smpl_init.f, self.out_path, render=True, prefix='out', device=self.device) seq_to_video(os.path.join(self.out_path, 'renders'), os.path.join(self.out_path, 'merges'), video_path=os.path.join(self.out_path, 'motion.mp4')) joint_error = smpl_init.Jtr[:, :22] - smpl_gt.Jtr[:, :22] vert_error = smpl_init.v - smpl_gt.v MPJPE = torch.mean(torch.sqrt(torch.sum(joint_error * joint_error, dim=2)), dim=1) * 100. # remain batch dim MPVPE = torch.mean(torch.sqrt(torch.sum(vert_error * vert_error, dim=2)), dim=1) * 100. if verbose: print('after denoising:{:0.8f} cm'.format(MPJPE.mean())) results_dict = {'init_MPJPE': init_MPJPE.detach().cpu().numpy(), 'MPJPE': MPJPE.detach().cpu().numpy(), 'MPVPE': MPVPE.detach().cpu().numpy()} return results_dict def denoise(config, args, model, gt_file, out_path, std=0.04, verbose=False): motion_data_gt = np.load(gt_file)['pose_body'] batch_size = len(motion_data_gt) gt_poses = torch.from_numpy(motion_data_gt.astype(np.float32)).to(args.device) # [batchsize, 63] # load body model body_model = BodyModel(bm_path=args.bodymodel_path, model_type='smplx', batch_size=batch_size, num_betas=10).to( args.device) # generate noise on joints std = std joints3d = body_model(pose_body=gt_poses).Jtr[:, :22] noisy_joints3d = joints3d + std * torch.randn(*joints3d.shape, device=joints3d.device) if args.time_strategy in ['1']: sde_N = 500 dposer_weight = 1e-1 else: sde_N = 500 dposer_weight = 1.0 # If you try to reduce 'sample_trun' or 'sample_time', reduce weight too for converge. # create Motion denoiser layer motion_denoiser = MotionDenoise(config, args, model, sde_N=sde_N, body_model=body_model, dposer_weight=dposer_weight, # For axis setting 1e-1, batch_size=batch_size, out_path=out_path) if std == 0.02: kwargs = {'iterations': 3, 'steps_per_iter': 40, 'sample_trun': 10.0, 'sample_time': 495} elif std == 0.04: kwargs = {'iterations': 3, 'steps_per_iter': 60, 'sample_trun': 4.0, 'sample_time': 490} elif std == 0.1: kwargs = {'iterations': 3, 'steps_per_iter': 80, 'sample_trun': 3.0, 'sample_time': 480} else: raise NotImplementedError() if args.file_path is not None: # visualization for toy data verbose = True kwargs['vis'] = True batch_results = motion_denoiser.optimize(noisy_joints3d, gt_poses, args.time_strategy, verbose=verbose, **kwargs) return batch_results def main(args): def find_npz_files(data_dir): npz_files = [] for root, dirs, files in os.walk(data_dir): for file in files: if file.endswith('.npz'): npz_files.append(os.path.relpath(os.path.join(root, file), data_dir)) return npz_files torch.manual_seed(42) config = FLAGS.config POSE_DIM = 3 if config.data.rot_rep == 'axis' else 6 model = ScoreModelFC( config,
FLAGS = flags.FLAGS config_flags.DEFINE_config_file( "config", None, "Visualizing configuration.", lock_config=False) flags.mark_flags_as_required(["config"]) bg_img = np.ones([512, 384, 3]) * 255 # background canvas focal = [1500, 1500] princpt = [200, 192] def parse_args(argv): parser = argparse_flags.ArgumentParser(description='motion denosing (3D noisy joints -> clean poses)') parser.add_argument('--dataset-folder', type=str, default='../data/AMASS/amass_processed', help='the folder includes necessary normalizing parameters') parser.add_argument('--version', type=str, default='version1', help='dataset version') parser.add_argument('--ckpt-path', type=str, default='./pretrained_models/axis-zscore-400k.pth') parser.add_argument('--bodymodel-path', type=str, default='../body_models/smplx/SMPLX_NEUTRAL.npz', help='load SMPLX') parser.add_argument('--outpath-folder', type=str, default='./output/test_results/motion_denoise') parser.add_argument('--noise-std', type=float, default=0.04, help='control added noise scales') parser.add_argument('--time-strategy', type=str, default='3', choices=['1', '2', '3'], help='random, fix, truncated annealing') parser.add_argument('--device', type=str, default='cuda:0') # data preparation parser.add_argument('--file-path', type=str, help='use toy data to run') parser.add_argument('--data-dir', type=str, default='../humor/out/amass_joints_noisy_fitting/results_out', help='the whole AMASS testset, (output from HuMoR)') parser.add_argument('--dataset', type=str, default='AMASS') args = parser.parse_args(argv[1:]) return args class MotionDenoise(object): def __init__(self, config, args, diffusion_model, body_model, sde_N=1000, dposer_weight=1.0, out_path=None, debug=False, batch_size=1): self.args = args self.debug = debug self.device = args.device self.body_model = body_model self.dposer_weight = dposer_weight self.out_path = out_path # only needed for visualization self.batch_size = batch_size self.betas = torch.zeros((batch_size, 10), device=self.device) self.poses = torch.randn((batch_size, 63), device=self.device) * 0.01 self.Normalizer = Posenormalizer( data_path=f'{args.dataset_folder}/{args.version}/train', normalize=config.data.normalize, min_max=config.data.min_max, rot_rep=config.data.rot_rep, device=args.device) if config.training.sde.lower() == 'vpsde': sde = sde_lib.VPSDE(beta_min=config.model.beta_min, beta_max=config.model.beta_max, N=config.model.num_scales) elif config.training.sde.lower() == 'subvpsde': sde = sde_lib.subVPSDE(beta_min=config.model.beta_min, beta_max=config.model.beta_max, N=config.model.num_scales) elif config.training.sde.lower() == 'vesde': sde = sde_lib.VESDE(sigma_min=config.model.sigma_min, sigma_max=config.model.sigma_max, N=config.model.num_scales) else: raise NotImplementedError(f"SDE {config.training.sde} unknown.") sde.N = sde_N # discrete sampling steps self.sde = sde self.score_fn = mutils.get_score_fn(sde, diffusion_model, train=False, continuous=config.training.continuous) self.rsde = sde.reverse(self.score_fn, False) # L2 loss self.loss_fn = nn.MSELoss(reduction='none') def one_step_denoise(self, x_t, t): drift, diffusion, alpha, sigma_2, score = self.rsde.sde(x_t, t, guide=True) x_0_hat = (x_t + sigma_2[:, None] * score) / alpha SNR = alpha / torch.sqrt(sigma_2)[:, None] return x_0_hat.detach(), SNR def multi_step_denoise(self, x_t, t, t_end, N=10): time_traj = linear_interpolation(t, t_end, N + 1) x_current = x_t for i in range(N): t_current = time_traj[i] t_before = time_traj[i + 1] alpha_current, sigma_current = self.sde.return_alpha_sigma(t_current) alpha_before, sigma_before = self.sde.return_alpha_sigma(t_before) score = self.score_fn(x_current, t_current, condition=None, mask=None) score = -score * sigma_current[:, None] # score to noise prediction x_current = alpha_before / alpha_current * (x_current - sigma_current[:, None] * score) + sigma_before[ :, None] * score alpha, sigma = self.sde.return_alpha_sigma(time_traj[0]) SNR = alpha / sigma[:, None] return x_current.detach(), SNR # In our experiments, we found multi-step denoise will lead to worse results. def DPoser_loss(self, x_0, vec_t, quan_t, weighted=False, multi_denoise=False): # x_0: [B, j*6], vec_t: [B], quan_t: [1] z = torch.randn_like(x_0) mean, std = self.sde.marginal_prob(x_0, vec_t) perturbed_data = mean + std[:, None] * z # if multi_denoise: denoise_data, SNR = self.multi_step_denoise(perturbed_data, vec_t, t_end=vec_t / (2 * 10), N=10) else: denoise_data, SNR = self.one_step_denoise(perturbed_data, vec_t) if weighted: weight = 0.5 * torch.sqrt(1+SNR) else: weight = 0.5 dposer_loss = torch.sum(weight * self.loss_fn(x_0, denoise_data)) / self.batch_size return dposer_loss def RED_Diff(self, x_0, vec_t, quan_t): z = torch.randn_like(x_0) mean, std = self.sde.marginal_prob(x_0, vec_t) perturbed_data = mean + std[:, None] * z # _, _, alpha, sigma_2, score = self.rsde.sde(perturbed_data, vec_t, guide=True) score = -score * std[:, None] # score to noise prediction inverse_SNR = torch.sqrt(sigma_2) / alpha[:, 0] weight = inverse_SNR guidance = torch.mean(weight * torch.einsum('ij,ij->i', (score - z).detach(), x_0)) return guidance def get_loss_weights(self): """Set loss weights""" loss_weight = {'temp': lambda cst, it: 10. ** 1 * cst * (1 + it), 'data': lambda cst, it: 10. ** 2 * cst / (1 + it * it), 'dposer': lambda cst, it: 10. ** -1 * cst * (1 + it) * self.dposer_weight } return loss_weight @staticmethod def backward_step(loss_dict, weight_dict, it): w_loss = dict() for k in loss_dict: w_loss[k] = weight_dict[k](loss_dict[k], it) tot_loss = list(w_loss.values()) tot_loss = torch.stack(tot_loss).sum() return tot_loss @staticmethod def visualize(vertices, faces, out_path, render=False, prefix='out', save_mesh=False, faster=False, device=None): # save meshes and rendered results if needed os.makedirs(out_path, exist_ok=True) if save_mesh: vertices = vertices.detach().cpu() faces = faces.cpu() os.makedirs(os.path.join(out_path, 'meshes'), exist_ok=True) [save_obj(vertices[i], faces, os.path.join(out_path, 'meshes', '{}_{:04}.obj'.format(prefix, i))) for i in range(len(vertices))] if render: os.makedirs(os.path.join(out_path, 'renders'), exist_ok=True) if faster: assert device is not None target_path = os.path.join(out_path, 'renders') faster_render(vertices, faces, target_path, prefix + '_{:04}.jpg', device) else: vertices = vertices.detach().cpu() faces = faces.cpu() for i in range(len(vertices)): rendered_img = render_mesh(bg_img, vertices[i], faces, {'focal': focal, 'princpt': princpt}, view='front') cv2.imwrite(os.path.join(out_path, 'renders', '{}_{:04}.png'.format(prefix, i)), rendered_img) def optimize(self, joints3d, gt_poses=None, time_strategy='1', sample_trun=2.0, sample_time=990, iterations=5, steps_per_iter=50, verbose=False, vis=False): # create initial SMPL joints and vertices for visualition(to be used for data term) smpl_init = self.body_model(betas=self.betas, pose_body=self.poses) smpl_gt = self.body_model(betas=self.betas, pose_body=gt_poses) if vis: vis_skeletons(joints3d.detach().cpu().numpy(), os.path.join(self.out_path, 'renders')) print('skeleton figures saved') self.visualize(smpl_gt.v, smpl_gt.f, self.out_path, render=True, prefix='gt', device=self.device) joint_error = joints3d - smpl_gt.Jtr[:, :22] init_MPJPE = torch.mean(torch.sqrt(torch.sum(joint_error * joint_error, dim=2)), dim=1) * 100. if verbose: print('before denoising:{:0.8f} cm'.format(init_MPJPE.mean())) init_joints = joints3d.detach() # Optimizer smpl_init.pose_body.requires_grad = True optimizer = torch.optim.Adam([smpl_init.pose_body], 0.03, betas=(0.9, 0.999)) # Get loss_weights weight_dict = self.get_loss_weights() eps = 1e-3 timesteps = torch.linspace(self.sde.T, eps, self.sde.N, device=self.device) total_steps = iterations*steps_per_iter for it in range(iterations): if verbose: loop = tqdm(range(steps_per_iter)) loop.set_description('Optimizing SMPL poses') else: loop = range(steps_per_iter) for i in loop: step = it * steps_per_iter + i optimizer.zero_grad() loss_dict = dict() ''' ************* DPoser loss *********** ''' poses = self.Normalizer.offline_normalize(smpl_init.pose_body, from_axis=True) if time_strategy == '1': # not recommend quan_t = torch.randint(self.sde.N, [1]) elif time_strategy == '2': quan_t = torch.tensor(sample_time) elif time_strategy == '3': quan_t = self.sde.N - math.floor(torch.tensor(total_steps - step - 1) * (self.sde.N / (sample_trun * total_steps))) - 2 else: raise NotImplementedError('unsupported time sampling strategy') t = timesteps[quan_t] vec_t = torch.ones(self.batch_size, device=self.device) * t loss_dict['dposer'] = self.DPoser_loss(poses, vec_t, quan_t) ''' *********** DPoser loss ************ ''' # calculate temporal loss between mesh vertices smpl_init = self.body_model(betas=smpl_init.betas, pose_body=smpl_init.pose_body) temp_term = smpl_init.v[:-1] - smpl_init.v[1:] loss_dict['temp'] = torch.mean(torch.sqrt(torch.sum(temp_term * temp_term, dim=2))) # calculate data term from inital noisy pose data_term = smpl_init.Jtr[:, :22] - init_joints data_term = torch.mean(torch.sqrt(torch.sum(data_term * data_term, dim=2))) if data_term > 0: # for nans loss_dict['data'] = data_term # Get total loss for backward pass tot_loss = self.backward_step(loss_dict, weight_dict, it) tot_loss.backward() optimizer.step() if verbose: # only for check joint_error = smpl_init.Jtr[:, :22] - smpl_gt.Jtr[:, :22] joint_error = torch.mean(torch.sqrt(torch.sum(joint_error * joint_error, dim=2))) * 100. l_str = 'Step: {} Iter: {}'.format(it, i) l_str += ' j2j : {:0.8f}'.format(joint_error) l_str += ' total : {:0.8f}'.format(tot_loss) for k in loss_dict: l_str += ', {}: {:0.8f}'.format(k, loss_dict[k].mean().item()) loop.set_description(l_str) # create final results, the smoothing can be used to create consistent demo videos # Note that we do not use the smoothing for evaluation in our paper smooth_pose = gaussian_smoothing(smpl_init.pose_body, window_size=3, sigma=2) idx = [0, -1] smooth_pose[idx] = smpl_init.pose_body[idx] smpl_init = self.body_model(betas=self.betas, pose_body=smooth_pose) if vis: self.visualize(smpl_init.v, smpl_init.f, self.out_path, render=True, prefix='out', device=self.device) seq_to_video(os.path.join(self.out_path, 'renders'), os.path.join(self.out_path, 'merges'), video_path=os.path.join(self.out_path, 'motion.mp4')) joint_error = smpl_init.Jtr[:, :22] - smpl_gt.Jtr[:, :22] vert_error = smpl_init.v - smpl_gt.v MPJPE = torch.mean(torch.sqrt(torch.sum(joint_error * joint_error, dim=2)), dim=1) * 100. # remain batch dim MPVPE = torch.mean(torch.sqrt(torch.sum(vert_error * vert_error, dim=2)), dim=1) * 100. if verbose: print('after denoising:{:0.8f} cm'.format(MPJPE.mean())) results_dict = {'init_MPJPE': init_MPJPE.detach().cpu().numpy(), 'MPJPE': MPJPE.detach().cpu().numpy(), 'MPVPE': MPVPE.detach().cpu().numpy()} return results_dict def denoise(config, args, model, gt_file, out_path, std=0.04, verbose=False): motion_data_gt = np.load(gt_file)['pose_body'] batch_size = len(motion_data_gt) gt_poses = torch.from_numpy(motion_data_gt.astype(np.float32)).to(args.device) # [batchsize, 63] # load body model body_model = BodyModel(bm_path=args.bodymodel_path, model_type='smplx', batch_size=batch_size, num_betas=10).to( args.device) # generate noise on joints std = std joints3d = body_model(pose_body=gt_poses).Jtr[:, :22] noisy_joints3d = joints3d + std * torch.randn(*joints3d.shape, device=joints3d.device) if args.time_strategy in ['1']: sde_N = 500 dposer_weight = 1e-1 else: sde_N = 500 dposer_weight = 1.0 # If you try to reduce 'sample_trun' or 'sample_time', reduce weight too for converge. # create Motion denoiser layer motion_denoiser = MotionDenoise(config, args, model, sde_N=sde_N, body_model=body_model, dposer_weight=dposer_weight, # For axis setting 1e-1, batch_size=batch_size, out_path=out_path) if std == 0.02: kwargs = {'iterations': 3, 'steps_per_iter': 40, 'sample_trun': 10.0, 'sample_time': 495} elif std == 0.04: kwargs = {'iterations': 3, 'steps_per_iter': 60, 'sample_trun': 4.0, 'sample_time': 490} elif std == 0.1: kwargs = {'iterations': 3, 'steps_per_iter': 80, 'sample_trun': 3.0, 'sample_time': 480} else: raise NotImplementedError() if args.file_path is not None: # visualization for toy data verbose = True kwargs['vis'] = True batch_results = motion_denoiser.optimize(noisy_joints3d, gt_poses, args.time_strategy, verbose=verbose, **kwargs) return batch_results def main(args): def find_npz_files(data_dir): npz_files = [] for root, dirs, files in os.walk(data_dir): for file in files: if file.endswith('.npz'): npz_files.append(os.path.relpath(os.path.join(root, file), data_dir)) return npz_files torch.manual_seed(42) config = FLAGS.config POSE_DIM = 3 if config.data.rot_rep == 'axis' else 6 model = ScoreModelFC( config,
n_poses=N_POSES,
14
2023-11-29 15:55:50+00:00
16k
KylinYee/R2-Talker-code
main.py
[ { "identifier": "NeRFDataset", "path": "nerf/provider.py", "snippet": "class NeRFDataset:\n def __init__(self, opt, device, type='train', downscale=1):\n super().__init__()\n \n self.opt = opt\n self.device = device\n self.type = type # train, val, test\n sel...
import torch import argparse from nerf.provider import NeRFDataset from nerf.gui import NeRFGUI from nerf.utils import * from nerf.network import NeRFNetwork, R2TalkerNeRF, GeneNeRFNetwork
12,896
parser.add_argument('--W', type=int, default=450, help="GUI width") parser.add_argument('--H', type=int, default=450, help="GUI height") parser.add_argument('--radius', type=float, default=3.35, help="default GUI camera radius from center") parser.add_argument('--fovy', type=float, default=21.24, help="default GUI camera fovy") parser.add_argument('--max_spp', type=int, default=1, help="GUI rendering max sample per pixel") ### else parser.add_argument('--att', type=int, default=2, help="audio attention mode (0 = turn off, 1 = left-direction, 2 = bi-direction)") parser.add_argument('--aud', type=str, default='', help="audio source (empty will load the default, else should be a path to a npy file)") parser.add_argument('--cond_type', type=str, default=None, help="type of driving condition: eo, ds, idexp") parser.add_argument('--method', type=str, default='r2talker', help="r2talker, genefaceDagger, rad-nerf") parser.add_argument('--emb', action='store_true', help="use audio class + embedding instead of logits") parser.add_argument('--ind_dim', type=int, default=4, help="individual code dim, 0 to turn off") parser.add_argument('--ind_num', type=int, default=10000, help="number of individual codes, should be larger than training dataset size") parser.add_argument('--ind_dim_torso', type=int, default=8, help="individual code dim, 0 to turn off") parser.add_argument('--amb_dim', type=int, default=2, help="ambient dimension") parser.add_argument('--part', action='store_true', help="use partial training data (1/10)") parser.add_argument('--part2', action='store_true', help="use partial training data (first 15s)") parser.add_argument('--train_camera', action='store_true', help="optimize camera pose") parser.add_argument('--smooth_path', action='store_true', help="brute-force smooth camera pose trajectory with a window size") parser.add_argument('--smooth_path_window', type=int, default=7, help="smoothing window size") # asr parser.add_argument('--asr', action='store_true', help="load asr for real-time app") parser.add_argument('--asr_wav', type=str, default='', help="load the wav and use as input") parser.add_argument('--asr_play', action='store_true', help="play out the audio") parser.add_argument('--asr_model', type=str, default='cpierse/wav2vec2-large-xlsr-53-esperanto') # parser.add_argument('--asr_model', type=str, default='facebook/wav2vec2-large-960h-lv60-self') parser.add_argument('--asr_save_feats', action='store_true') # audio FPS parser.add_argument('--fps', type=int, default=50) # sliding window left-middle-right length (unit: 20ms) parser.add_argument('-l', type=int, default=10) parser.add_argument('-m', type=int, default=50) parser.add_argument('-r', type=int, default=10) opt = parser.parse_args() if opt.method == 'r2talker': opt.cond_type = 'idexp' elif opt.method == 'genefaceDagger': opt.cond_type = 'idexp' elif opt.method == 'rad-nerf': opt.cond_type = 'eo' if opt.O: opt.fp16 = True opt.exp_eye = True if opt.test: opt.smooth_path = True opt.smooth_eye = True opt.smooth_lips = True opt.cuda_ray = True # assert opt.cuda_ray, "Only support CUDA ray mode." if opt.patch_size > 1: # assert opt.patch_size > 16, "patch_size should > 16 to run LPIPS loss." assert opt.num_rays % (opt.patch_size ** 2) == 0, "patch_size ** 2 should be dividable by num_rays." if opt.finetune_lips: # do not update density grid in finetune stage opt.update_extra_interval = 1e9 print(opt) seed_everything(opt.seed) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if opt.method == 'r2talker': model = R2TalkerNeRF(opt) elif opt.method == 'genefaceDagger': model = GeneNeRFNetwork(opt) elif opt.method == 'rad-nerf': model = NeRFNetwork(opt) # manually load state dict for head if opt.torso and opt.head_ckpt != '': model_dict = torch.load(opt.head_ckpt, map_location='cpu')['model'] missing_keys, unexpected_keys = model.load_state_dict(model_dict, strict=False) if len(missing_keys) > 0: print(f"[WARN] missing keys: {missing_keys}") if len(unexpected_keys) > 0: print(f"[WARN] unexpected keys: {unexpected_keys}") # freeze these keys for k, v in model.named_parameters(): if k in model_dict: # print(f'[INFO] freeze {k}, {v.shape}') v.requires_grad = False # print(model) criterion = torch.nn.MSELoss(reduction='none') if opt.test: if opt.gui: metrics = [] # use no metric in GUI for faster initialization... else: # metrics = [PSNRMeter(), LPIPSMeter(device=device)] metrics = [PSNRMeter(), LPIPSMeter(device=device), LMDMeter(backend='fan')] trainer = Trainer('ngp', opt, model, device=device, workspace=opt.workspace, criterion=criterion, fp16=opt.fp16, metrics=metrics, use_checkpoint=opt.ckpt) if opt.test_train:
# torch.autograd.set_detect_anomaly(True) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('path', type=str) parser.add_argument('-O', action='store_true', help="equals --fp16 --cuda_ray --exp_eye") parser.add_argument('--test', action='store_true', help="test mode (load model and test dataset)") parser.add_argument('--test_train', action='store_true', help="test mode (load model and train dataset)") parser.add_argument('--data_range', type=int, nargs='*', default=[0, -1], help="data range to use") parser.add_argument('--workspace', type=str, default='workspace') parser.add_argument('--seed', type=int, default=0) ### training options parser.add_argument('--iters', type=int, default=200000, help="training iters") parser.add_argument('--lr', type=float, default=5e-3, help="initial learning rate") parser.add_argument('--lr_net', type=float, default=5e-4, help="initial learning rate") parser.add_argument('--ckpt', type=str, default='latest') parser.add_argument('--num_rays', type=int, default=4096 * 16, help="num rays sampled per image for each training step") parser.add_argument('--cuda_ray', action='store_true', help="use CUDA raymarching instead of pytorch") parser.add_argument('--max_steps', type=int, default=16, help="max num steps sampled per ray (only valid when using --cuda_ray)") parser.add_argument('--num_steps', type=int, default=16, help="num steps sampled per ray (only valid when NOT using --cuda_ray)") parser.add_argument('--upsample_steps', type=int, default=0, help="num steps up-sampled per ray (only valid when NOT using --cuda_ray)") parser.add_argument('--update_extra_interval', type=int, default=16, help="iter interval to update extra status (only valid when using --cuda_ray)") parser.add_argument('--max_ray_batch', type=int, default=4096, help="batch size of rays at inference to avoid OOM (only valid when NOT using --cuda_ray)") ### network backbone options parser.add_argument('--fp16', action='store_true', help="use amp mixed precision training") parser.add_argument('--lambda_amb', type=float, default=0.1, help="lambda for ambient loss") parser.add_argument('--bg_img', type=str, default='', help="background image") parser.add_argument('--fbg', action='store_true', help="frame-wise bg") parser.add_argument('--exp_eye', action='store_true', help="explicitly control the eyes") parser.add_argument('--fix_eye', type=float, default=-1, help="fixed eye area, negative to disable, set to 0-0.3 for a reasonable eye") parser.add_argument('--smooth_eye', action='store_true', help="smooth the eye area sequence") parser.add_argument('--torso_shrink', type=float, default=0.8, help="shrink bg coords to allow more flexibility in deform") ### dataset options parser.add_argument('--color_space', type=str, default='srgb', help="Color space, supports (linear, srgb)") parser.add_argument('--preload', type=int, default=0, help="0 means load data from disk on-the-fly, 1 means preload to CPU, 2 means GPU.") # (the default value is for the fox dataset) parser.add_argument('--bound', type=float, default=1, help="assume the scene is bounded in box[-bound, bound]^3, if > 1, will invoke adaptive ray marching.") parser.add_argument('--scale', type=float, default=4, help="scale camera location into box[-bound, bound]^3") parser.add_argument('--offset', type=float, nargs='*', default=[0, 0, 0], help="offset of camera location") parser.add_argument('--dt_gamma', type=float, default=1/256, help="dt_gamma (>=0) for adaptive ray marching. set to 0 to disable, >0 to accelerate rendering (but usually with worse quality)") parser.add_argument('--min_near', type=float, default=0.05, help="minimum near distance for camera") parser.add_argument('--density_thresh', type=float, default=10, help="threshold for density grid to be occupied (sigma)") parser.add_argument('--density_thresh_torso', type=float, default=0.01, help="threshold for density grid to be occupied (alpha)") parser.add_argument('--patch_size', type=int, default=1, help="[experimental] render patches in training, so as to apply LPIPS loss. 1 means disabled, use [64, 32, 16] to enable") parser.add_argument('--finetune_lips', action='store_true', help="use LPIPS and landmarks to fine tune lips region") parser.add_argument('--smooth_lips', action='store_true', help="smooth the enc_a in a exponential decay way...") parser.add_argument('--torso', action='store_true', help="fix head and train torso") parser.add_argument('--head_ckpt', type=str, default='', help="head model") ### GUI options parser.add_argument('--gui', action='store_true', help="start a GUI") parser.add_argument('--W', type=int, default=450, help="GUI width") parser.add_argument('--H', type=int, default=450, help="GUI height") parser.add_argument('--radius', type=float, default=3.35, help="default GUI camera radius from center") parser.add_argument('--fovy', type=float, default=21.24, help="default GUI camera fovy") parser.add_argument('--max_spp', type=int, default=1, help="GUI rendering max sample per pixel") ### else parser.add_argument('--att', type=int, default=2, help="audio attention mode (0 = turn off, 1 = left-direction, 2 = bi-direction)") parser.add_argument('--aud', type=str, default='', help="audio source (empty will load the default, else should be a path to a npy file)") parser.add_argument('--cond_type', type=str, default=None, help="type of driving condition: eo, ds, idexp") parser.add_argument('--method', type=str, default='r2talker', help="r2talker, genefaceDagger, rad-nerf") parser.add_argument('--emb', action='store_true', help="use audio class + embedding instead of logits") parser.add_argument('--ind_dim', type=int, default=4, help="individual code dim, 0 to turn off") parser.add_argument('--ind_num', type=int, default=10000, help="number of individual codes, should be larger than training dataset size") parser.add_argument('--ind_dim_torso', type=int, default=8, help="individual code dim, 0 to turn off") parser.add_argument('--amb_dim', type=int, default=2, help="ambient dimension") parser.add_argument('--part', action='store_true', help="use partial training data (1/10)") parser.add_argument('--part2', action='store_true', help="use partial training data (first 15s)") parser.add_argument('--train_camera', action='store_true', help="optimize camera pose") parser.add_argument('--smooth_path', action='store_true', help="brute-force smooth camera pose trajectory with a window size") parser.add_argument('--smooth_path_window', type=int, default=7, help="smoothing window size") # asr parser.add_argument('--asr', action='store_true', help="load asr for real-time app") parser.add_argument('--asr_wav', type=str, default='', help="load the wav and use as input") parser.add_argument('--asr_play', action='store_true', help="play out the audio") parser.add_argument('--asr_model', type=str, default='cpierse/wav2vec2-large-xlsr-53-esperanto') # parser.add_argument('--asr_model', type=str, default='facebook/wav2vec2-large-960h-lv60-self') parser.add_argument('--asr_save_feats', action='store_true') # audio FPS parser.add_argument('--fps', type=int, default=50) # sliding window left-middle-right length (unit: 20ms) parser.add_argument('-l', type=int, default=10) parser.add_argument('-m', type=int, default=50) parser.add_argument('-r', type=int, default=10) opt = parser.parse_args() if opt.method == 'r2talker': opt.cond_type = 'idexp' elif opt.method == 'genefaceDagger': opt.cond_type = 'idexp' elif opt.method == 'rad-nerf': opt.cond_type = 'eo' if opt.O: opt.fp16 = True opt.exp_eye = True if opt.test: opt.smooth_path = True opt.smooth_eye = True opt.smooth_lips = True opt.cuda_ray = True # assert opt.cuda_ray, "Only support CUDA ray mode." if opt.patch_size > 1: # assert opt.patch_size > 16, "patch_size should > 16 to run LPIPS loss." assert opt.num_rays % (opt.patch_size ** 2) == 0, "patch_size ** 2 should be dividable by num_rays." if opt.finetune_lips: # do not update density grid in finetune stage opt.update_extra_interval = 1e9 print(opt) seed_everything(opt.seed) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if opt.method == 'r2talker': model = R2TalkerNeRF(opt) elif opt.method == 'genefaceDagger': model = GeneNeRFNetwork(opt) elif opt.method == 'rad-nerf': model = NeRFNetwork(opt) # manually load state dict for head if opt.torso and opt.head_ckpt != '': model_dict = torch.load(opt.head_ckpt, map_location='cpu')['model'] missing_keys, unexpected_keys = model.load_state_dict(model_dict, strict=False) if len(missing_keys) > 0: print(f"[WARN] missing keys: {missing_keys}") if len(unexpected_keys) > 0: print(f"[WARN] unexpected keys: {unexpected_keys}") # freeze these keys for k, v in model.named_parameters(): if k in model_dict: # print(f'[INFO] freeze {k}, {v.shape}') v.requires_grad = False # print(model) criterion = torch.nn.MSELoss(reduction='none') if opt.test: if opt.gui: metrics = [] # use no metric in GUI for faster initialization... else: # metrics = [PSNRMeter(), LPIPSMeter(device=device)] metrics = [PSNRMeter(), LPIPSMeter(device=device), LMDMeter(backend='fan')] trainer = Trainer('ngp', opt, model, device=device, workspace=opt.workspace, criterion=criterion, fp16=opt.fp16, metrics=metrics, use_checkpoint=opt.ckpt) if opt.test_train:
test_set = NeRFDataset(opt, device=device, type='train')
0
2023-12-04 12:51:59+00:00
16k
ubc-vision/vivid123
vivid123/generation_utils.py
[ { "identifier": "CLIPCameraProjection", "path": "vivid123/models/clip_camera_projection.py", "snippet": "class CLIPCameraProjection(ModelMixin, ConfigMixin):\n \"\"\"\n A Projection layer for CLIP embedding and camera embedding.\n Parameters:\n embedding_dim (`int`, *optional*, defaults ...
import os import yaml import re import torch import numpy as np import imageio.v3 as imageio from typing import List, Any from yaml.parser import ParserError from PIL import Image from diffusers.pipelines import DiffusionPipeline from diffusers.models import UNet2DConditionModel, AutoencoderKL from diffusers.schedulers import DPMSolverMultistepScheduler, EulerDiscreteScheduler from diffusers.pipelines import DiffusionPipeline from transformers import CLIPVisionModelWithProjection from .models import CLIPCameraProjection from .pipelines import ViVid123Pipeline from .configs import ViVid123BaseSchema
10,899
video_end_step_percentage: float = 1.0, zero123_linear_start_weight: float = 1.0, zero123_linear_end_weight: float = 1.0, zero123_start_step_percentage: float = 0.0, zero123_end_step_percentage: float = 1.0, ): """ Prepare the fusion schedule of video diffusion and zero123 at all the denoising steps Args: video_linear_start_weight (`float`, *optional*, defaults to 1.0): The weight of the video diffusion at the start of the video. The weight is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` during the video diffusion. video_linear_end_weight (`float`, *optional*, defaults to 0.5): The weight of the video diffusion at the end of the video. The weight is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` during the video diffusion. video_start_step_percentage (`float`, *optional*, defaults to 0.0): The percentage of the total number of inference steps at which the video diffusion starts. The video diffusion is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` between `video_start_step_percentage` and `video_end_step_percentage`. video_end_step_percentage (`float`, *optional*, defaults to 1.0): The percentage of the total number of inference steps at which the video diffusion ends. The video diffusion is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` between `video_start_step_percentage` and `video_end_step_percentage`. zero123_linear_start_weight (`float`, *optional*, defaults to 1.0): The weight of the zero123 diffusion at the start of the video. The weight is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` during the zero123 diffusion. zero123_linear_end_weight (`float`, *optional*, defaults to 1.0): The weight of the zero123 diffusion at the end of the video. The weight is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` during the zero123 diffusion. zero123_start_step_percentage (`float`, *optional*, defaults to 0.0): The percentage of the total number of inference steps at which the zero123 diffusion starts. The zero123 diffusion is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` between `zero123_start_step_percentage` and `zero123_end_step_percentage`. zero123_end_step_percentage (`float`, *optional*, defaults to 1.0): The percentage of the total number of inference steps at which the zero123 diffusion ends. The zero123 diffusion is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` between `zero123_start_step_percentage` and `zero123_end_step_percentage`. Return: A tuple of two tensors, video_schedule (`torch.Tensor`): The schedule of the video diffusion weighting, with shape `[num_inference_steps]`. zero123_schedule (`torch.Tensor`): The schedule of the zero123 diffusion weighting, with shape `[num_inference_steps]`. """ assert ( video_linear_start_weight >= 0.0 and video_linear_start_weight <= 1.0 ), "video_linear_start_weight must be between 0.0 and 1.0" assert ( video_linear_end_weight >= 0.0 and video_linear_end_weight <= 1.0 ), "video_linear_end_weight must be between 0.0 and 1.0" assert ( video_start_step_percentage >= 0.0 and video_start_step_percentage <= 1.0 ), "video_start_step_percentage must be between 0.0 and 1.0" assert ( video_end_step_percentage >= 0.0 and video_end_step_percentage <= 1.0 ), "video_end_step_percentage must be between 0.0 and 1.0" assert ( zero123_linear_start_weight >= 0.0 and zero123_linear_start_weight <= 1.0 ), "zero123_linear_start_weight must be between 0.0 and 1.0" assert ( zero123_linear_end_weight >= 0.0 and zero123_linear_end_weight <= 1.0 ), "zero123_linear_end_weight must be between 0.0 and 1.0" assert ( zero123_start_step_percentage >= 0.0 and zero123_start_step_percentage <= 1.0 ), "zero123_start_step_percentage must be between 0.0 and 1.0" assert ( zero123_end_step_percentage >= 0.0 and zero123_end_step_percentage <= 1.0 ), "zero123_end_step_percentage must be between 0.0 and 1.0" video_schedule = torch.linspace( start=video_linear_start_weight, end=video_linear_end_weight, steps=int((video_end_step_percentage - video_start_step_percentage) * num_inference_steps), ) zero123_schedule = torch.linspace( start=zero123_linear_start_weight, end=zero123_linear_end_weight, steps=int((zero123_end_step_percentage - zero123_start_step_percentage) * num_inference_steps), ) if video_schedule.shape[0] < num_inference_steps: video_schedule = torch.cat( [ video_linear_start_weight * torch.ones([video_start_step_percentage * num_inference_steps]), video_schedule, video_linear_end_weight * torch.ones([num_inference_steps - video_end_step_percentage * num_inference_steps]), ] ) if zero123_schedule.shape[0] < num_inference_steps: zero123_schedule = torch.cat( [ zero123_linear_start_weight * torch.ones([zero123_start_step_percentage * num_inference_steps]), zero123_schedule, zero123_linear_end_weight * torch.ones([num_inference_steps - zero123_end_step_percentage * num_inference_steps]), ] ) return (video_schedule, zero123_schedule) def save_videos_grid_zeroscope_nplist(video_frames: List[np.ndarray], path: str, n_rows=6, fps=8, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]): # fourcc = cv2.VideoWriter_fourcc(*"mp4v") f = len(video_frames) h, w, c = video_frames[0].shape #images = [(image).astype("uint8") for image in video_frames] os.makedirs(os.path.dirname(path), exist_ok=True) imageio.imwrite(path, video_frames, fps=fps) def prepare_pipelines( ZERO123_MODEL_ID: str = "bennyguo/zero123-xl-diffusers", VIDEO_MODEL_ID: str = "cerspense/zeroscope_v2_576w", VIDEO_XL_MODEL_ID: str = "cerspense/zeroscope_v2_XL" ): zero123_unet = UNet2DConditionModel.from_pretrained(ZERO123_MODEL_ID, subfolder="unet") zero123_cam_proj = CLIPCameraProjection.from_pretrained(ZERO123_MODEL_ID, subfolder="clip_camera_projection") zero123_img_enc = CLIPVisionModelWithProjection.from_pretrained(ZERO123_MODEL_ID, subfolder="image_encoder")
def prepare_cam_pose_input( num_frames: int = 25, delta_elevation_start: float = 0.0, delta_elevation_end: float = 0.0, delta_azimuth_start: float = -45.0, delta_azimuth_end: float = 45.0, delta_radius_start: float = 0.0, delta_radius_end: float = 0.0, ): r""" The function to prepare the input to the vivid123 pipeline Args: delta_elevation_start (`float`, *optional*, defaults to 0.0): The starting relative elevation angle of the camera, in degree. Relative to the elevation of the reference image. The camera is facing towards the origin. delta_elevation_end (`float`, *optional*, defaults to 0.0): The ending relative elevation angle of the camera, in degree. Relative to the elevation of the reference image. The camera is facing towards the origin. delta_azimuth_start (`float`, *optional*, defaults to -45.0): The starting relative azimuth angle of the camera, in degree. Relative to the elevation of the reference image. The camera is facing towards the origin. delta_azimuth_end (`float`, *optional*, defaults to 45.0): The ending relative azimuth angle of the camera, in degree. Relative to the elevation of the reference image. The camera is facing towards the origin. Returns: """ cam_elevation = np.radians(np.linspace(delta_elevation_start, delta_elevation_end, num_frames))[..., None] cam_azimuth = np.radians(np.linspace(delta_azimuth_start, delta_azimuth_end, num_frames)) cam_azimuth_sin_cos = np.stack([np.sin(cam_azimuth), np.cos(cam_azimuth)], axis=-1) cam_radius = np.linspace(delta_radius_start, delta_radius_end, num_frames)[..., None] cam_pose_np = np.concatenate([cam_elevation, cam_azimuth_sin_cos, cam_radius], axis=-1) cam_pose_torch = torch.from_numpy(cam_pose_np) return cam_pose_torch # refer to https://stackoverflow.com/a/33507138/6257375 def conver_rgba_to_rgb_white_bg( image: Image, H: int = 256, W: int = 256, ): input_image = image.convert("RGBA").resize((H, W), Image.BICUBIC) background = Image.new("RGBA", input_image.size, (255, 255, 255)) alpha_composite = Image.alpha_composite(background, input_image) return alpha_composite def prepare_fusion_schedule_linear( num_inference_steps: int = 50, video_linear_start_weight: float = 1.0, video_linear_end_weight: float = 0.5, video_start_step_percentage: float = 0.0, video_end_step_percentage: float = 1.0, zero123_linear_start_weight: float = 1.0, zero123_linear_end_weight: float = 1.0, zero123_start_step_percentage: float = 0.0, zero123_end_step_percentage: float = 1.0, ): """ Prepare the fusion schedule of video diffusion and zero123 at all the denoising steps Args: video_linear_start_weight (`float`, *optional*, defaults to 1.0): The weight of the video diffusion at the start of the video. The weight is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` during the video diffusion. video_linear_end_weight (`float`, *optional*, defaults to 0.5): The weight of the video diffusion at the end of the video. The weight is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` during the video diffusion. video_start_step_percentage (`float`, *optional*, defaults to 0.0): The percentage of the total number of inference steps at which the video diffusion starts. The video diffusion is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` between `video_start_step_percentage` and `video_end_step_percentage`. video_end_step_percentage (`float`, *optional*, defaults to 1.0): The percentage of the total number of inference steps at which the video diffusion ends. The video diffusion is linearly increased from `video_linear_start_weight` to `video_linear_end_weight` between `video_start_step_percentage` and `video_end_step_percentage`. zero123_linear_start_weight (`float`, *optional*, defaults to 1.0): The weight of the zero123 diffusion at the start of the video. The weight is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` during the zero123 diffusion. zero123_linear_end_weight (`float`, *optional*, defaults to 1.0): The weight of the zero123 diffusion at the end of the video. The weight is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` during the zero123 diffusion. zero123_start_step_percentage (`float`, *optional*, defaults to 0.0): The percentage of the total number of inference steps at which the zero123 diffusion starts. The zero123 diffusion is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` between `zero123_start_step_percentage` and `zero123_end_step_percentage`. zero123_end_step_percentage (`float`, *optional*, defaults to 1.0): The percentage of the total number of inference steps at which the zero123 diffusion ends. The zero123 diffusion is linearly increased from `zero123_linear_start_weight` to `zero123_linear_end_weight` between `zero123_start_step_percentage` and `zero123_end_step_percentage`. Return: A tuple of two tensors, video_schedule (`torch.Tensor`): The schedule of the video diffusion weighting, with shape `[num_inference_steps]`. zero123_schedule (`torch.Tensor`): The schedule of the zero123 diffusion weighting, with shape `[num_inference_steps]`. """ assert ( video_linear_start_weight >= 0.0 and video_linear_start_weight <= 1.0 ), "video_linear_start_weight must be between 0.0 and 1.0" assert ( video_linear_end_weight >= 0.0 and video_linear_end_weight <= 1.0 ), "video_linear_end_weight must be between 0.0 and 1.0" assert ( video_start_step_percentage >= 0.0 and video_start_step_percentage <= 1.0 ), "video_start_step_percentage must be between 0.0 and 1.0" assert ( video_end_step_percentage >= 0.0 and video_end_step_percentage <= 1.0 ), "video_end_step_percentage must be between 0.0 and 1.0" assert ( zero123_linear_start_weight >= 0.0 and zero123_linear_start_weight <= 1.0 ), "zero123_linear_start_weight must be between 0.0 and 1.0" assert ( zero123_linear_end_weight >= 0.0 and zero123_linear_end_weight <= 1.0 ), "zero123_linear_end_weight must be between 0.0 and 1.0" assert ( zero123_start_step_percentage >= 0.0 and zero123_start_step_percentage <= 1.0 ), "zero123_start_step_percentage must be between 0.0 and 1.0" assert ( zero123_end_step_percentage >= 0.0 and zero123_end_step_percentage <= 1.0 ), "zero123_end_step_percentage must be between 0.0 and 1.0" video_schedule = torch.linspace( start=video_linear_start_weight, end=video_linear_end_weight, steps=int((video_end_step_percentage - video_start_step_percentage) * num_inference_steps), ) zero123_schedule = torch.linspace( start=zero123_linear_start_weight, end=zero123_linear_end_weight, steps=int((zero123_end_step_percentage - zero123_start_step_percentage) * num_inference_steps), ) if video_schedule.shape[0] < num_inference_steps: video_schedule = torch.cat( [ video_linear_start_weight * torch.ones([video_start_step_percentage * num_inference_steps]), video_schedule, video_linear_end_weight * torch.ones([num_inference_steps - video_end_step_percentage * num_inference_steps]), ] ) if zero123_schedule.shape[0] < num_inference_steps: zero123_schedule = torch.cat( [ zero123_linear_start_weight * torch.ones([zero123_start_step_percentage * num_inference_steps]), zero123_schedule, zero123_linear_end_weight * torch.ones([num_inference_steps - zero123_end_step_percentage * num_inference_steps]), ] ) return (video_schedule, zero123_schedule) def save_videos_grid_zeroscope_nplist(video_frames: List[np.ndarray], path: str, n_rows=6, fps=8, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]): # fourcc = cv2.VideoWriter_fourcc(*"mp4v") f = len(video_frames) h, w, c = video_frames[0].shape #images = [(image).astype("uint8") for image in video_frames] os.makedirs(os.path.dirname(path), exist_ok=True) imageio.imwrite(path, video_frames, fps=fps) def prepare_pipelines( ZERO123_MODEL_ID: str = "bennyguo/zero123-xl-diffusers", VIDEO_MODEL_ID: str = "cerspense/zeroscope_v2_576w", VIDEO_XL_MODEL_ID: str = "cerspense/zeroscope_v2_XL" ): zero123_unet = UNet2DConditionModel.from_pretrained(ZERO123_MODEL_ID, subfolder="unet") zero123_cam_proj = CLIPCameraProjection.from_pretrained(ZERO123_MODEL_ID, subfolder="clip_camera_projection") zero123_img_enc = CLIPVisionModelWithProjection.from_pretrained(ZERO123_MODEL_ID, subfolder="image_encoder")
vivid123_pipe = ViVid123Pipeline.from_pretrained(
1
2023-11-27 22:48:17+00:00
16k
TISUnion/PrimeBackup
prime_backup/mcdr/task/backup/restore_backup_task.py
[ { "identifier": "CreateBackupAction", "path": "prime_backup/action/create_backup_action.py", "snippet": "class CreateBackupAction(CreateBackupActionBase):\n\tdef __init__(self, creator: Operator, comment: str, *, tags: Optional[BackupTags] = None, expire_timestamp_ns: Optional[int] = None):\n\t\tsuper()...
from typing import Optional from mcdreforged.api.all import * from prime_backup.action.create_backup_action import CreateBackupAction from prime_backup.action.export_backup_action import ExportBackupToDirectoryAction from prime_backup.action.get_backup_action import GetBackupAction from prime_backup.action.list_backup_action import ListBackupAction from prime_backup.mcdr.task.basic_task import HeavyTask from prime_backup.mcdr.text_components import TextComponents from prime_backup.types.backup_filter import BackupFilter from prime_backup.types.backup_info import BackupInfo from prime_backup.types.backup_tags import BackupTags, BackupTagName from prime_backup.types.operator import Operator, PrimeBackupOperatorNames from prime_backup.utils import backup_utils, log_utils from prime_backup.utils.mcdr_utils import click_and_run, mkcmd from prime_backup.utils.timer import Timer
12,221
class RestoreBackupTask(HeavyTask[None]): def __init__(self, source: CommandSource, backup_id: Optional[int] = None, needs_confirm: bool = True, fail_soft: bool = False, verify_blob: bool = True): super().__init__(source) self.backup_id = backup_id self.needs_confirm = needs_confirm self.fail_soft = fail_soft self.verify_blob = verify_blob self.__can_abort = False @property def id(self) -> str: return 'backup_restore' def is_abort_able(self) -> bool: return super().is_abort_able() or self.__can_abort def get_abort_permission(self) -> int: return 0 def __countdown_and_stop_server(self, backup: BackupInfo) -> bool: for countdown in range(max(0, self.config.command.restore_countdown_sec), 0, -1): self.broadcast(click_and_run( RText('!!! ', RColor.red) + self.tr('countdown', countdown, TextComponents.backup_brief(backup, backup_id_fancy=False)), self.tr('countdown.hover', TextComponents.command('abort')), mkcmd('abort'), )) if self.aborted_event.wait(1): self.broadcast(self.get_aborted_text()) return False self.server.stop() self.logger.info('Wait for server to stop') self.server.wait_until_stop() return True def run(self): if self.backup_id is None: backup_filter = BackupFilter() backup_filter.filter_non_pre_restore_backup() candidates = ListBackupAction(backup_filter=backup_filter, limit=1).run() if len(candidates) == 0: self.reply_tr('no_backup') return backup = candidates[0] else: backup = GetBackupAction(self.backup_id).run() self.__can_abort = True self.broadcast(self.tr('show_backup', TextComponents.backup_brief(backup))) if self.needs_confirm: if not self.wait_confirm(self.tr('confirm_target')): return server_was_running = self.server.is_server_running() if server_was_running: if not self.__countdown_and_stop_server(backup): return else: self.logger.info('Found an already-stopped server') self.__can_abort = False
class RestoreBackupTask(HeavyTask[None]): def __init__(self, source: CommandSource, backup_id: Optional[int] = None, needs_confirm: bool = True, fail_soft: bool = False, verify_blob: bool = True): super().__init__(source) self.backup_id = backup_id self.needs_confirm = needs_confirm self.fail_soft = fail_soft self.verify_blob = verify_blob self.__can_abort = False @property def id(self) -> str: return 'backup_restore' def is_abort_able(self) -> bool: return super().is_abort_able() or self.__can_abort def get_abort_permission(self) -> int: return 0 def __countdown_and_stop_server(self, backup: BackupInfo) -> bool: for countdown in range(max(0, self.config.command.restore_countdown_sec), 0, -1): self.broadcast(click_and_run( RText('!!! ', RColor.red) + self.tr('countdown', countdown, TextComponents.backup_brief(backup, backup_id_fancy=False)), self.tr('countdown.hover', TextComponents.command('abort')), mkcmd('abort'), )) if self.aborted_event.wait(1): self.broadcast(self.get_aborted_text()) return False self.server.stop() self.logger.info('Wait for server to stop') self.server.wait_until_stop() return True def run(self): if self.backup_id is None: backup_filter = BackupFilter() backup_filter.filter_non_pre_restore_backup() candidates = ListBackupAction(backup_filter=backup_filter, limit=1).run() if len(candidates) == 0: self.reply_tr('no_backup') return backup = candidates[0] else: backup = GetBackupAction(self.backup_id).run() self.__can_abort = True self.broadcast(self.tr('show_backup', TextComponents.backup_brief(backup))) if self.needs_confirm: if not self.wait_confirm(self.tr('confirm_target')): return server_was_running = self.server.is_server_running() if server_was_running: if not self.__countdown_and_stop_server(backup): return else: self.logger.info('Found an already-stopped server') self.__can_abort = False
timer = Timer()
16
2023-11-28 19:03:36+00:00
16k
metatube-community/metatube-plex-plugins
MetaTube.bundle/Contents/Libraries/Shared/urllib3/poolmanager.py
[ { "identifier": "HTTPHeaderDict", "path": "MetaTube.bundle/Contents/Libraries/Shared/urllib3/_collections.py", "snippet": "class HTTPHeaderDict(MutableMapping):\n \"\"\"\n :param headers:\n An iterable of field-value pairs. Must not contain multiple field names\n when compared case-i...
import collections import functools import logging from ._collections import HTTPHeaderDict, RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme from .exceptions import ( LocationValueError, MaxRetryError, ProxySchemeUnknown, ProxySchemeUnsupported, URLSchemeUnknown, ) from .packages import six from .packages.six.moves.urllib.parse import urljoin from .request import RequestMethods from .util.proxy import connection_requires_http_tunnel from .util.retry import Retry from .util.url import parse_url
14,158
if field not in context: context[field] = None return key_class(**context) #: A dictionary that maps a scheme to a callable that creates a pool key. #: This can be used to alter the way pool keys are constructed, if desired. #: Each PoolManager makes a copy of this dictionary so they can be configured #: globally here, or individually on the instance. key_fn_by_scheme = { "http": functools.partial(_default_key_normalizer, PoolKey), "https": functools.partial(_default_key_normalizer, PoolKey), } pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} class PoolManager(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param \\**connection_pool_kw: Additional parameters are used to create fresh :class:`urllib3.connectionpool.ConnectionPool` instances. Example:: >>> manager = PoolManager(num_pools=2) >>> r = manager.request('GET', 'http://google.com/') >>> r = manager.request('GET', 'http://google.com/mail') >>> r = manager.request('GET', 'http://yahoo.com/') >>> len(manager.pools) 2 """ proxy = None proxy_config = None def __init__(self, num_pools=10, headers=None, **connection_pool_kw): RequestMethods.__init__(self, headers) self.connection_pool_kw = connection_pool_kw self.pools = RecentlyUsedContainer(num_pools) # Locally set the pool classes and keys so other PoolManagers can # override them. self.pool_classes_by_scheme = pool_classes_by_scheme self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.clear() # Return False to re-raise any potential exceptions return False def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context["scheme"] = scheme or "http" if not port:
from __future__ import absolute_import __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"] log = logging.getLogger(__name__) SSL_KEYWORDS = ( "key_file", "cert_file", "cert_reqs", "ca_certs", "ssl_version", "ca_cert_dir", "ssl_context", "key_password", "server_hostname", ) # All known keyword arguments that could be provided to the pool manager, its # pools, or the underlying connections. This is used to construct a pool key. _key_fields = ( "key_scheme", # str "key_host", # str "key_port", # int "key_timeout", # int or float or Timeout "key_retries", # int or Retry "key_strict", # bool "key_block", # bool "key_source_address", # str "key_key_file", # str "key_key_password", # str "key_cert_file", # str "key_cert_reqs", # str "key_ca_certs", # str "key_ssl_version", # str "key_ca_cert_dir", # str "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext "key_maxsize", # int "key_headers", # dict "key__proxy", # parsed proxy url "key__proxy_headers", # dict "key__proxy_config", # class "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples "key__socks_options", # dict "key_assert_hostname", # bool or string "key_assert_fingerprint", # str "key_server_hostname", # str ) #: The namedtuple class used to construct keys for the connection pool. #: All custom key schemes should include the fields in this key at a minimum. PoolKey = collections.namedtuple("PoolKey", _key_fields) _proxy_config_fields = ("ssl_context", "use_forwarding_for_https") ProxyConfig = collections.namedtuple("ProxyConfig", _proxy_config_fields) def _default_key_normalizer(key_class, request_context): """ Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_scheme``. :param key_class: The class to use when constructing the key. This should be a namedtuple with the ``scheme`` and ``host`` keys at a minimum. :type key_class: namedtuple :param request_context: A dictionary-like object that contain the context for a request. :type request_context: dict :return: A namedtuple that can be used as a connection pool key. :rtype: PoolKey """ # Since we mutate the dictionary, make a copy first context = request_context.copy() context["scheme"] = context["scheme"].lower() context["host"] = context["host"].lower() # These are both dictionaries and need to be transformed into frozensets for key in ("headers", "_proxy_headers", "_socks_options"): if key in context and context[key] is not None: context[key] = frozenset(context[key].items()) # The socket_options key may be a list and needs to be transformed into a # tuple. socket_opts = context.get("socket_options") if socket_opts is not None: context["socket_options"] = tuple(socket_opts) # Map the kwargs to the names in the namedtuple - this is necessary since # namedtuples can't have fields starting with '_'. for key in list(context.keys()): context["key_" + key] = context.pop(key) # Default to ``None`` for keys missing from the context for field in key_class._fields: if field not in context: context[field] = None return key_class(**context) #: A dictionary that maps a scheme to a callable that creates a pool key. #: This can be used to alter the way pool keys are constructed, if desired. #: Each PoolManager makes a copy of this dictionary so they can be configured #: globally here, or individually on the instance. key_fn_by_scheme = { "http": functools.partial(_default_key_normalizer, PoolKey), "https": functools.partial(_default_key_normalizer, PoolKey), } pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool} class PoolManager(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param \\**connection_pool_kw: Additional parameters are used to create fresh :class:`urllib3.connectionpool.ConnectionPool` instances. Example:: >>> manager = PoolManager(num_pools=2) >>> r = manager.request('GET', 'http://google.com/') >>> r = manager.request('GET', 'http://google.com/mail') >>> r = manager.request('GET', 'http://yahoo.com/') >>> len(manager.pools) 2 """ proxy = None proxy_config = None def __init__(self, num_pools=10, headers=None, **connection_pool_kw): RequestMethods.__init__(self, headers) self.connection_pool_kw = connection_pool_kw self.pools = RecentlyUsedContainer(num_pools) # Locally set the pool classes and keys so other PoolManagers can # override them. self.pool_classes_by_scheme = pool_classes_by_scheme self.key_fn_by_scheme = key_fn_by_scheme.copy() def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.clear() # Return False to re-raise any potential exceptions return False def _new_pool(self, scheme, host, port, request_context=None): """ Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization. """ pool_cls = self.pool_classes_by_scheme[scheme] if request_context is None: request_context = self.connection_pool_kw.copy() # Although the context has everything necessary to create the pool, # this function has historically only used the scheme, host, and port # in the positional args. When an API change is acceptable these can # be removed. for key in ("scheme", "host", "port"): request_context.pop(key, None) if scheme == "http": for kw in SSL_KEYWORDS: request_context.pop(kw, None) return pool_cls(host, port, **request_context) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None): """ Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance's ``connection_pool_kw`` variable and used to create the new connection pool, if one is needed. """ if not host: raise LocationValueError("No host specified.") request_context = self._merge_pool_kwargs(pool_kwargs) request_context["scheme"] = scheme or "http" if not port:
port = port_by_scheme.get(request_context["scheme"].lower(), 80)
2
2023-11-27 07:01:39+00:00
16k
TACJu/MaXTron
MaXTron_Tube-Link/mmdet/datasets/coco_panoptic.py
[ { "identifier": "COCO", "path": "MaXTron_Tube-Link/mmdet/datasets/api_wrappers/coco_api.py", "snippet": "class COCO(_COCO):\n \"\"\"This class is almost the same as official pycocotools package.\n\n It implements some snake case function aliases. So that the COCO class has\n the same interface ...
import itertools import os import mmcv import numpy as np import panopticapi from collections import defaultdict from mmcv.utils import print_log from terminaltables import AsciiTable from mmdet.core import INSTANCE_OFFSET from .api_wrappers import COCO, pq_compute_multi_core from .builder import DATASETS from .coco import CocoDataset from panopticapi.evaluation import VOID from panopticapi.utils import id2rgb
11,507
pred_annotations = [] outdir = os.path.join(os.path.dirname(outfile_prefix), 'panoptic') for idx in range(len(self)): img_id = self.img_ids[idx] segm_file = self.data_infos[idx]['segm_file'] pan = results[idx] pan_labels = np.unique(pan) segm_info = [] for pan_label in pan_labels: sem_label = pan_label % INSTANCE_OFFSET # We reserve the length of self.CLASSES for VOID label if sem_label == len(self.CLASSES): continue # convert sem_label to json label cat_id = label2cat[sem_label] is_thing = self.categories[cat_id]['isthing'] mask = pan == pan_label area = mask.sum() segm_info.append({ 'id': int(pan_label), 'category_id': cat_id, 'isthing': is_thing, 'area': int(area) }) # evaluation script uses 0 for VOID label. pan[pan % INSTANCE_OFFSET == len(self.CLASSES)] = VOID pan = id2rgb(pan).astype(np.uint8) mmcv.imwrite(pan[:, :, ::-1], os.path.join(outdir, segm_file)) record = { 'image_id': img_id, 'segments_info': segm_info, 'file_name': segm_file } pred_annotations.append(record) pan_json_results = dict(annotations=pred_annotations) return pan_json_results def results2json(self, results, outfile_prefix): """Dump the results to a COCO style json file. There are 4 types of results: proposals, bbox predictions, mask predictions, panoptic segmentation predictions, and they have different data types. This method will automatically recognize the type, and dump them to json files. .. code-block:: none [ { 'pan_results': np.array, # shape (h, w) # ins_results which includes bboxes and RLE encoded masks # is optional. 'ins_results': (list[np.array], list[list[str]]) }, ... ] Args: results (list[dict]): Testing results of the dataset. outfile_prefix (str): The filename prefix of the json files. If the prefix is "somepath/xxx", the json files will be named "somepath/xxx.panoptic.json", "somepath/xxx.bbox.json", "somepath/xxx.segm.json" Returns: dict[str: str]: Possible keys are "panoptic", "bbox", "segm", \ "proposal", and values are corresponding filenames. """ result_files = dict() # panoptic segmentation results if 'pan_results' in results[0]: pan_results = [result['pan_results'] for result in results] pan_json_results = self._pan2json(pan_results, outfile_prefix) result_files['panoptic'] = f'{outfile_prefix}.panoptic.json' mmcv.dump(pan_json_results, result_files['panoptic']) # instance segmentation results if 'ins_results' in results[0]: ins_results = [result['ins_results'] for result in results] bbox_json_results, segm_json_results = self._segm2json(ins_results) result_files['bbox'] = f'{outfile_prefix}.bbox.json' result_files['proposal'] = f'{outfile_prefix}.bbox.json' result_files['segm'] = f'{outfile_prefix}.segm.json' mmcv.dump(bbox_json_results, result_files['bbox']) mmcv.dump(segm_json_results, result_files['segm']) return result_files def evaluate_pan_json(self, result_files, outfile_prefix, logger=None, classwise=False, nproc=32): """Evaluate PQ according to the panoptic results json file.""" imgs = self.coco.imgs gt_json = self.coco.img_ann_map # image to annotations gt_json = [{ 'image_id': k, 'segments_info': v, 'file_name': imgs[k]['segm_file'] } for k, v in gt_json.items()] pred_json = mmcv.load(result_files['panoptic']) pred_json = dict( (el['image_id'], el) for el in pred_json['annotations']) # match the gt_anns and pred_anns in the same image matched_annotations_list = [] for gt_ann in gt_json: img_id = gt_ann['image_id'] if img_id not in pred_json.keys(): raise Exception('no prediction for the image' ' with id: {}'.format(img_id)) matched_annotations_list.append((gt_ann, pred_json[img_id])) gt_folder = self.seg_prefix pred_folder = os.path.join(os.path.dirname(outfile_prefix), 'panoptic')
# Copyright (c) OpenMMLab. All rights reserved. # This file has been modified. try: except ImportError: panopticapi = None id2rgb = None VOID = None __all__ = ['CocoPanopticDataset'] class COCOPanoptic(COCO): """This wrapper is for loading the panoptic style annotation file. The format is shown in the CocoPanopticDataset class. Args: annotation_file (str): Path of annotation file. """ def __init__(self, annotation_file=None): if panopticapi is None: raise RuntimeError( 'panopticapi is not installed, please install it by: ' 'pip install git+https://github.com/cocodataset/' 'panopticapi.git.') super(COCOPanoptic, self).__init__(annotation_file) # load_ext for compatibility of nv pycocotools def createIndex(self, load_ext=False): assert not load_ext # create index print('creating index...') # anns stores 'segment_id -> annotation' anns, cats, imgs = {}, {}, {} img_to_anns, cat_to_imgs = defaultdict(list), defaultdict(list) if 'annotations' in self.dataset: for ann, img_info in zip(self.dataset['annotations'], self.dataset['images']): img_info['segm_file'] = ann['file_name'] for seg_ann in ann['segments_info']: # to match with instance.json seg_ann['image_id'] = ann['image_id'] seg_ann['height'] = img_info['height'] seg_ann['width'] = img_info['width'] img_to_anns[ann['image_id']].append(seg_ann) # segment_id is not unique in coco dataset orz... if seg_ann['id'] in anns.keys(): anns[seg_ann['id']].append(seg_ann) else: anns[seg_ann['id']] = [seg_ann] if 'images' in self.dataset: for img in self.dataset['images']: imgs[img['id']] = img if 'categories' in self.dataset: for cat in self.dataset['categories']: cats[cat['id']] = cat if 'annotations' in self.dataset and 'categories' in self.dataset: for ann in self.dataset['annotations']: for seg_ann in ann['segments_info']: cat_to_imgs[seg_ann['category_id']].append(ann['image_id']) print('index created!') self.anns = anns self.imgToAnns = img_to_anns self.catToImgs = cat_to_imgs self.imgs = imgs self.cats = cats def load_anns(self, ids=[]): """Load anns with the specified ids. self.anns is a list of annotation lists instead of a list of annotations. Args: ids (int array): integer ids specifying anns Returns: anns (object array): loaded ann objects """ anns = [] if hasattr(ids, '__iter__') and hasattr(ids, '__len__'): # self.anns is a list of annotation lists instead of # a list of annotations for id in ids: anns += self.anns[id] return anns elif type(ids) == int: return self.anns[ids] @DATASETS.register_module() class CocoPanopticDataset(CocoDataset): """Coco dataset for Panoptic segmentation. The annotation format is shown as follows. The `ann` field is optional for testing. .. code-block:: none [ { 'filename': f'{image_id:012}.png', 'image_id':9 'segments_info': { [ { 'id': 8345037, (segment_id in panoptic png, convert from rgb) 'category_id': 51, 'iscrowd': 0, 'bbox': (x1, y1, w, h), 'area': 24315, 'segmentation': list,(coded mask) }, ... } } }, ... ] Args: ann_file (str): Panoptic segmentation annotation file path. pipeline (list[dict]): Processing pipeline. ins_ann_file (str): Instance segmentation annotation file path. Defaults to None. classes (str | Sequence[str], optional): Specify classes to load. If is None, ``cls.CLASSES`` will be used. Defaults to None. data_root (str, optional): Data root for ``ann_file``, ``ins_ann_file`` ``img_prefix``, ``seg_prefix``, ``proposal_file`` if specified. Defaults to None. img_prefix (str, optional): Prefix of path to images. Defaults to ''. seg_prefix (str, optional): Prefix of path to segmentation files. Defaults to None. proposal_file (str, optional): Path to proposal file. Defaults to None. test_mode (bool, optional): If set True, annotation will not be loaded. Defaults to False. filter_empty_gt (bool, optional): If set true, images without bounding boxes of the dataset's classes will be filtered out. This option only works when `test_mode=False`, i.e., we never filter images during tests. Defaults to True. file_client_args (:obj:`mmcv.ConfigDict` | dict): file client args. Defaults to dict(backend='disk'). """ CLASSES = [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', ' truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', 'blanket', 'bridge', 'cardboard', 'counter', 'curtain', 'door-stuff', 'floor-wood', 'flower', 'fruit', 'gravel', 'house', 'light', 'mirror-stuff', 'net', 'pillow', 'platform', 'playingfield', 'railroad', 'river', 'road', 'roof', 'sand', 'sea', 'shelf', 'snow', 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', 'wall-tile', 'wall-wood', 'water-other', 'window-blind', 'window-other', 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', 'cabinet-merged', 'table-merged', 'floor-other-merged', 'pavement-merged', 'mountain-merged', 'grass-merged', 'dirt-merged', 'paper-merged', 'food-other-merged', 'building-other-merged', 'rock-merged', 'wall-other-merged', 'rug-merged' ] THING_CLASSES = [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush' ] STUFF_CLASSES = [ 'banner', 'blanket', 'bridge', 'cardboard', 'counter', 'curtain', 'door-stuff', 'floor-wood', 'flower', 'fruit', 'gravel', 'house', 'light', 'mirror-stuff', 'net', 'pillow', 'platform', 'playingfield', 'railroad', 'river', 'road', 'roof', 'sand', 'sea', 'shelf', 'snow', 'stairs', 'tent', 'towel', 'wall-brick', 'wall-stone', 'wall-tile', 'wall-wood', 'water-other', 'window-blind', 'window-other', 'tree-merged', 'fence-merged', 'ceiling-merged', 'sky-other-merged', 'cabinet-merged', 'table-merged', 'floor-other-merged', 'pavement-merged', 'mountain-merged', 'grass-merged', 'dirt-merged', 'paper-merged', 'food-other-merged', 'building-other-merged', 'rock-merged', 'wall-other-merged', 'rug-merged' ] PALETTE = [(220, 20, 60), (119, 11, 32), (0, 0, 142), (0, 0, 230), (106, 0, 228), (0, 60, 100), (0, 80, 100), (0, 0, 70), (0, 0, 192), (250, 170, 30), (100, 170, 30), (220, 220, 0), (175, 116, 175), (250, 0, 30), (165, 42, 42), (255, 77, 255), (0, 226, 252), (182, 182, 255), (0, 82, 0), (120, 166, 157), (110, 76, 0), (174, 57, 255), (199, 100, 0), (72, 0, 118), (255, 179, 240), (0, 125, 92), (209, 0, 151), (188, 208, 182), (0, 220, 176), (255, 99, 164), (92, 0, 73), (133, 129, 255), (78, 180, 255), (0, 228, 0), (174, 255, 243), (45, 89, 255), (134, 134, 103), (145, 148, 174), (255, 208, 186), (197, 226, 255), (171, 134, 1), (109, 63, 54), (207, 138, 255), (151, 0, 95), (9, 80, 61), (84, 105, 51), (74, 65, 105), (166, 196, 102), (208, 195, 210), (255, 109, 65), (0, 143, 149), (179, 0, 194), (209, 99, 106), (5, 121, 0), (227, 255, 205), (147, 186, 208), (153, 69, 1), (3, 95, 161), (163, 255, 0), (119, 0, 170), (0, 182, 199), (0, 165, 120), (183, 130, 88), (95, 32, 0), (130, 114, 135), (110, 129, 133), (166, 74, 118), (219, 142, 185), (79, 210, 114), (178, 90, 62), (65, 70, 15), (127, 167, 115), (59, 105, 106), (142, 108, 45), (196, 172, 0), (95, 54, 80), (128, 76, 255), (201, 57, 1), (246, 0, 122), (191, 162, 208), (255, 255, 128), (147, 211, 203), (150, 100, 100), (168, 171, 172), (146, 112, 198), (210, 170, 100), (92, 136, 89), (218, 88, 184), (241, 129, 0), (217, 17, 255), (124, 74, 181), (70, 70, 70), (255, 228, 255), (154, 208, 0), (193, 0, 92), (76, 91, 113), (255, 180, 195), (106, 154, 176), (230, 150, 140), (60, 143, 255), (128, 64, 128), (92, 82, 55), (254, 212, 124), (73, 77, 174), (255, 160, 98), (255, 255, 255), (104, 84, 109), (169, 164, 131), (225, 199, 255), (137, 54, 74), (135, 158, 223), (7, 246, 231), (107, 255, 200), (58, 41, 149), (183, 121, 142), (255, 73, 97), (107, 142, 35), (190, 153, 153), (146, 139, 141), (70, 130, 180), (134, 199, 156), (209, 226, 140), (96, 36, 108), (96, 96, 96), (64, 170, 64), (152, 251, 152), (208, 229, 228), (206, 186, 171), (152, 161, 64), (116, 112, 0), (0, 114, 143), (102, 102, 156), (250, 141, 255)] def __init__(self, ann_file, pipeline, ins_ann_file=None, classes=None, data_root=None, img_prefix='', seg_prefix=None, proposal_file=None, test_mode=False, filter_empty_gt=True, file_client_args=dict(backend='disk')): super().__init__( ann_file, pipeline, classes=classes, data_root=data_root, img_prefix=img_prefix, seg_prefix=seg_prefix, proposal_file=proposal_file, test_mode=test_mode, filter_empty_gt=filter_empty_gt, file_client_args=file_client_args) self.ins_ann_file = ins_ann_file def load_annotations(self, ann_file): """Load annotation from COCO Panoptic style annotation file. Args: ann_file (str): Path of annotation file. Returns: list[dict]: Annotation info from COCO api. """ self.coco = COCOPanoptic(ann_file) self.cat_ids = self.coco.get_cat_ids() self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} self.categories = self.coco.cats self.img_ids = self.coco.get_img_ids() data_infos = [] for i in self.img_ids: info = self.coco.load_imgs([i])[0] info['filename'] = info['file_name'] info['segm_file'] = info['filename'].replace('jpg', 'png') data_infos.append(info) return data_infos def get_ann_info(self, idx): """Get COCO annotation by index. Args: idx (int): Index of data. Returns: dict: Annotation info of specified index. """ img_id = self.data_infos[idx]['id'] ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) ann_info = self.coco.load_anns(ann_ids) # filter out unmatched images ann_info = [i for i in ann_info if i['image_id'] == img_id] return self._parse_ann_info(self.data_infos[idx], ann_info) def _parse_ann_info(self, img_info, ann_info): """Parse annotations and load panoptic ground truths. Args: img_info (int): Image info of an image. ann_info (list[dict]): Annotation info of an image. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore, labels, masks, seg_map. """ gt_bboxes = [] gt_labels = [] gt_bboxes_ignore = [] gt_mask_infos = [] for i, ann in enumerate(ann_info): x1, y1, w, h = ann['bbox'] if ann['area'] <= 0 or w < 1 or h < 1: continue bbox = [x1, y1, x1 + w, y1 + h] category_id = ann['category_id'] contiguous_cat_id = self.cat2label[category_id] is_thing = self.coco.load_cats(ids=category_id)[0]['isthing'] if is_thing: is_crowd = ann.get('iscrowd', False) if not is_crowd: gt_bboxes.append(bbox) gt_labels.append(contiguous_cat_id) else: gt_bboxes_ignore.append(bbox) is_thing = False mask_info = { 'id': ann['id'], 'category': contiguous_cat_id, 'is_thing': is_thing } gt_mask_infos.append(mask_info) if gt_bboxes: gt_bboxes = np.array(gt_bboxes, dtype=np.float32) gt_labels = np.array(gt_labels, dtype=np.int64) else: gt_bboxes = np.zeros((0, 4), dtype=np.float32) gt_labels = np.array([], dtype=np.int64) if gt_bboxes_ignore: gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32) else: gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32) ann = dict( bboxes=gt_bboxes, labels=gt_labels, bboxes_ignore=gt_bboxes_ignore, masks=gt_mask_infos, seg_map=img_info['segm_file']) return ann def _filter_imgs(self, min_size=32): """Filter images too small or without ground truths.""" ids_with_ann = [] # check whether images have legal thing annotations. for lists in self.coco.anns.values(): for item in lists: category_id = item['category_id'] is_thing = self.coco.load_cats(ids=category_id)[0]['isthing'] if not is_thing: continue ids_with_ann.append(item['image_id']) ids_with_ann = set(ids_with_ann) valid_inds = [] valid_img_ids = [] for i, img_info in enumerate(self.data_infos): img_id = self.img_ids[i] if self.filter_empty_gt and img_id not in ids_with_ann: continue if min(img_info['width'], img_info['height']) >= min_size: valid_inds.append(i) valid_img_ids.append(img_id) self.img_ids = valid_img_ids return valid_inds def _pan2json(self, results, outfile_prefix): """Convert panoptic results to COCO panoptic json style.""" label2cat = dict((v, k) for (k, v) in self.cat2label.items()) pred_annotations = [] outdir = os.path.join(os.path.dirname(outfile_prefix), 'panoptic') for idx in range(len(self)): img_id = self.img_ids[idx] segm_file = self.data_infos[idx]['segm_file'] pan = results[idx] pan_labels = np.unique(pan) segm_info = [] for pan_label in pan_labels: sem_label = pan_label % INSTANCE_OFFSET # We reserve the length of self.CLASSES for VOID label if sem_label == len(self.CLASSES): continue # convert sem_label to json label cat_id = label2cat[sem_label] is_thing = self.categories[cat_id]['isthing'] mask = pan == pan_label area = mask.sum() segm_info.append({ 'id': int(pan_label), 'category_id': cat_id, 'isthing': is_thing, 'area': int(area) }) # evaluation script uses 0 for VOID label. pan[pan % INSTANCE_OFFSET == len(self.CLASSES)] = VOID pan = id2rgb(pan).astype(np.uint8) mmcv.imwrite(pan[:, :, ::-1], os.path.join(outdir, segm_file)) record = { 'image_id': img_id, 'segments_info': segm_info, 'file_name': segm_file } pred_annotations.append(record) pan_json_results = dict(annotations=pred_annotations) return pan_json_results def results2json(self, results, outfile_prefix): """Dump the results to a COCO style json file. There are 4 types of results: proposals, bbox predictions, mask predictions, panoptic segmentation predictions, and they have different data types. This method will automatically recognize the type, and dump them to json files. .. code-block:: none [ { 'pan_results': np.array, # shape (h, w) # ins_results which includes bboxes and RLE encoded masks # is optional. 'ins_results': (list[np.array], list[list[str]]) }, ... ] Args: results (list[dict]): Testing results of the dataset. outfile_prefix (str): The filename prefix of the json files. If the prefix is "somepath/xxx", the json files will be named "somepath/xxx.panoptic.json", "somepath/xxx.bbox.json", "somepath/xxx.segm.json" Returns: dict[str: str]: Possible keys are "panoptic", "bbox", "segm", \ "proposal", and values are corresponding filenames. """ result_files = dict() # panoptic segmentation results if 'pan_results' in results[0]: pan_results = [result['pan_results'] for result in results] pan_json_results = self._pan2json(pan_results, outfile_prefix) result_files['panoptic'] = f'{outfile_prefix}.panoptic.json' mmcv.dump(pan_json_results, result_files['panoptic']) # instance segmentation results if 'ins_results' in results[0]: ins_results = [result['ins_results'] for result in results] bbox_json_results, segm_json_results = self._segm2json(ins_results) result_files['bbox'] = f'{outfile_prefix}.bbox.json' result_files['proposal'] = f'{outfile_prefix}.bbox.json' result_files['segm'] = f'{outfile_prefix}.segm.json' mmcv.dump(bbox_json_results, result_files['bbox']) mmcv.dump(segm_json_results, result_files['segm']) return result_files def evaluate_pan_json(self, result_files, outfile_prefix, logger=None, classwise=False, nproc=32): """Evaluate PQ according to the panoptic results json file.""" imgs = self.coco.imgs gt_json = self.coco.img_ann_map # image to annotations gt_json = [{ 'image_id': k, 'segments_info': v, 'file_name': imgs[k]['segm_file'] } for k, v in gt_json.items()] pred_json = mmcv.load(result_files['panoptic']) pred_json = dict( (el['image_id'], el) for el in pred_json['annotations']) # match the gt_anns and pred_anns in the same image matched_annotations_list = [] for gt_ann in gt_json: img_id = gt_ann['image_id'] if img_id not in pred_json.keys(): raise Exception('no prediction for the image' ' with id: {}'.format(img_id)) matched_annotations_list.append((gt_ann, pred_json[img_id])) gt_folder = self.seg_prefix pred_folder = os.path.join(os.path.dirname(outfile_prefix), 'panoptic')
pq_stat = pq_compute_multi_core(
1
2023-12-01 20:08:54+00:00
16k
IanYeung/MGLD-VSR
basicsr/data/realbasicvsr_dataset.py
[ { "identifier": "Clip", "path": "basicsr/data/mmcv_transforms/aug_pix.py", "snippet": "class Clip(BaseTransform):\n \"\"\"Clip the pixels.\n\n Modified keys are the attributes specified in \"keys\".\n\n Args:\n keys (list[str]): The keys whose values are clipped.\n a_min (int): Lo...
import cv2 import math import time import os import os.path as osp import numpy as np import random import torch from copy import deepcopy from pathlib import Path from torch.utils import data as data from basicsr.data.mmcv_transforms import Clip, UnsharpMasking, RescaleToZeroOne from basicsr.data.mmcv_transforms import RandomBlur, RandomResize, RandomNoise, RandomJPEGCompression, RandomVideoCompression, DegradationsWithShuffle from basicsr.data.degradations import circular_lowpass_kernel, random_mixed_kernels from basicsr.data.transforms import augment, single_random_crop, paired_random_crop from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor, tensor2img, imwrite from basicsr.utils.flow_util import dequantize_flow from basicsr.utils.registry import DATASET_REGISTRY
13,872
# @DATASET_REGISTRY.register() class RealVSRRecurrentDataset(data.Dataset): """REDS dataset for training recurrent networks. The keys are generated from a meta info txt file. basicsr/data/meta_info/meta_info_REDS_GT.txt Each line contains: 1. subfolder (clip) name; 2. frame number; 3. image shape, separated by a white space. Examples: 000 100 (720,1280,3) 001 100 (720,1280,3) ... Key examples: "000/00000000" GT (gt): Ground-Truth; LQ (lq): Low-Quality, e.g., low-resolution/blurry/noisy/compressed frames. Args: opt (dict): Config for train dataset. It contains the following keys: dataroot_gt (str): Data root path for gt. meta_info_file (str): Path for meta information file. val_partition (str): Validation partition types. 'REDS4' or 'official'. io_backend (dict): IO backend type and other kwarg. num_frame (int): Window size for input frames. gt_size (int): Cropped patched size for gt patches. interval_list (list): Interval list for temporal augmentation. random_reverse (bool): Random reverse input frames. use_hflip (bool): Use horizontal flips. use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation). """ def __init__(self, opt): super(RealVSRRecurrentDataset, self).__init__() self.opt = opt self.gt_root = Path(opt['dataroot_gt']) self.num_frame = opt['num_frame'] self.keys = [] with open(opt['meta_info_file'], 'r') as fin: for line in fin: folder, frame_num, _ = line.split(' ') self.keys.extend([f'{folder}/{i:08d}' for i in range(int(frame_num))]) # remove the video clips used in validation if opt['val_partition'] == 'REDS4': val_partition = ['000', '011', '015', '020'] elif opt['val_partition'] == 'official': val_partition = [f'{v:03d}' for v in range(240, 270)] else: raise ValueError(f'Wrong validation partition {opt["val_partition"]}.' f"Supported ones are ['official', 'REDS4'].") if opt['test_mode']: self.keys = [v for v in self.keys if v.split('/')[0] in val_partition] else: self.keys = [v for v in self.keys if v.split('/')[0] not in val_partition] # file client (io backend) self.file_client = None self.io_backend_opt = opt['io_backend'] self.is_lmdb = False if self.io_backend_opt['type'] == 'lmdb': self.is_lmdb = True self.io_backend_opt['db_paths'] = [self.gt_root] self.io_backend_opt['client_keys'] = ['gt'] # temporal augmentation configs self.interval_list = opt.get('interval_list', [1]) self.random_reverse = opt.get('random_reverse', False) interval_str = ','.join(str(x) for x in self.interval_list) logger = get_root_logger() logger.info(f'Temporal augmentation interval list: [{interval_str}]; ' f'random reverse is {self.random_reverse}.') # the first degradation self.random_blur_1 = RandomBlur( params=opt['degradation_1']['random_blur']['params'], keys=opt['degradation_1']['random_blur']['keys'] ) self.random_resize_1 = RandomResize( params=opt['degradation_1']['random_resize']['params'], keys=opt['degradation_1']['random_resize']['keys'] ) self.random_noise_1 = RandomNoise( params=opt['degradation_1']['random_noise']['params'], keys=opt['degradation_1']['random_noise']['keys'] ) self.random_jpeg_1 = RandomJPEGCompression( params=opt['degradation_1']['random_jpeg']['params'], keys=opt['degradation_1']['random_jpeg']['keys'] )
# @DATASET_REGISTRY.register() class RealVSRRecurrentDataset(data.Dataset): """REDS dataset for training recurrent networks. The keys are generated from a meta info txt file. basicsr/data/meta_info/meta_info_REDS_GT.txt Each line contains: 1. subfolder (clip) name; 2. frame number; 3. image shape, separated by a white space. Examples: 000 100 (720,1280,3) 001 100 (720,1280,3) ... Key examples: "000/00000000" GT (gt): Ground-Truth; LQ (lq): Low-Quality, e.g., low-resolution/blurry/noisy/compressed frames. Args: opt (dict): Config for train dataset. It contains the following keys: dataroot_gt (str): Data root path for gt. meta_info_file (str): Path for meta information file. val_partition (str): Validation partition types. 'REDS4' or 'official'. io_backend (dict): IO backend type and other kwarg. num_frame (int): Window size for input frames. gt_size (int): Cropped patched size for gt patches. interval_list (list): Interval list for temporal augmentation. random_reverse (bool): Random reverse input frames. use_hflip (bool): Use horizontal flips. use_rot (bool): Use rotation (use vertical flip and transposing h and w for implementation). """ def __init__(self, opt): super(RealVSRRecurrentDataset, self).__init__() self.opt = opt self.gt_root = Path(opt['dataroot_gt']) self.num_frame = opt['num_frame'] self.keys = [] with open(opt['meta_info_file'], 'r') as fin: for line in fin: folder, frame_num, _ = line.split(' ') self.keys.extend([f'{folder}/{i:08d}' for i in range(int(frame_num))]) # remove the video clips used in validation if opt['val_partition'] == 'REDS4': val_partition = ['000', '011', '015', '020'] elif opt['val_partition'] == 'official': val_partition = [f'{v:03d}' for v in range(240, 270)] else: raise ValueError(f'Wrong validation partition {opt["val_partition"]}.' f"Supported ones are ['official', 'REDS4'].") if opt['test_mode']: self.keys = [v for v in self.keys if v.split('/')[0] in val_partition] else: self.keys = [v for v in self.keys if v.split('/')[0] not in val_partition] # file client (io backend) self.file_client = None self.io_backend_opt = opt['io_backend'] self.is_lmdb = False if self.io_backend_opt['type'] == 'lmdb': self.is_lmdb = True self.io_backend_opt['db_paths'] = [self.gt_root] self.io_backend_opt['client_keys'] = ['gt'] # temporal augmentation configs self.interval_list = opt.get('interval_list', [1]) self.random_reverse = opt.get('random_reverse', False) interval_str = ','.join(str(x) for x in self.interval_list) logger = get_root_logger() logger.info(f'Temporal augmentation interval list: [{interval_str}]; ' f'random reverse is {self.random_reverse}.') # the first degradation self.random_blur_1 = RandomBlur( params=opt['degradation_1']['random_blur']['params'], keys=opt['degradation_1']['random_blur']['keys'] ) self.random_resize_1 = RandomResize( params=opt['degradation_1']['random_resize']['params'], keys=opt['degradation_1']['random_resize']['keys'] ) self.random_noise_1 = RandomNoise( params=opt['degradation_1']['random_noise']['params'], keys=opt['degradation_1']['random_noise']['keys'] ) self.random_jpeg_1 = RandomJPEGCompression( params=opt['degradation_1']['random_jpeg']['params'], keys=opt['degradation_1']['random_jpeg']['keys'] )
self.random_mpeg_1 = RandomVideoCompression(
7
2023-11-30 01:50:29+00:00
16k
Institute4FutureHealth/CHA
tasks/types.py
[ { "identifier": "ActivityAnalysis", "path": "tasks/affect/activity_analysis.py", "snippet": "class ActivityAnalysis(Affect):\n \"\"\"\n **Description:**\n\n This tasks performs average, sum, or trend analysis on the provided raw activity affect data for specific patient.\n \"\"\"\n\n ...
from typing import Dict from typing import Type from tasks.affect import ActivityAnalysis from tasks.affect import ActivityGet from tasks.affect import SleepAnalysis from tasks.affect import SleepGet from tasks.ask_user import AskUser from tasks.google_translator import GoogleTranslate from tasks.playwright import Click from tasks.playwright import CurrentWebPage from tasks.playwright import ExtractHyperlinks from tasks.playwright import ExtractText from tasks.playwright import GetElements from tasks.playwright import Navigate from tasks.playwright import NavigateBack from tasks.read_from_datapipe import ReadDataPipe from tasks.serpapi import SerpAPI from tasks.task import BaseTask from tasks.task_types import TaskType from tasks.test_file import TestFile
13,939
TASK_TO_CLASS: Dict[TaskType, Type[BaseTask]] = { TaskType.SERPAPI: SerpAPI, TaskType.CLICK: Click, TaskType.GET_CURRENT_PAGE: CurrentWebPage, TaskType.EXTRACT_HYPERLINKS: ExtractHyperlinks, TaskType.EXTRACT_TEXT: ExtractText,
TASK_TO_CLASS: Dict[TaskType, Type[BaseTask]] = { TaskType.SERPAPI: SerpAPI, TaskType.CLICK: Click, TaskType.GET_CURRENT_PAGE: CurrentWebPage, TaskType.EXTRACT_HYPERLINKS: ExtractHyperlinks, TaskType.EXTRACT_TEXT: ExtractText,
TaskType.GET_ELEMENTS: GetElements,
10
2023-12-02 05:10:44+00:00
16k
Czm369/MixPL
mmdet/models/dense_heads/atss_vlfusion_head.py
[ { "identifier": "MODELS", "path": "mmdet/registry.py", "snippet": "MODELS = Registry('model', parent=MMENGINE_MODELS, locations=['mmdet.models'])" }, { "identifier": "cat_boxes", "path": "mmdet/structures/bbox/transforms.py", "snippet": "def cat_boxes(data_list: List[Union[Tensor, BaseBo...
import copy import math import torch import torch.nn as nn import torch.nn.functional as F from typing import Callable, List, Optional, Sequence, Tuple, Union from mmcv.cnn import Scale from mmcv.ops.modulated_deform_conv import ModulatedDeformConv2d from mmengine.config import ConfigDict from mmengine.model import BaseModel from mmengine.structures import InstanceData from torch import Tensor from transformers import BertConfig from mmdet.registry import MODELS from mmdet.structures.bbox import cat_boxes from mmdet.utils import InstanceList, OptInstanceList, reduce_mean from ..utils import (BertEncoderLayer, VLFuse, filter_scores_and_topk, permute_and_flatten, select_single_mlvl, unpack_gt_instances) from ..utils.vlfuse_helper import MAX_CLAMP_VALUE from .atss_head import ATSSHead
10,921
use_dyfuse: bool = True, use_dcn: bool = True, use_checkpoint: bool = False, **kwargs) -> None: super().__init__(**kwargs) if BertConfig is None: raise RuntimeError( 'transformers is not installed, please install it by: ' 'pip install transformers.') self.in_channels = in_channels self.feat_channels = feat_channels self.num_base_priors = num_base_priors self.early_fuse = early_fuse self.num_dyhead_blocks = num_dyhead_blocks self.use_dyrelu = use_dyrelu self.use_dyfuse = use_dyfuse self.use_dcn = use_dcn self.use_checkpoint = use_checkpoint self.lang_cfg = BertConfig.from_pretrained(lang_model_name) self.lang_dim = self.lang_cfg.hidden_size self._init_layers() def _init_layers(self) -> None: """Initialize layers of the model.""" bias_value = -math.log((1 - 0.01) / 0.01) dyhead_tower = [] for i in range(self.num_dyhead_blocks): if self.early_fuse: # cross-modality fusion dyhead_tower.append(VLFuse(use_checkpoint=self.use_checkpoint)) # lang branch dyhead_tower.append( BertEncoderLayer( self.lang_cfg, clamp_min_for_underflow=True, clamp_max_for_overflow=True)) # vision branch dyhead_tower.append( DyConv( lambda i, o, s: Conv3x3Norm( i, o, s, use_dcn=self.use_dcn, norm_type=['gn', 16]), self.in_channels if i == 0 else self.feat_channels, self.feat_channels, use_dyrelu=(self.use_dyrelu and self.in_channels == self.feat_channels) if i == 0 else self.use_dyrelu, use_dyfuse=(self.use_dyfuse and self.in_channels == self.feat_channels) if i == 0 else self.use_dyfuse, use_dcn=(self.use_dcn and self.in_channels == self.feat_channels) if i == 0 else self.use_dcn, )) self.add_module('dyhead_tower', nn.Sequential(*dyhead_tower)) self.bbox_pred = nn.Conv2d( self.feat_channels, self.num_base_priors * 4, kernel_size=1) self.centerness = nn.Conv2d( self.feat_channels, self.num_base_priors * 1, kernel_size=1) self.dot_product_projection_text = nn.Linear( self.lang_dim, self.num_base_priors * self.feat_channels, bias=True) self.log_scale = nn.Parameter(torch.Tensor([0.0]), requires_grad=True) self.bias_lang = nn.Parameter( torch.zeros(self.lang_dim), requires_grad=True) self.bias0 = nn.Parameter( torch.Tensor([bias_value]), requires_grad=True) self.scales = nn.ModuleList([Scale(1.0) for _ in range(5)]) def forward(self, visual_feats: Tuple[Tensor], language_feats: dict) -> Tuple: feat_inputs = {'visual': visual_feats, 'lang': language_feats} dyhead_tower = self.dyhead_tower(feat_inputs) if self.early_fuse: embedding = dyhead_tower['lang']['hidden'] else: embedding = language_feats['embedded'] embedding = F.normalize(embedding, p=2, dim=-1) dot_product_proj_tokens = self.dot_product_projection_text(embedding / 2.0) dot_product_proj_tokens_bias = torch.matmul( embedding, self.bias_lang) + self.bias0 bbox_preds = [] centerness = [] cls_logits = [] for i, feature in enumerate(visual_feats): visual = dyhead_tower['visual'][i] B, C, H, W = visual.shape bbox_pred = self.scales[i](self.bbox_pred(visual)) bbox_preds.append(bbox_pred) centerness.append(self.centerness(visual)) dot_product_proj_queries = permute_and_flatten( visual, B, self.num_base_priors, C, H, W) bias = dot_product_proj_tokens_bias.unsqueeze(1).repeat( 1, self.num_base_priors, 1) dot_product_logit = ( torch.matmul(dot_product_proj_queries, dot_product_proj_tokens.transpose(-1, -2)) / self.log_scale.exp()) + bias dot_product_logit = torch.clamp( dot_product_logit, max=MAX_CLAMP_VALUE) dot_product_logit = torch.clamp( dot_product_logit, min=-MAX_CLAMP_VALUE) cls_logits.append(dot_product_logit) return bbox_preds, centerness, cls_logits
# Copyright (c) OpenMMLab. All rights reserved. try: except ImportError: BertConfig = None def convert_grounding_to_cls_scores(logits: Tensor, positive_maps: List[dict]) -> Tensor: """Convert logits to class scores.""" assert len(positive_maps) == logits.shape[0] # batch size scores = torch.zeros(logits.shape[0], logits.shape[1], len(positive_maps[0])).to(logits.device) if positive_maps is not None: if all(x == positive_maps[0] for x in positive_maps): # only need to compute once positive_map = positive_maps[0] for label_j in positive_map: scores[:, :, label_j - 1] = logits[:, :, torch.LongTensor(positive_map[label_j] )].mean(-1) else: for i, positive_map in enumerate(positive_maps): for label_j in positive_map: scores[i, :, label_j - 1] = logits[ i, :, torch.LongTensor(positive_map[label_j])].mean(-1) return scores class Conv3x3Norm(nn.Module): """Conv3x3 and norm.""" def __init__(self, in_channels: int, out_channels: int, stride: int, groups: int = 1, use_dcn: bool = False, norm_type: Optional[Union[Sequence, str]] = None): super().__init__() if use_dcn: self.conv = ModulatedDeformConv2d( in_channels, out_channels, kernel_size=3, stride=stride, padding=1, groups=groups) else: self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=stride, padding=1, groups=groups) if isinstance(norm_type, Sequence): assert len(norm_type) == 2 assert norm_type[0] == 'gn' gn_group = norm_type[1] norm_type = norm_type[0] if norm_type == 'bn': bn_op = nn.BatchNorm2d(out_channels) elif norm_type == 'gn': bn_op = nn.GroupNorm( num_groups=gn_group, num_channels=out_channels) if norm_type is not None: self.bn = bn_op else: self.bn = None def forward(self, x, **kwargs): x = self.conv(x, **kwargs) if self.bn: x = self.bn(x) return x class DyReLU(nn.Module): """Dynamic ReLU.""" def __init__(self, in_channels: int, out_channels: int, expand_ratio: int = 4): super().__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.expand_ratio = expand_ratio self.out_channels = out_channels self.fc = nn.Sequential( nn.Linear(in_channels, in_channels // expand_ratio), nn.ReLU(inplace=True), nn.Linear(in_channels // expand_ratio, out_channels * self.expand_ratio), nn.Hardsigmoid(inplace=True)) def forward(self, x) -> Tensor: x_out = x b, c, h, w = x.size() x = self.avg_pool(x).view(b, c) x = self.fc(x).view(b, -1, 1, 1) a1, b1, a2, b2 = torch.split(x, self.out_channels, dim=1) a1 = (a1 - 0.5) * 2 + 1.0 a2 = (a2 - 0.5) * 2 b1 = b1 - 0.5 b2 = b2 - 0.5 out = torch.max(x_out * a1 + b1, x_out * a2 + b2) return out class DyConv(nn.Module): """Dynamic Convolution.""" def __init__(self, conv_func: Callable, in_channels: int, out_channels: int, use_dyfuse: bool = True, use_dyrelu: bool = False, use_dcn: bool = False): super().__init__() self.dyconvs = nn.ModuleList() self.dyconvs.append(conv_func(in_channels, out_channels, 1)) self.dyconvs.append(conv_func(in_channels, out_channels, 1)) self.dyconvs.append(conv_func(in_channels, out_channels, 2)) if use_dyfuse: self.attnconv = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels, 1, kernel_size=1), nn.ReLU(inplace=True)) self.h_sigmoid = nn.Hardsigmoid(inplace=True) else: self.attnconv = None if use_dyrelu: self.relu = DyReLU(in_channels, out_channels) else: self.relu = nn.ReLU() if use_dcn: self.offset = nn.Conv2d( in_channels, 27, kernel_size=3, stride=1, padding=1) else: self.offset = None self.init_weights() def init_weights(self): for m in self.dyconvs.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weight.data, 0, 0.01) if m.bias is not None: m.bias.data.zero_() if self.attnconv is not None: for m in self.attnconv.modules(): if isinstance(m, nn.Conv2d): nn.init.normal_(m.weight.data, 0, 0.01) if m.bias is not None: m.bias.data.zero_() def forward(self, inputs: dict) -> dict: visual_feats = inputs['visual'] out_vis_feats = [] for level, feature in enumerate(visual_feats): offset_conv_args = {} if self.offset is not None: offset_mask = self.offset(feature) offset = offset_mask[:, :18, :, :] mask = offset_mask[:, 18:, :, :].sigmoid() offset_conv_args = dict(offset=offset, mask=mask) temp_feats = [self.dyconvs[1](feature, **offset_conv_args)] if level > 0: temp_feats.append(self.dyconvs[2](visual_feats[level - 1], **offset_conv_args)) if level < len(visual_feats) - 1: temp_feats.append( F.upsample_bilinear( self.dyconvs[0](visual_feats[level + 1], **offset_conv_args), size=[feature.size(2), feature.size(3)])) mean_feats = torch.mean( torch.stack(temp_feats), dim=0, keepdim=False) if self.attnconv is not None: attn_feat = [] res_feat = [] for feat in temp_feats: res_feat.append(feat) attn_feat.append(self.attnconv(feat)) res_feat = torch.stack(res_feat) spa_pyr_attn = self.h_sigmoid(torch.stack(attn_feat)) mean_feats = torch.mean( res_feat * spa_pyr_attn, dim=0, keepdim=False) out_vis_feats.append(mean_feats) out_vis_feats = [self.relu(item) for item in out_vis_feats] features_dict = {'visual': out_vis_feats, 'lang': inputs['lang']} return features_dict class VLFusionModule(BaseModel): """Visual-lang Fusion Module.""" def __init__(self, in_channels: int, feat_channels: int, num_base_priors: int, early_fuse: bool = False, num_dyhead_blocks: int = 6, lang_model_name: str = 'bert-base-uncased', use_dyrelu: bool = True, use_dyfuse: bool = True, use_dcn: bool = True, use_checkpoint: bool = False, **kwargs) -> None: super().__init__(**kwargs) if BertConfig is None: raise RuntimeError( 'transformers is not installed, please install it by: ' 'pip install transformers.') self.in_channels = in_channels self.feat_channels = feat_channels self.num_base_priors = num_base_priors self.early_fuse = early_fuse self.num_dyhead_blocks = num_dyhead_blocks self.use_dyrelu = use_dyrelu self.use_dyfuse = use_dyfuse self.use_dcn = use_dcn self.use_checkpoint = use_checkpoint self.lang_cfg = BertConfig.from_pretrained(lang_model_name) self.lang_dim = self.lang_cfg.hidden_size self._init_layers() def _init_layers(self) -> None: """Initialize layers of the model.""" bias_value = -math.log((1 - 0.01) / 0.01) dyhead_tower = [] for i in range(self.num_dyhead_blocks): if self.early_fuse: # cross-modality fusion dyhead_tower.append(VLFuse(use_checkpoint=self.use_checkpoint)) # lang branch dyhead_tower.append( BertEncoderLayer( self.lang_cfg, clamp_min_for_underflow=True, clamp_max_for_overflow=True)) # vision branch dyhead_tower.append( DyConv( lambda i, o, s: Conv3x3Norm( i, o, s, use_dcn=self.use_dcn, norm_type=['gn', 16]), self.in_channels if i == 0 else self.feat_channels, self.feat_channels, use_dyrelu=(self.use_dyrelu and self.in_channels == self.feat_channels) if i == 0 else self.use_dyrelu, use_dyfuse=(self.use_dyfuse and self.in_channels == self.feat_channels) if i == 0 else self.use_dyfuse, use_dcn=(self.use_dcn and self.in_channels == self.feat_channels) if i == 0 else self.use_dcn, )) self.add_module('dyhead_tower', nn.Sequential(*dyhead_tower)) self.bbox_pred = nn.Conv2d( self.feat_channels, self.num_base_priors * 4, kernel_size=1) self.centerness = nn.Conv2d( self.feat_channels, self.num_base_priors * 1, kernel_size=1) self.dot_product_projection_text = nn.Linear( self.lang_dim, self.num_base_priors * self.feat_channels, bias=True) self.log_scale = nn.Parameter(torch.Tensor([0.0]), requires_grad=True) self.bias_lang = nn.Parameter( torch.zeros(self.lang_dim), requires_grad=True) self.bias0 = nn.Parameter( torch.Tensor([bias_value]), requires_grad=True) self.scales = nn.ModuleList([Scale(1.0) for _ in range(5)]) def forward(self, visual_feats: Tuple[Tensor], language_feats: dict) -> Tuple: feat_inputs = {'visual': visual_feats, 'lang': language_feats} dyhead_tower = self.dyhead_tower(feat_inputs) if self.early_fuse: embedding = dyhead_tower['lang']['hidden'] else: embedding = language_feats['embedded'] embedding = F.normalize(embedding, p=2, dim=-1) dot_product_proj_tokens = self.dot_product_projection_text(embedding / 2.0) dot_product_proj_tokens_bias = torch.matmul( embedding, self.bias_lang) + self.bias0 bbox_preds = [] centerness = [] cls_logits = [] for i, feature in enumerate(visual_feats): visual = dyhead_tower['visual'][i] B, C, H, W = visual.shape bbox_pred = self.scales[i](self.bbox_pred(visual)) bbox_preds.append(bbox_pred) centerness.append(self.centerness(visual)) dot_product_proj_queries = permute_and_flatten( visual, B, self.num_base_priors, C, H, W) bias = dot_product_proj_tokens_bias.unsqueeze(1).repeat( 1, self.num_base_priors, 1) dot_product_logit = ( torch.matmul(dot_product_proj_queries, dot_product_proj_tokens.transpose(-1, -2)) / self.log_scale.exp()) + bias dot_product_logit = torch.clamp( dot_product_logit, max=MAX_CLAMP_VALUE) dot_product_logit = torch.clamp( dot_product_logit, min=-MAX_CLAMP_VALUE) cls_logits.append(dot_product_logit) return bbox_preds, centerness, cls_logits
@MODELS.register_module()
0
2023-11-30 08:58:00+00:00
16k
SEU-ProactiveSecurity-Group/MalPurifier
core/defense/md_at_ma.py
[ { "identifier": "Max", "path": "core/attack/max.py", "snippet": "class Max(BaseAttack):\n \"\"\"\n Max攻击:迭代地从多个攻击方法中选择结果。\n\n 参数\n --------\n @param attack_list: List, 已实例化的攻击对象的列表。\n @param varepsilon: Float, 用于判断收敛性的标量。\n \"\"\"\n\n def __init__(self, attack_list, varepsilon=1e...
import os.path as path import random import time import torch import torch.optim as optim import numpy as np from core.attack.max import Max from core.attack.stepwise_max import StepwiseMax from config import config, logging, ErrorHandler from tools import utils
14,036
""" max adversarial training framework """ from __future__ import absolute_import from __future__ import division from __future__ import print_function
""" max adversarial training framework """ from __future__ import absolute_import from __future__ import division from __future__ import print_function
logger = logging.getLogger('core.defense.max_adv_training')
2
2023-11-27 02:00:23+00:00
16k
Vali-98/XTTS-RVC-UI
rvc.py
[ { "identifier": "SynthesizerTrnMs256NSFsid", "path": "infer_pack/models.py", "snippet": "class SynthesizerTrnMs256NSFsid(nn.Module):\n def __init__(\n self,\n spec_channels,\n segment_size,\n inter_channels,\n hidden_channels,\n filter_channels,\n n_he...
from multiprocessing import cpu_count from pathlib import Path from fairseq import checkpoint_utils from scipy.io import wavfile from infer_pack.models import ( SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono, SynthesizerTrnMs768NSFsid, SynthesizerTrnMs768NSFsid_nono, ) from vc_infer_pipeline import VC import torch import librosa import numpy as np
11,057
class Config: def __init__(self, device, is_half): self.device = device self.is_half = is_half self.n_cpu = 0 self.gpu_name = None self.gpu_mem = None self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config() def device_config(self) -> tuple: if torch.cuda.is_available(): i_device = int(self.device.split(":")[-1]) self.gpu_name = torch.cuda.get_device_name(i_device) if ( ("16" in self.gpu_name and "V100" not in self.gpu_name.upper()) or "P40" in self.gpu_name.upper() or "1060" in self.gpu_name or "1070" in self.gpu_name or "1080" in self.gpu_name ): print("16 series/10 series P40 forced single precision") self.is_half = False else: self.gpu_name = None self.gpu_mem = int( torch.cuda.get_device_properties(i_device).total_memory / 1024 / 1024 / 1024 + 0.4 ) if self.gpu_mem <= 2: print('Not enough VRAM to load models (Probably)') self.device = 'cpu' elif torch.backends.mps.is_available(): print("No supported N-card found, use MPS for inference") self.device = "mps" else: print("No supported N-card found, use CPU for inference") self.device = "cpu" if self.n_cpu == 0: self.n_cpu = cpu_count() if self.is_half: # 6G memory config x_pad = 3 x_query = 10 x_center = 60 x_max = 65 else: # 5G memory config x_pad = 1 x_query = 6 x_center = 38 x_max = 41 if self.gpu_mem != None and self.gpu_mem <= 4: x_pad = 1 x_query = 5 x_center = 30 x_max = 32 return x_pad, x_query, x_center, x_max def load_hubert(device, is_half, model_path): models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task([model_path], suffix='', ) hubert = models[0] hubert = hubert.to(device) if is_half: hubert = hubert.half() else: hubert = hubert.float() hubert.eval() return hubert def get_vc(device, is_half, config, model_path): cpt = torch.load(model_path, map_location='cpu') if "config" not in cpt or "weight" not in cpt: raise ValueError(f'Incorrect format for {model_path}. Use a voice model trained using RVC v2 instead.') tgt_sr = cpt["config"][-1] cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] if_f0 = cpt.get("f0", 1) version = cpt.get("version", "v1") if version == "v1": if if_f0 == 1: net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=is_half) else:
class Config: def __init__(self, device, is_half): self.device = device self.is_half = is_half self.n_cpu = 0 self.gpu_name = None self.gpu_mem = None self.x_pad, self.x_query, self.x_center, self.x_max = self.device_config() def device_config(self) -> tuple: if torch.cuda.is_available(): i_device = int(self.device.split(":")[-1]) self.gpu_name = torch.cuda.get_device_name(i_device) if ( ("16" in self.gpu_name and "V100" not in self.gpu_name.upper()) or "P40" in self.gpu_name.upper() or "1060" in self.gpu_name or "1070" in self.gpu_name or "1080" in self.gpu_name ): print("16 series/10 series P40 forced single precision") self.is_half = False else: self.gpu_name = None self.gpu_mem = int( torch.cuda.get_device_properties(i_device).total_memory / 1024 / 1024 / 1024 + 0.4 ) if self.gpu_mem <= 2: print('Not enough VRAM to load models (Probably)') self.device = 'cpu' elif torch.backends.mps.is_available(): print("No supported N-card found, use MPS for inference") self.device = "mps" else: print("No supported N-card found, use CPU for inference") self.device = "cpu" if self.n_cpu == 0: self.n_cpu = cpu_count() if self.is_half: # 6G memory config x_pad = 3 x_query = 10 x_center = 60 x_max = 65 else: # 5G memory config x_pad = 1 x_query = 6 x_center = 38 x_max = 41 if self.gpu_mem != None and self.gpu_mem <= 4: x_pad = 1 x_query = 5 x_center = 30 x_max = 32 return x_pad, x_query, x_center, x_max def load_hubert(device, is_half, model_path): models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task([model_path], suffix='', ) hubert = models[0] hubert = hubert.to(device) if is_half: hubert = hubert.half() else: hubert = hubert.float() hubert.eval() return hubert def get_vc(device, is_half, config, model_path): cpt = torch.load(model_path, map_location='cpu') if "config" not in cpt or "weight" not in cpt: raise ValueError(f'Incorrect format for {model_path}. Use a voice model trained using RVC v2 instead.') tgt_sr = cpt["config"][-1] cpt["config"][-3] = cpt["weight"]["emb_g.weight"].shape[0] if_f0 = cpt.get("f0", 1) version = cpt.get("version", "v1") if version == "v1": if if_f0 == 1: net_g = SynthesizerTrnMs256NSFsid(*cpt["config"], is_half=is_half) else:
net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
1
2023-11-30 08:47:28+00:00
16k
ubc-vision/nf-soft-mining
examples/utils.py
[ { "identifier": "OccGridEstimator", "path": "nerfacc/estimators/occ_grid.py", "snippet": "class OccGridEstimator(AbstractEstimator):\n \"\"\"Occupancy grid transmittance estimator for spatial skipping.\n\n References: \"Instant Neural Graphics Primitives.\"\n\n Args:\n roi_aabb: The axis...
import random import numpy as np import torch from typing import Optional, Sequence from typing import Literal from typing_extensions import Literal from datasets.utils import Rays, namedtuple_map from torch.utils.data._utils.collate import collate, default_collate_fn_map from nerfacc.estimators.occ_grid import OccGridEstimator from nerfacc.estimators.prop_net import PropNetEstimator from nerfacc.grid import ray_aabb_intersect, traverse_grids from nerfacc.volrend import ( accumulate_along_rays_, render_weight_from_density, rendering, )
11,006
""" Copyright (c) 2022 Ruilong Li, UC Berkeley. """ try: except ImportError: NERF_SYNTHETIC_SCENES = [ "chair", "drums", "ficus", "hotdog", "lego", "materials", "mic", "ship", ] MIPNERF360_UNBOUNDED_SCENES = [ "garden", "bicycle", "bonsai", "counter", "kitchen", "room", "stump", ] LLFF_NDC_SCENES = [ "fern", "flower", "fortress", "horns", "leaves", "orchids", "room_llff", "trex", ] def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) def render_image_with_occgrid( # scene radiance_field: torch.nn.Module,
""" Copyright (c) 2022 Ruilong Li, UC Berkeley. """ try: except ImportError: NERF_SYNTHETIC_SCENES = [ "chair", "drums", "ficus", "hotdog", "lego", "materials", "mic", "ship", ] MIPNERF360_UNBOUNDED_SCENES = [ "garden", "bicycle", "bonsai", "counter", "kitchen", "room", "stump", ] LLFF_NDC_SCENES = [ "fern", "flower", "fortress", "horns", "leaves", "orchids", "room_llff", "trex", ] def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) def render_image_with_occgrid( # scene radiance_field: torch.nn.Module,
estimator: OccGridEstimator,
0
2023-11-27 22:12:55+00:00
16k
facebookresearch/SOC-matching
main.py
[ { "identifier": "get_folder_name", "path": "SOC_matching/utils.py", "snippet": "def get_folder_name(cfg):\n folder_name = (\n cfg.method.algorithm\n + \"_\"\n + cfg.method.setting\n + \"_\"\n + str(cfg.method.lmbd)\n + \"_\"\n + str(cfg.method.T)\n ...
import torch import sys import logging import os import time import json import hydra import traceback from tqdm.notebook import tqdm from omegaconf import DictConfig from SOC_matching.utils import ( get_folder_name, get_file_name, control_objective, save_results, compute_EMA, normalization_constant, ) from SOC_matching.method import ( SOC_Solver, ) from SOC_matching.experiment_settings.settings import define_variables
11,688
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory. log = logging.getLogger(__name__) @hydra.main(version_base=None, config_path="configs", config_name="soc") def main(cfg: DictConfig): logging.getLogger("lightning.pytorch").setLevel(logging.getLevelName("INFO")) print(cfg) print("Found {} CUDA devices.".format(torch.cuda.device_count())) for i in range(torch.cuda.device_count()): props = torch.cuda.get_device_properties(i) print( "{} \t Memory: {:.2f}GB".format( props.name, props.total_memory / (1024**3) ) ) keys = [ "SLURM_NODELIST", "SLURM_JOB_ID", "SLURM_NTASKS", "SLURM_JOB_NAME", "SLURM_PROCID", "SLURM_LOCALID", "SLURM_NODEID", ] log.info(json.dumps({k: os.environ.get(k, None) for k in keys}, indent=4)) cmd_str = " \\\n".join([f"python {sys.argv[0]}"] + ["\t" + x for x in sys.argv[1:]]) with open("cmd.sh", "w") as fout: print("#!/bin/bash\n", file=fout) print(cmd_str, file=fout) log.info(f"CWD: {os.getcwd()}") if cfg.method.use_gpu: cfg.method.device = "cuda:" + str(cfg.method.device_number) else: cfg.method.device = "cpu" torch.manual_seed(cfg.method.seed) algorithm = cfg.method.algorithm folder_name = ( cfg.method.algorithm + "_" + cfg.method.setting + "_" + str(cfg.method.lmbd) + "_" + str(cfg.method.T) + "_" + str(cfg.method.num_steps) + "_" + str(cfg.method.use_warm_start) + "_" + str(cfg.method.seed) + "_" + str(cfg.optim.batch_size) + "_" + str(cfg.optim.M_lr) + "_" + str(cfg.optim.nabla_V_lr) ) ts = torch.linspace(0, cfg.method.T, cfg.method.num_steps + 1).to(cfg.method.device) folder_name = get_folder_name(cfg) file_name = get_file_name(folder_name, num_iterations=cfg.method.num_iterations) EMA_loss = 0 EMA_norm_sqd_diff = 0 EMA_coeff = 0.01 EMA_weight_mean_coeff = 0.002 x0, sigma, optimal_sde, neural_sde, u_warm_start = define_variables(cfg, ts) if optimal_sde is not None: ground_truth_control = optimal_sde.u else: ground_truth_control = None state0 = x0.repeat(cfg.optim.batch_size, 1) ########### Compute normalization constant and control L2 error for initial control ############ print( f"Estimating normalization constant and control L2 error for initial control..." ) ( normalization_const, normalization_const_std_error, norm_sqd_diff_mean, ) = normalization_constant( neural_sde, state0, ts, cfg, n_batches_normalization=512, ground_truth_control=ground_truth_control, ) print( f"Normalization_constant (mean and std. error): {normalization_const:5.8E} {normalization_const_std_error:5.8E}" ) if ground_truth_control is not None: print( f"Control L2 error for initial control: {norm_sqd_diff_mean / normalization_const}" ) ########### Compute control loss for optimal control ############ if optimal_sde is not None: ( optimal_control_objective_mean, optimal_control_objective_std_error,
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory. log = logging.getLogger(__name__) @hydra.main(version_base=None, config_path="configs", config_name="soc") def main(cfg: DictConfig): logging.getLogger("lightning.pytorch").setLevel(logging.getLevelName("INFO")) print(cfg) print("Found {} CUDA devices.".format(torch.cuda.device_count())) for i in range(torch.cuda.device_count()): props = torch.cuda.get_device_properties(i) print( "{} \t Memory: {:.2f}GB".format( props.name, props.total_memory / (1024**3) ) ) keys = [ "SLURM_NODELIST", "SLURM_JOB_ID", "SLURM_NTASKS", "SLURM_JOB_NAME", "SLURM_PROCID", "SLURM_LOCALID", "SLURM_NODEID", ] log.info(json.dumps({k: os.environ.get(k, None) for k in keys}, indent=4)) cmd_str = " \\\n".join([f"python {sys.argv[0]}"] + ["\t" + x for x in sys.argv[1:]]) with open("cmd.sh", "w") as fout: print("#!/bin/bash\n", file=fout) print(cmd_str, file=fout) log.info(f"CWD: {os.getcwd()}") if cfg.method.use_gpu: cfg.method.device = "cuda:" + str(cfg.method.device_number) else: cfg.method.device = "cpu" torch.manual_seed(cfg.method.seed) algorithm = cfg.method.algorithm folder_name = ( cfg.method.algorithm + "_" + cfg.method.setting + "_" + str(cfg.method.lmbd) + "_" + str(cfg.method.T) + "_" + str(cfg.method.num_steps) + "_" + str(cfg.method.use_warm_start) + "_" + str(cfg.method.seed) + "_" + str(cfg.optim.batch_size) + "_" + str(cfg.optim.M_lr) + "_" + str(cfg.optim.nabla_V_lr) ) ts = torch.linspace(0, cfg.method.T, cfg.method.num_steps + 1).to(cfg.method.device) folder_name = get_folder_name(cfg) file_name = get_file_name(folder_name, num_iterations=cfg.method.num_iterations) EMA_loss = 0 EMA_norm_sqd_diff = 0 EMA_coeff = 0.01 EMA_weight_mean_coeff = 0.002 x0, sigma, optimal_sde, neural_sde, u_warm_start = define_variables(cfg, ts) if optimal_sde is not None: ground_truth_control = optimal_sde.u else: ground_truth_control = None state0 = x0.repeat(cfg.optim.batch_size, 1) ########### Compute normalization constant and control L2 error for initial control ############ print( f"Estimating normalization constant and control L2 error for initial control..." ) ( normalization_const, normalization_const_std_error, norm_sqd_diff_mean, ) = normalization_constant( neural_sde, state0, ts, cfg, n_batches_normalization=512, ground_truth_control=ground_truth_control, ) print( f"Normalization_constant (mean and std. error): {normalization_const:5.8E} {normalization_const_std_error:5.8E}" ) if ground_truth_control is not None: print( f"Control L2 error for initial control: {norm_sqd_diff_mean / normalization_const}" ) ########### Compute control loss for optimal control ############ if optimal_sde is not None: ( optimal_control_objective_mean, optimal_control_objective_std_error,
) = control_objective(
2
2023-12-04 20:26:18+00:00
16k
yiwenlu66/learning-qp
experiments/tank/visualize_feasible_sets.py
[ { "identifier": "sys_param", "path": "src/envs/env_creators.py", "snippet": "def tank_initial_generator(size, device, rng):\ndef tank_ref_generator(size, device, rng):\ndef tank_randomizer(size, device, rng):\n B = torch.tensor(sys_param[\"tank\"][\"B\"], device=device, dtype=torch.float).unsqueeze(0...
import numpy as np import sys import os import torch from src.envs.env_creators import sys_param, env_creators from src.envs.mpc_baseline_parameters import get_mpc_baseline_parameters from src.modules.qp_unrolled_network import QPUnrolledNetwork from matplotlib import pyplot as plt from icecream import ic from src.utils.torch_utils import bmv from src.utils.visualization import plot_multiple_2d_polytopes_with_contour from src.utils.geometry import high_dim_to_2D_sampling, partial_minimization_2D
10,828
return results def evaluate_constraint_violation(trained_with_residual_loss, steps=10, forced_feasibility=False): """Rollout for multiple steps, and compute average (number of violated constraints, magnitude of violation).""" rollout_results = rollout(trained_with_residual_loss, False, steps, forced_feasibility) constraint_violation_indices = [] for i in range(steps): H = rollout_results[i][2] action_all = rollout_results[i][4] b = rollout_results[i][3] constraint_violation_indices.append(compute_violation(H, action_all, b)) average_violation_count = torch.stack([v[0] for v in constraint_violation_indices], dim=0).to(dtype=torch.float).mean(dim=0) average_violation_magnitude = torch.stack([v[1] for v in constraint_violation_indices], dim=0).mean(dim=0) return average_violation_count, average_violation_magnitude violation_count_with_residual_loss, violation_magnitude_with_residual_loss = evaluate_constraint_violation(True) violation_count_without_residual_loss, violation_magnitude_without_residual_loss = evaluate_constraint_violation(False) ic(violation_count_with_residual_loss, violation_count_without_residual_loss) ic(violation_magnitude_with_residual_loss, violation_magnitude_without_residual_loss) # %% Visualize the feasible set and objective function at a certain step, ignoring constraints that are violated at_step = 10 def get_violated_mask(H, action_all, b): z_recovered = bmv(H, action_all) + b return torch.where(z_recovered < 0., torch.ones_like(z_recovered), torch.zeros_like(z_recovered)) def get_step_parameters(at_step, trained_with_residual_loss, is_mpc, forced_feasibility=False): rollout_results = rollout(trained_with_residual_loss, is_mpc, at_step, forced_feasibility) result_last_step = rollout_results[-1] P, q, H, b, action_all = result_last_step violated_mask = get_violated_mask(H, action_all, b) return P, q, H, b, violated_mask, action_all def get_plot_parameters(trained_with_residual_loss, is_mpc, color, label, is_forced_feasibility=False): a = lambda t: t.squeeze(0).detach().cpu().numpy() global P, q, H, b, violated_mask, action_all P, q, H, b, violated_mask, action_all = get_step_parameters(at_step, trained_with_residual_loss, is_mpc, is_forced_feasibility) if not is_forced_feasibility: # Filter out violated constraints satisfied_mask = torch.logical_not(violated_mask) plot_params = { "A": a(-H[satisfied_mask, :]), "b": a(b[satisfied_mask]), "optimal_solution": a(action_all[:, :m_sys]), "P": a(P), "q": a(q), "color": color, "label": label, } else: # Learned problem with forced feasibility; recover original P, q, H, b from augmented P, q, H, b y = action_all[:, -1].item() P0 = P[:, :n, :n] q0 = q[:, :n] H0 = H[:, :m, :n] b0 = b[:, :m] + y plot_params = { "A": a(-H0), "b": a(b0), "optimal_solution": a(action_all[:, :m_sys]), "P": a(P0), "q": a(q0), "color": color, "label": label, } return plot_params fig, ax = plot_multiple_2d_polytopes_with_contour([ get_plot_parameters(True, False, "blue", "Learned QP (with residual loss)"), get_plot_parameters(False, False, "red", "Learned QP (w/o residual loss)"), get_plot_parameters(False, True, "green", "MPC") ]) ax.set_xlabel("$u_1$") ax.set_ylabel("$u_2$") ax.set_title(f"Feasible sets and objective functions at step {at_step}") # %% Visualize the feasible set and objective function at a certain step, forcing feasibility fig, ax = plot_multiple_2d_polytopes_with_contour([ get_plot_parameters(True, False, "blue", "Learned QP (forced feasibility, n=2)", True), get_plot_parameters(False, True, "green", "MPC (N=1)", True) ]) ax.set_xlabel("$u_1$") ax.set_ylabel("$u_2$") ax.set_title(f"Feasible sets and objective functions at step {at_step}") # %% Visualize feasible set vs. MPC; Now # 1. The learned QP is guaranteed to be feasible; no need to ignore violated constraints # 2. The variable are allowed to be high-dimensional; we project the constraint polytope and the quadratic objective to 2D n = 8 m = 32 mpc_N = 4 at_step = 50 mpc_baseline = get_mpc_baseline_parameters("tank", mpc_N) mpc_baseline["normalize"] = True # Solve for normalized action, to be consistent with learned QP mpc_module = QPUnrolledNetwork( device, input_size, n, m, qp_iter, None, True, True, mpc_baseline=mpc_baseline, use_osqp_for_mpc=True, ) def get_plot_parameters_proj(is_mpc, color, label): a = lambda t: t.squeeze(0).detach().cpu().numpy() P, q, H, b, violated_mask, action_all = get_step_parameters(at_step, False, is_mpc, True) if not is_mpc: # Learned problem with forced feasibility; recover original P, q, H, b from augmented P, q, H, b y = action_all[:, -1].item() P0 = P[:, :n, :n] q0 = q[:, :n] H0 = H[:, :m, :n] b0 = b[:, :m] + y else: P0, q0, H0, b0 = P, q, H, b A_proj, b_proj = high_dim_to_2D_sampling(-a(H0), a(b0))
# %% Specify test case # Case where MPC is better x0 = np.array([10., 10., 10., 10.]) x_ref = np.array([19, 19, 2.4, 2.4]) # # Case where MPC fails # x0 = np.array([ 5.4963946, 10.947876, 1.034516, 18.08066 ]) # x_ref = np.array([7.522859, 8.169776, 1.1107684, 1. ]) # Controlling process noise and parametric uncertainty noise_level = 0 parametric_uncertainty = False parameter_randomization_seed = 2 # %% Set up test bench file_path = os.path.dirname(__file__) sys.path.append(os.path.join(file_path, "../..")) # Utilities def make_obs(x, x_ref, running_mean, running_std, normalize): raw_obs = torch.tensor(np.concatenate([x, x_ref]), device=device, dtype=torch.float) if not normalize: return raw_obs.unsqueeze(0) else: return ((raw_obs - running_mean) / running_std).unsqueeze(0) def get_state_dict(checkpoint_path): checkpoint = torch.load(checkpoint_path) model = checkpoint["model"] prefix = "a2c_network.policy_net." policy_net_state_dict = {k.lstrip(prefix): v for (k, v) in model.items() if k.startswith(prefix)} if "running_mean_std.running_mean" in model: running_mean = model["running_mean_std.running_mean"].to(dtype=torch.float) running_std = model["running_mean_std.running_var"].sqrt().to(dtype=torch.float) else: running_mean = torch.tensor([0.]) running_std = torch.tensor([1.]) return policy_net_state_dict, running_mean, running_std def rescale_action(action, low=-1., high=8.): action = action.clamp(-1., 1.) return low + (high - low) * (action + 1) / 2 t = lambda arr: torch.tensor(arr, device=device, dtype=torch.float).unsqueeze(0) a = lambda t: t.detach().cpu().numpy() # Constants and options n_sys = 4 m_sys = 2 input_size = 8 # 4 for x, 4 for x_ref n = 2 m = 64 qp_iter = 10 device = "cuda:0" # MPC module mpc_baseline = get_mpc_baseline_parameters("tank", 1) mpc_baseline["normalize"] = True # Solve for normalized action, to be consistent with learned QP mpc_module = QPUnrolledNetwork( device, input_size, n, m, qp_iter, None, True, True, mpc_baseline=mpc_baseline, use_osqp_for_mpc=True, ) # Environment env = env_creators["tank"]( noise_level=noise_level, bs=1, max_steps=300, keep_stats=True, run_name="", exp_name="", randomize=parametric_uncertainty, ) # %% Compare learned QPs learned with / without residual loss, and compare degree of constraint violation def get_qp_net(trained_with_residual_loss, forced_feasibility=False): exp_name = f"residual_loss_{'on' if trained_with_residual_loss else 'off'}" if forced_feasibility: exp_name = "force_feasible_on" net = QPUnrolledNetwork(device, input_size, n, m, qp_iter, None, True, True, force_feasible=forced_feasibility) if parametric_uncertainty: exp_name += "+rand" checkpoint_path = f"runs/tank_{exp_name}/nn/tank.pth" policy_net_state_dict, running_mean, running_std = get_state_dict(checkpoint_path) net.load_state_dict(policy_net_state_dict) running_mean, running_std = running_mean.to(device=device), running_std.to(device=device) net.to(device) return net, running_mean, running_std def compute_violation(H, action_all, b): """ Number of violated constraints, as well as magnitude of constraint violation. """ z_recovered = bmv(H, action_all) + b violation_count = (z_recovered < 0.).sum(dim=-1) violation_magnitude = torch.norm(z_recovered.clamp(-torch.inf, 0.), dim=-1) return violation_count, violation_magnitude def rollout(trained_with_residual_loss, is_mpc, steps, forced_feasibility=False): net, running_mean, running_std = get_qp_net(trained_with_residual_loss, forced_feasibility) if is_mpc: net = mpc_module results = [] env.reset(t(x0), t(x_ref), randomize_seed=parameter_randomization_seed) x = x0 obs = make_obs(x, x_ref, running_mean, running_std, not is_mpc) for i in range(steps): action_all, problem_params = net(obs, return_problem_params=True) u = rescale_action(action_all[:, :m_sys]) raw_obs, reward, done_t, info = env.step(u) if not is_mpc: obs = (raw_obs - running_mean) / running_std else: obs = raw_obs done = done_t.item() P, q, H, b = problem_params results.append((P, q, H, b, action_all)) return results def evaluate_constraint_violation(trained_with_residual_loss, steps=10, forced_feasibility=False): """Rollout for multiple steps, and compute average (number of violated constraints, magnitude of violation).""" rollout_results = rollout(trained_with_residual_loss, False, steps, forced_feasibility) constraint_violation_indices = [] for i in range(steps): H = rollout_results[i][2] action_all = rollout_results[i][4] b = rollout_results[i][3] constraint_violation_indices.append(compute_violation(H, action_all, b)) average_violation_count = torch.stack([v[0] for v in constraint_violation_indices], dim=0).to(dtype=torch.float).mean(dim=0) average_violation_magnitude = torch.stack([v[1] for v in constraint_violation_indices], dim=0).mean(dim=0) return average_violation_count, average_violation_magnitude violation_count_with_residual_loss, violation_magnitude_with_residual_loss = evaluate_constraint_violation(True) violation_count_without_residual_loss, violation_magnitude_without_residual_loss = evaluate_constraint_violation(False) ic(violation_count_with_residual_loss, violation_count_without_residual_loss) ic(violation_magnitude_with_residual_loss, violation_magnitude_without_residual_loss) # %% Visualize the feasible set and objective function at a certain step, ignoring constraints that are violated at_step = 10 def get_violated_mask(H, action_all, b): z_recovered = bmv(H, action_all) + b return torch.where(z_recovered < 0., torch.ones_like(z_recovered), torch.zeros_like(z_recovered)) def get_step_parameters(at_step, trained_with_residual_loss, is_mpc, forced_feasibility=False): rollout_results = rollout(trained_with_residual_loss, is_mpc, at_step, forced_feasibility) result_last_step = rollout_results[-1] P, q, H, b, action_all = result_last_step violated_mask = get_violated_mask(H, action_all, b) return P, q, H, b, violated_mask, action_all def get_plot_parameters(trained_with_residual_loss, is_mpc, color, label, is_forced_feasibility=False): a = lambda t: t.squeeze(0).detach().cpu().numpy() global P, q, H, b, violated_mask, action_all P, q, H, b, violated_mask, action_all = get_step_parameters(at_step, trained_with_residual_loss, is_mpc, is_forced_feasibility) if not is_forced_feasibility: # Filter out violated constraints satisfied_mask = torch.logical_not(violated_mask) plot_params = { "A": a(-H[satisfied_mask, :]), "b": a(b[satisfied_mask]), "optimal_solution": a(action_all[:, :m_sys]), "P": a(P), "q": a(q), "color": color, "label": label, } else: # Learned problem with forced feasibility; recover original P, q, H, b from augmented P, q, H, b y = action_all[:, -1].item() P0 = P[:, :n, :n] q0 = q[:, :n] H0 = H[:, :m, :n] b0 = b[:, :m] + y plot_params = { "A": a(-H0), "b": a(b0), "optimal_solution": a(action_all[:, :m_sys]), "P": a(P0), "q": a(q0), "color": color, "label": label, } return plot_params fig, ax = plot_multiple_2d_polytopes_with_contour([ get_plot_parameters(True, False, "blue", "Learned QP (with residual loss)"), get_plot_parameters(False, False, "red", "Learned QP (w/o residual loss)"), get_plot_parameters(False, True, "green", "MPC") ]) ax.set_xlabel("$u_1$") ax.set_ylabel("$u_2$") ax.set_title(f"Feasible sets and objective functions at step {at_step}") # %% Visualize the feasible set and objective function at a certain step, forcing feasibility fig, ax = plot_multiple_2d_polytopes_with_contour([ get_plot_parameters(True, False, "blue", "Learned QP (forced feasibility, n=2)", True), get_plot_parameters(False, True, "green", "MPC (N=1)", True) ]) ax.set_xlabel("$u_1$") ax.set_ylabel("$u_2$") ax.set_title(f"Feasible sets and objective functions at step {at_step}") # %% Visualize feasible set vs. MPC; Now # 1. The learned QP is guaranteed to be feasible; no need to ignore violated constraints # 2. The variable are allowed to be high-dimensional; we project the constraint polytope and the quadratic objective to 2D n = 8 m = 32 mpc_N = 4 at_step = 50 mpc_baseline = get_mpc_baseline_parameters("tank", mpc_N) mpc_baseline["normalize"] = True # Solve for normalized action, to be consistent with learned QP mpc_module = QPUnrolledNetwork( device, input_size, n, m, qp_iter, None, True, True, mpc_baseline=mpc_baseline, use_osqp_for_mpc=True, ) def get_plot_parameters_proj(is_mpc, color, label): a = lambda t: t.squeeze(0).detach().cpu().numpy() P, q, H, b, violated_mask, action_all = get_step_parameters(at_step, False, is_mpc, True) if not is_mpc: # Learned problem with forced feasibility; recover original P, q, H, b from augmented P, q, H, b y = action_all[:, -1].item() P0 = P[:, :n, :n] q0 = q[:, :n] H0 = H[:, :m, :n] b0 = b[:, :m] + y else: P0, q0, H0, b0 = P, q, H, b A_proj, b_proj = high_dim_to_2D_sampling(-a(H0), a(b0))
P_proj, q_proj, _ = partial_minimization_2D(a(P0), a(q0))
6
2023-11-28 05:56:22+00:00
16k
Fraunhofer-SCAI/llamol
sample.py
[ { "identifier": "Transformer", "path": "model.py", "snippet": "class Transformer(nn.Module):\n last_loss: Optional[torch.Tensor]\n\n def __init__(self, params: ModelArgs, context_params: ContextArgs):\n super().__init__()\n self.params = params\n self.context_params = context_...
import os import sys import time import pandas as pd import torch import numpy as np import re import logging import argparse import rdkit.rdBase as rkrb import rdkit.RDLogger as rkl from contextlib import nullcontext from tqdm.auto import tqdm from model import Transformer from plot_utils import ( check_metrics, plot_1D_condition, plot_2D_condition, plot_3D_condition, plot_unconditional, ) from tokenizer import SmilesTokenizer from typing import Dict, List, Tuple, Union from rdkit import Chem from rdkit import DataStructs from rdkit.Chem.Fingerprints import FingerprintMols
13,302
gens_per_step = num_samples // total_gen_steps logger.debug(f"Gens per Step: {gens_per_step}") context = None # {"context": None, "fragment" : None} out_smiles = [] with tqdm(total=total_gen_steps, desc="Batch") as pbar: for i in range(total_gen_steps): if isinstance(context_cols, dict): # TODO: Test if same length cd = { c: context_cols[c][ i * gens_per_step : (i + 1) * gens_per_step ] for c in context_cols.keys() } context_dict = {"context": cd, "fragment": None} if context_smi is not None: logger.debug( f"context_smiles: {context_smi}", ) # NOTE: Remove beginning [CLS] and end token [SEP] incorporate_selfie = self.tokenizer.encode(context_smi)[ 1:-1 ] context_tensor = torch.tensor( [incorporate_selfie] * gens_per_step, dtype=torch.long, device=self.device, ) context_dict["fragment"] = context_tensor context_cols = list(context_cols.keys()) else: context_dict = self.get_context( context_cols, context_smi, num_examples=gens_per_step ) # for k in range(num_samples): y = self.model.generate( self.tokenizer, context=context_dict["context"], fragments=context_dict["fragment"], start_smiles=start_smiles, num_gen=gens_per_step, temperature=temperature, top_k=top_k, max_length=max_new_tokens, device=self.device, cache_kv=use_kv_cache, ) new_context = {k: [] for k in context_dict["context"]} for i, sample in enumerate(y): # print(sample) mol = Chem.MolFromSmiles(sample) if mol is not None: out_smiles.append(sample) for k in new_context: new_context[k].append( context_dict["context"][k][i].unsqueeze(-1) ) for k in new_context: new_context[k] = torch.concat(new_context[k], dim=0) if context is None: context = new_context else: for k in context: context[k] = torch.concat( [context[k], new_context[k]], dim=0 ) pbar.update(1) logger.info( f"Number valid generated: {len(out_smiles) / num_samples * 100} %" ) logger.info("---------------") if return_context: return (out_smiles, context) else: return out_smiles @torch.no_grad() def generate_with_evaluation( self, context_cols: Union[List[str], None] = None, context_smi: Union[str, None] = None, start_smiles: Union[str, None] = None, num_samples: int = 50, max_new_tokens: int = 256, temperature: float = 1.0, top_k: Union[int, None] = None, cmp_context_dict: Union[Dict[str, torch.Tensor], None] = None, total_gen_steps: int = 1, use_kv_cache: bool = False, ): out_smiles, new_context = self.generate( context_cols=context_cols, context_smi=context_smi, start_smiles=start_smiles, num_samples=num_samples, max_new_tokens=max_new_tokens, temperature=temperature, top_k=top_k, return_context=True, total_gen_steps=total_gen_steps, use_kv_cache=use_kv_cache, ) out_dir = os.path.dirname(self.load_path) if context_cols is not None: if len(context_cols) == 1:
# from tqdm.notebook import tqdm logger = logging.getLogger(__name__) class Sampler: def __init__( self, load_path: str, device: str = "cpu", seed: int = 1337, dtype: str = "float16", compile: bool = True, quantize: bool = False, ) -> None: self.load_path = load_path self.device = device self.dtype = dtype self.compile = compile self.quantize = quantize self.seed = seed self._init_model() def _init_model(self): np.random.seed(self.seed) torch.cuda.manual_seed(self.seed) torch.backends.cuda.matmul.allow_tf32 = True # allow tf32 on matmul torch.backends.cudnn.allow_tf32 = True # allow tf32 on cudnn self.device_type = ( "cuda" if "cuda" in self.device else "cpu" ) # for later use in torch.autocast ptdtype = { "float32": torch.float32, "bfloat16": torch.bfloat16, "float16": torch.float16, }[self.dtype] self.ptdtype = ptdtype self.ctx = self._autocast() # init from a model saved in a specific directory # ckpt_path = os.path.join(out_dir, "ckpt_full_dim=256.pt") self.model = Transformer.load(self.load_path, device=self.device) self.model.eval() if self.quantize: raise NotImplementedError("Not properly implemented for CPU / GPU") self.model = torch.ao.quantization.quantize_dynamic( self.model, # the original model {torch.nn.Linear}, # a set of layers to dynamically quantize dtype=torch.qint8, ) if self.compile: logger.info("Compiling the model...") self.model = torch.compile(self.model) # requires PyTorch 2.0 (optional) self.model = self.model.to(self.device) # load the tokenizer self.tokenizer = SmilesTokenizer() def get_context( self, context_col: List[str], context_smi: str, num_examples: int = 50, ): """ Returns a dictionary in the form of { "fragment": torch.tensor, "context": { "logp": torch.tensor, "sascore": torch.tensor, "mol_weight": torch.tensor } } When context_smi is set to a string, then the "fragment" field is populated. All of the properties listed in the context_col list is set to the keys and the values are set to a resonable range for each property. num_examples indicates how many values are sampled for each property. """ output_dict = {"context": {}, "fragment": None} if context_smi is not None: logger.debug( f"context_smiles: {context_smi}", ) # NOTE: Remove beginning [CLS] and end token [SEP] incorporate_selfie = self.tokenizer.encode(context_smi)[1:-1] context = torch.tensor( [incorporate_selfie] * num_examples, dtype=torch.long, device=self.device, ) output_dict["fragment"] = context if context_col is None: return output_dict if "logp" in context_col: # context = 0.5 * torch.randint( # -8, 14, (num_examples,), device=self.device, dtype=torch.float # ) # context = 0.5 * torch.randint( # -6, 6, (num_examples, 1), device=device, dtype=torch.float # ) context = torch.tensor( np.random.choice([-2, 0, 2], (num_examples,)), device=self.device, dtype=self.ptdtype, ) # context = 2.0 * torch.ones( # (num_examples,1), device=device, dtype=torch.float # ) # context = -2.0*torch.ones((num_examples,2),device=device,dtype=torch.float) # context, _ = torch.sort(context, 0) output_dict["context"]["logp"] = context if "energy" in context_col: context = 0.1 * torch.randint( -15, 15, (num_examples,), device=self.device, dtype=torch.float ) # context = -2.0*torch.ones((num_examples,2),device=device,dtype=torch.float) context, _ = torch.sort(context, 0) output_dict["context"]["energy"] = context if "sascore" in context_col: # context = 0.5 * torch.randint( # 2, 20, (num_examples, ), device=self.device, dtype=torch.float # ) context = torch.tensor( np.random.choice([2, 3, 4], (num_examples,)), device=self.device, dtype=torch.float, ) # context = 0.5 * torch.randint( # 4, 8, (num_examples, 1), device=device, dtype=torch.float # ) # context = 2.0*torch.ones((num_examples,1),device=device,dtype=torch.float) # context, _ = torch.sort(context, 0) output_dict["context"]["sascore"] = context if "mol_weight" in context_col: # context = 0.5 * torch.randint( # 2, 20, (num_examples,), device=self.device, dtype=torch.float # ) context = torch.tensor( np.random.choice([2.0, 3.0, 4.0], (num_examples,)), device=self.device, dtype=torch.float, ) # context = 0.5 * torch.randint( # 2, 20, (num_examples, 1), device=device, dtype=torch.float # ) # context = 2.5*torch.ones((num_examples,1),device=device,dtype=torch.float) # context, _ = torch.sort(context, 0) output_dict["context"]["mol_weight"] = context return output_dict def _autocast(self): if "cuda" in self.device: if self.dtype == "bfloat16" and torch.cuda.is_bf16_supported(): return torch.cuda.amp.autocast(dtype=torch.bfloat16) elif self.dtype == "float16": return torch.cuda.amp.autocast(dtype=torch.float16) else: return torch.cuda.amp.autocast(dtype=torch.float32) else: # cpu return nullcontext() @torch.no_grad() def generate( self, context_cols: Union[List[str], None, Dict[str, torch.Tensor]] = None, context_smi: Union[str, None] = None, start_smiles: Union[str, None] = None, num_samples: int = 50, max_new_tokens: int = 256, temperature: float = 1.0, top_k: Union[int, None] = None, return_context: bool = False, total_gen_steps: int = 1, use_kv_cache: bool = False, ) -> Union[List[str], Tuple[List[str], List[float]]]: """ Generates a list of SMILES. With the default options it would generate them unconditionally. Params: - context_cols : When a list the context is randomly sampled from the get_context method, when given a dictionary the context values are taken from the dictionary instead. - context_smi : Further conditioning by the usage of a molecular fragment . start_smiles : Can be used to start the SMILES with a specific string, the model then generates the next tokens including that start sequence. - num_samples : Controlls how many SMILES in total will be generated be the model. - max_new_tokens : Controlls the maximum length of each SMILES (in tokens) that is generated. - temperature: Controlls the randomness of the model. A temperature = 1.0 means it is the trained distribution. A temperature < 1 is more deterministic and temperature > 1 is more random - top_k : Clamps the probability distribution to the top k tokens. From these the next token is then sampled from. - return_context : Whether the context that was given to the model should be returned. - total_gen_steps : In how many sub steps the generation should be split up to. Useful when generation 10k + SMILES and wanting to chunk these into for example 10 * 1k generations with total_gen_steps = 10. - use_kv_cache: Runs the generation using kv-caching. It is faster, but takes more memory. """ with self.ctx: gens_per_step = num_samples // total_gen_steps logger.debug(f"Gens per Step: {gens_per_step}") context = None # {"context": None, "fragment" : None} out_smiles = [] with tqdm(total=total_gen_steps, desc="Batch") as pbar: for i in range(total_gen_steps): if isinstance(context_cols, dict): # TODO: Test if same length cd = { c: context_cols[c][ i * gens_per_step : (i + 1) * gens_per_step ] for c in context_cols.keys() } context_dict = {"context": cd, "fragment": None} if context_smi is not None: logger.debug( f"context_smiles: {context_smi}", ) # NOTE: Remove beginning [CLS] and end token [SEP] incorporate_selfie = self.tokenizer.encode(context_smi)[ 1:-1 ] context_tensor = torch.tensor( [incorporate_selfie] * gens_per_step, dtype=torch.long, device=self.device, ) context_dict["fragment"] = context_tensor context_cols = list(context_cols.keys()) else: context_dict = self.get_context( context_cols, context_smi, num_examples=gens_per_step ) # for k in range(num_samples): y = self.model.generate( self.tokenizer, context=context_dict["context"], fragments=context_dict["fragment"], start_smiles=start_smiles, num_gen=gens_per_step, temperature=temperature, top_k=top_k, max_length=max_new_tokens, device=self.device, cache_kv=use_kv_cache, ) new_context = {k: [] for k in context_dict["context"]} for i, sample in enumerate(y): # print(sample) mol = Chem.MolFromSmiles(sample) if mol is not None: out_smiles.append(sample) for k in new_context: new_context[k].append( context_dict["context"][k][i].unsqueeze(-1) ) for k in new_context: new_context[k] = torch.concat(new_context[k], dim=0) if context is None: context = new_context else: for k in context: context[k] = torch.concat( [context[k], new_context[k]], dim=0 ) pbar.update(1) logger.info( f"Number valid generated: {len(out_smiles) / num_samples * 100} %" ) logger.info("---------------") if return_context: return (out_smiles, context) else: return out_smiles @torch.no_grad() def generate_with_evaluation( self, context_cols: Union[List[str], None] = None, context_smi: Union[str, None] = None, start_smiles: Union[str, None] = None, num_samples: int = 50, max_new_tokens: int = 256, temperature: float = 1.0, top_k: Union[int, None] = None, cmp_context_dict: Union[Dict[str, torch.Tensor], None] = None, total_gen_steps: int = 1, use_kv_cache: bool = False, ): out_smiles, new_context = self.generate( context_cols=context_cols, context_smi=context_smi, start_smiles=start_smiles, num_samples=num_samples, max_new_tokens=max_new_tokens, temperature=temperature, top_k=top_k, return_context=True, total_gen_steps=total_gen_steps, use_kv_cache=use_kv_cache, ) out_dir = os.path.dirname(self.load_path) if context_cols is not None: if len(context_cols) == 1:
plot_1D_condition(
2
2023-11-28 09:50:31+00:00
16k
lampmerchant/tashrouter
tashrouter/router/router.py
[ { "identifier": "RoutingTable", "path": "tashrouter/router/routing_table.py", "snippet": "class RoutingTable:\n '''A Router's routing table.'''\n \n STATE_GOOD = 1\n STATE_SUS = 2\n STATE_BAD = 3\n STATE_WORST = 4\n \n def __init__(self, router):\n self._router = router\n self._entry_by_ne...
import logging from .routing_table import RoutingTable from .zone_information_table import ZoneInformationTable from ..datagram import Datagram from ..service.echo import EchoService from ..service.name_information import NameInformationService from ..service.routing_table_aging import RoutingTableAgingService from ..service.rtmp.responding import RtmpRespondingService from ..service.rtmp.sending import RtmpSendingService from ..service.zip.responding import ZipRespondingService from ..service.zip.sending import ZipSendingService
11,960
'''The heart of this whole affair.''' class Router: '''A router, a device which sends Datagrams to Ports and runs Services.''' def __init__(self, short_str, ports): self._short_str = short_str self.ports = ports self._services = (
'''The heart of this whole affair.''' class Router: '''A router, a device which sends Datagrams to Ports and runs Services.''' def __init__(self, short_str, ports): self._short_str = short_str self.ports = ports self._services = (
(EchoService.ECHO_SAS, EchoService()),
3
2023-12-02 15:17:07+00:00
16k
jags111/ComfyUI_Jags_Audiotools
libs/dance_diffusion/dd/inference.py
[ { "identifier": "SchedulerType", "path": "libs/diffusion_library/scheduler.py", "snippet": "class SchedulerType(str, enum.Enum):\n V_DDPM = 'V_DDPM'\n V_SPLICED_DDPM_COSINE = 'V_SPLICED_DDPM_COSINE'\n V_LOG = 'V_LOG'\n V_CRASH = 'V_CRASH'\n \n K_KARRAS = 'K_KARRAS'\n K_EXPONENTIAL =...
import torch from tqdm.auto import trange from diffusion.utils import t_to_alpha_sigma from k_diffusion.external import VDenoiser from typing import Tuple, Callable from libs.diffusion_library.scheduler import SchedulerType from libs.diffusion_library.sampler import SamplerType from libs.dance_diffusion.base.model import ModelWrapperBase from libs.dance_diffusion.base.inference import InferenceBase from libs.util.util import tensor_slerp_2D, PosteriorSampling from typing import Tuple, Callable from libs.diffusion_library.scheduler import SchedulerType from libs.diffusion_library.sampler import SamplerType from libs.dance_diffusion.base.model import ModelWrapperBase from libs.dance_diffusion.base.inference import InferenceBase from libs.util.util import tensor_slerp_2D, PosteriorSampling
10,836
x_T, step_list, callback, **sampler_args ).float() def generate_variation( self, callback: Callable = None, batch_size: int = None, seed: int = None, audio_source: torch.Tensor = None, expansion_map: list[int] = None, noise_level: float = None, steps: int = None, scheduler: SchedulerType = None, scheduler_args = None, sampler: SamplerType = None, sampler_args = None, **kwargs ) -> torch.Tensor: self.generator.manual_seed(seed) audio_source = self.expand(audio_source, expansion_map) if SamplerType.is_v_sampler(sampler): step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) step_list = step_list[step_list < noise_level] alpha_T, sigma_T = t_to_alpha_sigma(step_list[0]) x_T = alpha_T * audio_source + sigma_T * torch.randn(audio_source.shape, device=audio_source.device, generator=self.generator) model = self.model.model else: scheduler_args.update(sigma_max = scheduler_args.get('sigma_max', 1.0) * noise_level) step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) x_T = audio_source + step_list[0] * torch.randn(audio_source.shape, device=audio_source.device, generator=self.generator) model = VDenoiser(self.model.model) with self.offload_context(self.model.model): return sampler.sample( model, x_T, step_list, callback, **sampler_args ).float() def generate_interpolation( self, callback: Callable = None, batch_size: int = None, # seed: int = None, interpolation_positions: list[float] = None, audio_source: torch.Tensor = None, audio_target: torch.Tensor = None, expansion_map: list[int] = None, noise_level: float = None, steps: int = None, scheduler: SchedulerType = None, scheduler_args = None, sampler: SamplerType = None, sampler_args = None, **kwargs ) -> torch.Tensor: if SamplerType.is_v_sampler(sampler): step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) step_list = step_list[step_list < noise_level] step_list[-1] += 1e-7 #HACK avoid division by 0 in reverse sampling model = self.model.model else: scheduler_args.update(sigma_max = scheduler_args.get('sigma_max', 1.0) * noise_level) step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) step_list = step_list[:-1] #HACK avoid division by 0 in reverse sampling model = VDenoiser(self.model.model) if self.optimize_memory_use and batch_size < 2: x_0_source = audio_source x_0_target = audio_target with self.offload_context(self.model.model): x_T_source = sampler.sample( model, x_0_source, step_list.flip(0), callback, **sampler_args ) with self.offload_context(self.model.model): x_T_target = sampler.sample( model, x_0_target, step_list.flip(0), callback, **sampler_args ) x_T = torch.cat([x_T_source, x_T_target], dim=0) else: x_0 = torch.cat([audio_source, audio_target], dim=0) with self.offload_context(self.model.model): x_T = sampler.sample( model, x_0, step_list.flip(0), callback, **sampler_args ) if SamplerType.is_v_sampler(sampler): #HACK reset schedule after hack step_list[-1] = 0.0 else: step_list = torch.cat([step_list, step_list.new_zeros([1])]) x_Int = torch.empty([batch_size, 2, self.model.chunk_size], device=self.device_accelerator) for pos in range(len(interpolation_positions)):
class DDInference(InferenceBase): def __init__( self, device_accelerator: torch.device = None, device_offload: torch.device = None, optimize_memory_use: bool = False, use_autocast: bool = True, model: ModelWrapperBase = None ): super().__init__(device_accelerator, device_offload, optimize_memory_use, use_autocast, model) def generate( self, callback: Callable = None, batch_size: int = None, seed: int = None, steps: int = None, scheduler: SchedulerType = None, scheduler_args: dict = None, sampler: SamplerType = None, sampler_args: dict = None, **kwargs ): self.generator.manual_seed(seed) step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args)#step_list = step_list[:-1] if sampler in [SamplerType.V_PRK, SamplerType.V_PLMS, SamplerType.V_PIE, SamplerType.V_PLMS2, SamplerType.V_IPLMS] else step_list if SamplerType.is_v_sampler(sampler): x_T = torch.randn([batch_size, 2, self.model.chunk_size], generator=self.generator, device=self.device_accelerator) model = self.model.model else: x_T = step_list[0] * torch.randn([batch_size, 2, self.model.chunk_size], generator=self.generator, device=self.device_accelerator) model = VDenoiser(self.model.model) with self.offload_context(self.model.model): return sampler.sample( model, x_T, step_list, callback, **sampler_args ).float() def generate_variation( self, callback: Callable = None, batch_size: int = None, seed: int = None, audio_source: torch.Tensor = None, expansion_map: list[int] = None, noise_level: float = None, steps: int = None, scheduler: SchedulerType = None, scheduler_args = None, sampler: SamplerType = None, sampler_args = None, **kwargs ) -> torch.Tensor: self.generator.manual_seed(seed) audio_source = self.expand(audio_source, expansion_map) if SamplerType.is_v_sampler(sampler): step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) step_list = step_list[step_list < noise_level] alpha_T, sigma_T = t_to_alpha_sigma(step_list[0]) x_T = alpha_T * audio_source + sigma_T * torch.randn(audio_source.shape, device=audio_source.device, generator=self.generator) model = self.model.model else: scheduler_args.update(sigma_max = scheduler_args.get('sigma_max', 1.0) * noise_level) step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) x_T = audio_source + step_list[0] * torch.randn(audio_source.shape, device=audio_source.device, generator=self.generator) model = VDenoiser(self.model.model) with self.offload_context(self.model.model): return sampler.sample( model, x_T, step_list, callback, **sampler_args ).float() def generate_interpolation( self, callback: Callable = None, batch_size: int = None, # seed: int = None, interpolation_positions: list[float] = None, audio_source: torch.Tensor = None, audio_target: torch.Tensor = None, expansion_map: list[int] = None, noise_level: float = None, steps: int = None, scheduler: SchedulerType = None, scheduler_args = None, sampler: SamplerType = None, sampler_args = None, **kwargs ) -> torch.Tensor: if SamplerType.is_v_sampler(sampler): step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) step_list = step_list[step_list < noise_level] step_list[-1] += 1e-7 #HACK avoid division by 0 in reverse sampling model = self.model.model else: scheduler_args.update(sigma_max = scheduler_args.get('sigma_max', 1.0) * noise_level) step_list = scheduler.get_step_list(steps, self.device_accelerator.type, **scheduler_args) step_list = step_list[:-1] #HACK avoid division by 0 in reverse sampling model = VDenoiser(self.model.model) if self.optimize_memory_use and batch_size < 2: x_0_source = audio_source x_0_target = audio_target with self.offload_context(self.model.model): x_T_source = sampler.sample( model, x_0_source, step_list.flip(0), callback, **sampler_args ) with self.offload_context(self.model.model): x_T_target = sampler.sample( model, x_0_target, step_list.flip(0), callback, **sampler_args ) x_T = torch.cat([x_T_source, x_T_target], dim=0) else: x_0 = torch.cat([audio_source, audio_target], dim=0) with self.offload_context(self.model.model): x_T = sampler.sample( model, x_0, step_list.flip(0), callback, **sampler_args ) if SamplerType.is_v_sampler(sampler): #HACK reset schedule after hack step_list[-1] = 0.0 else: step_list = torch.cat([step_list, step_list.new_zeros([1])]) x_Int = torch.empty([batch_size, 2, self.model.chunk_size], device=self.device_accelerator) for pos in range(len(interpolation_positions)):
x_Int[pos] = tensor_slerp_2D(x_T[0], x_T[1], interpolation_positions[pos])
10
2023-11-28 09:09:59+00:00
16k
Matrixeigs/UncertaintyManagementInteroperablePowerTransportationSystems
TestCaseDistributionSystems/uc_mmgs_tess_pv_stochastic.py
[ { "identifier": "case33", "path": "TestCaseDistributionSystems/test_cases/case33.py", "snippet": "def case33():\n \"\"\"Power flow data for 33 bus, 6 generator case.\n Please see L{caseformat} for details on the case file format.\n\n Based on data from ...\n\n Alsac, O. & Stott, B., I{\"Opti...
from TestCaseDistributionSystems.test_cases import case33 from TestCasesMicrogrids.test_cases.cases_unit_commitment import micro_grid from TestCasesTransportationSystems.test_cases import case3, TIME, LOCATION from numpy import zeros, shape, ones, diag, concatenate, eye from scipy.sparse import csr_matrix as sparse from scipy.sparse import hstack, vstack, lil_matrix from numpy import flatnonzero as find from numpy import array, tile, arange, random from pypower.idx_brch import F_BUS, T_BUS, BR_R, BR_X, RATE_A from pypower.idx_bus import PD, VMAX, VMIN, QD from pypower.idx_gen import GEN_BUS, PMAX, PMIN, QMAX, QMIN from pypower.ext2int import ext2int from Solvers.mixed_integer_quadratic_constrained_cplex import mixed_integer_quadratic_constrained_programming as miqcp from Solvers.mixed_integer_solvers_cplex import mixed_integer_linear_programming as milp from copy import deepcopy from TestCaseDistributionSystems.data_format.idx_MG_PV import PBIC_AC2DC, PG, PESS_DC, PBIC_DC2AC, PUG, PESS_CH, \ PMESS, EESS, NX_MG, QBIC, QUG, QG, PPV from TestCaseDistributionSystems.database_management_pv import DataBaseManagement from StochasticOptimization.scenario_reduction import ScenarioReduction
12,823
self.name = "Unit commitment with tess" def main(self, power_networks, micro_grids, profile, pv_profile, mess, traffic_networks, ns=100): """ Main entrance for network reconfiguration problems :param case: electric network information :param profile: load profile within the distribution networks :param micrgrids: dictionary for microgrids :param tess: dictionary for tess :return: network reconfiguration, distribution network status, and microgrid status """ T = len(profile) # Time spans self.T = T nmg = len(micro_grids) # Number of microgrids self.nmg = nmg nmes = len(mess) # Number of mobile energy storage systems self.nmes = nmes nb_tra = traffic_networks["bus"].shape[0] # Number of buses in the transportation networks self.nb_tra = nb_tra assert nb_tra == nmg, "The microgrids within the transportation networks are not synchronized!" # 1) Formulate the first stage optimization problem model_first_stage = self.first_stage_problem_formulation(pns=power_networks, mgs=micro_grids, mess=mess, tns=traffic_networks) # (sol_first_stage, obj, success) = milp(model_first_stage["c"], Aeq=model_first_stage["Aeq"], # beq=model_first_stage["beq"], # A=model_first_stage["A"], b=model_first_stage["b"], # vtypes=model_first_stage["vtypes"], # xmax=model_first_stage["ub"], xmin=model_first_stage["lb"]) # sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 2) Formulate the second stage optimization problem # Formulate the second stage scenarios (ds_second_stage, mgs_second_stage, weight) = self.scenario_generation_reduction(profile=profile, micro_grids=micro_grids, ns=ns, pns=power_networks, pv_profile=pv_profile, ns_reduced=round(0.98 * ns)) ns -= round(0.98 * ns) model_second_stage = {} for i in range(ns): model_second_stage[i] = self.second_stage_problem_formualtion(pns=power_networks, mgs=mgs_second_stage[i], mess=mess, tns=traffic_networks, profile=ds_second_stage[i, :], index=i, weight=weight[i]) # 3) Merge the first-stage problem and second stage problem lb = model_first_stage["lb"] ub = model_first_stage["ub"] vtypes = model_first_stage["vtypes"] c = model_first_stage["c"] Qc = dict() if model_first_stage["Aeq"] is not None: neq = model_first_stage["Aeq"].shape[0] else: neq = 0 if model_first_stage["A"] is not None: nineq = model_first_stage["A"].shape[0] else: nineq = 0 nv_first_stage = self.nv_first_stage nv_second_stage = self.nv_second_stage q = zeros(nv_first_stage) nv_index = zeros(ns + 1).astype(int) neq_index = zeros(ns + 1).astype(int) nineq_index = zeros(ns + 1).astype(int) neq_index[0] = neq nineq_index[0] = nineq nv_index[0] = nv_first_stage beq = model_first_stage["beq"] for i in range(ns): if model_second_stage[i]["Aeq"] is not None: neq_index[i + 1] = neq_index[i] + model_second_stage[i]["Aeq"].shape[0] else: neq_index[i + 1] = neq_index[i] if model_second_stage[i]["Ts"] is not None: nineq_index[i + 1] = nineq_index[i] + model_second_stage[i]["Ts"].shape[0] else: nineq_index[i + 1] = nineq_index[i] nv_index[i + 1] = nv_index[i] + nv_second_stage c = concatenate([c, model_second_stage[i]["c"]]) q = concatenate([q, model_second_stage[i]["q"]]) lb = concatenate([lb, model_second_stage[i]["lb"]]) ub = concatenate([ub, model_second_stage[i]["ub"]]) vtypes += model_second_stage[i]["vtypes"] beq = concatenate([beq, model_second_stage[i]["beq"]]) Aeq_full = lil_matrix((neq_index[-1], nv_index[-1])) Aeq_full[0:neq_index[0], 0:nv_index[0]] = model_first_stage["Aeq"] rc = zeros(0) for i in range(ns): Aeq_full[neq_index[i]:neq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Aeq"] Qc.update(model_second_stage[i]["Qc"]) rc = concatenate([rc, model_second_stage[i]["rc"]]) A_full = lil_matrix((nineq_index[-1], nv_index[-1])) b = model_first_stage["b"] A_full[0:int(nineq_index[0]), 0:int(nv_index[0])] = model_first_stage["A"] for i in range(ns): A_full[nineq_index[i]:nineq_index[i + 1], 0:nv_index[0]] = model_second_stage[i]["Ts"] A_full[nineq_index[i]:nineq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Ws"] b = concatenate([b, model_second_stage[i]["hs"]]) # 3) Obtain the results for first-stage and second stage optimization problems # 3.1) Obtain the integrated solution (sol, obj, success) = miqcp(c, q, Aeq=Aeq_full, beq=beq, A=A_full, b=b, Qc=Qc, rc=rc, xmin=lb, xmax=ub, vtypes=vtypes) # 3.2) decouple the solution into multiple subsystems sol_first_stage = sol[0:nv_second_stage] sol_second_stage = {} for i in range(ns): sol_second_stage[i] = sol[int(nv_index[i]):int(nv_index[i + 1])] # 4) Verify the first-stage and second stage optization problem # 4.1) First-stage solution sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 4.2) Second-stage solution sol_second_stage_checked = {}
""" Stochastic optimal power flow with multiple microgrids and mobile energy storage systems @author: Zhao Tianyang @e-mail: zhaoty@ntu.edu.sg @date: 10 Jan 2019 Major updates: 1) Update code style using PEP 8 -- Style Guide for Python Code 2) Store data in database 3) Scenario generation and reduction 4) Automatic results analysis Nomenclature: nV: number of variables mg: microgrid ds: distribution systems me: mobile energy storage systems ch: charging dc: discharging ele: electricity tra: traffic i,j,k: index t: time index T: time periods tns:traffic networks pns:power networks """ class StochasticDynamicOptimalPowerFlowTess(): def __init__(self): self.name = "Unit commitment with tess" def main(self, power_networks, micro_grids, profile, pv_profile, mess, traffic_networks, ns=100): """ Main entrance for network reconfiguration problems :param case: electric network information :param profile: load profile within the distribution networks :param micrgrids: dictionary for microgrids :param tess: dictionary for tess :return: network reconfiguration, distribution network status, and microgrid status """ T = len(profile) # Time spans self.T = T nmg = len(micro_grids) # Number of microgrids self.nmg = nmg nmes = len(mess) # Number of mobile energy storage systems self.nmes = nmes nb_tra = traffic_networks["bus"].shape[0] # Number of buses in the transportation networks self.nb_tra = nb_tra assert nb_tra == nmg, "The microgrids within the transportation networks are not synchronized!" # 1) Formulate the first stage optimization problem model_first_stage = self.first_stage_problem_formulation(pns=power_networks, mgs=micro_grids, mess=mess, tns=traffic_networks) # (sol_first_stage, obj, success) = milp(model_first_stage["c"], Aeq=model_first_stage["Aeq"], # beq=model_first_stage["beq"], # A=model_first_stage["A"], b=model_first_stage["b"], # vtypes=model_first_stage["vtypes"], # xmax=model_first_stage["ub"], xmin=model_first_stage["lb"]) # sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 2) Formulate the second stage optimization problem # Formulate the second stage scenarios (ds_second_stage, mgs_second_stage, weight) = self.scenario_generation_reduction(profile=profile, micro_grids=micro_grids, ns=ns, pns=power_networks, pv_profile=pv_profile, ns_reduced=round(0.98 * ns)) ns -= round(0.98 * ns) model_second_stage = {} for i in range(ns): model_second_stage[i] = self.second_stage_problem_formualtion(pns=power_networks, mgs=mgs_second_stage[i], mess=mess, tns=traffic_networks, profile=ds_second_stage[i, :], index=i, weight=weight[i]) # 3) Merge the first-stage problem and second stage problem lb = model_first_stage["lb"] ub = model_first_stage["ub"] vtypes = model_first_stage["vtypes"] c = model_first_stage["c"] Qc = dict() if model_first_stage["Aeq"] is not None: neq = model_first_stage["Aeq"].shape[0] else: neq = 0 if model_first_stage["A"] is not None: nineq = model_first_stage["A"].shape[0] else: nineq = 0 nv_first_stage = self.nv_first_stage nv_second_stage = self.nv_second_stage q = zeros(nv_first_stage) nv_index = zeros(ns + 1).astype(int) neq_index = zeros(ns + 1).astype(int) nineq_index = zeros(ns + 1).astype(int) neq_index[0] = neq nineq_index[0] = nineq nv_index[0] = nv_first_stage beq = model_first_stage["beq"] for i in range(ns): if model_second_stage[i]["Aeq"] is not None: neq_index[i + 1] = neq_index[i] + model_second_stage[i]["Aeq"].shape[0] else: neq_index[i + 1] = neq_index[i] if model_second_stage[i]["Ts"] is not None: nineq_index[i + 1] = nineq_index[i] + model_second_stage[i]["Ts"].shape[0] else: nineq_index[i + 1] = nineq_index[i] nv_index[i + 1] = nv_index[i] + nv_second_stage c = concatenate([c, model_second_stage[i]["c"]]) q = concatenate([q, model_second_stage[i]["q"]]) lb = concatenate([lb, model_second_stage[i]["lb"]]) ub = concatenate([ub, model_second_stage[i]["ub"]]) vtypes += model_second_stage[i]["vtypes"] beq = concatenate([beq, model_second_stage[i]["beq"]]) Aeq_full = lil_matrix((neq_index[-1], nv_index[-1])) Aeq_full[0:neq_index[0], 0:nv_index[0]] = model_first_stage["Aeq"] rc = zeros(0) for i in range(ns): Aeq_full[neq_index[i]:neq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Aeq"] Qc.update(model_second_stage[i]["Qc"]) rc = concatenate([rc, model_second_stage[i]["rc"]]) A_full = lil_matrix((nineq_index[-1], nv_index[-1])) b = model_first_stage["b"] A_full[0:int(nineq_index[0]), 0:int(nv_index[0])] = model_first_stage["A"] for i in range(ns): A_full[nineq_index[i]:nineq_index[i + 1], 0:nv_index[0]] = model_second_stage[i]["Ts"] A_full[nineq_index[i]:nineq_index[i + 1], nv_index[i]:nv_index[i + 1]] = model_second_stage[i]["Ws"] b = concatenate([b, model_second_stage[i]["hs"]]) # 3) Obtain the results for first-stage and second stage optimization problems # 3.1) Obtain the integrated solution (sol, obj, success) = miqcp(c, q, Aeq=Aeq_full, beq=beq, A=A_full, b=b, Qc=Qc, rc=rc, xmin=lb, xmax=ub, vtypes=vtypes) # 3.2) decouple the solution into multiple subsystems sol_first_stage = sol[0:nv_second_stage] sol_second_stage = {} for i in range(ns): sol_second_stage[i] = sol[int(nv_index[i]):int(nv_index[i + 1])] # 4) Verify the first-stage and second stage optization problem # 4.1) First-stage solution sol_first_stage = self.first_stage_solution_validation(sol=sol_first_stage) # 4.2) Second-stage solution sol_second_stage_checked = {}
db_management = DataBaseManagement()
15
2023-11-27 15:57:53+00:00
16k
andryyy/ehlocomputer
models/listeners.py
[ { "identifier": "defaults", "path": "config/defaults.py", "snippet": "ACCEPT_LANGUAGES = [\"en\", \"de\"]\nMAX_HISTORIC_REVISIONS = 5\nWEBAUTHN_CHALLENGE_TIMEOUT = 30 # seconds\nPROXY_AUTH_TIMEOUT = 300 # seconds\nTABLE_PAGE_SIZE = 10\nTINYDB = {\n \"storage\": RedisLockMiddleware(JSONStorage),\n ...
import json import os import re import uuid from config import defaults from config import lego from config.database import * from email_validator import validate_email from pydantic import ( AfterValidator, BaseModel, EmailStr, Field, FilePath, HttpUrl, field_validator, model_validator, validator, ) from pydantic.networks import IPv4Address, IPv6Address from typing import Annotated, Any, Literal from . import ( utc_now_as_str, ensure_list, to_unique_sorted_str_list, get_validated_fqdn, flatten, )
12,450
class ListenerCreate(BaseModel): id: Annotated[str, Field(default_factory=lambda: str(uuid.uuid4()))] name: Annotated[str, Field(min_length=1)] configuration: dict = {} historic: list = []
class ListenerCreate(BaseModel): id: Annotated[str, Field(default_factory=lambda: str(uuid.uuid4()))] name: Annotated[str, Field(min_length=1)] configuration: dict = {} historic: list = []
created: Annotated[str, Field(default_factory=utc_now_as_str)]
2
2023-12-01 08:36:45+00:00
16k
fzmi/ubdd
models/dino/models/dino/dino.py
[ { "identifier": "box_ops", "path": "models/dino/util/box_ops.py", "snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef box_iou_pairwise(boxes1, boxes2):\ndef generalized_box_iou_pairwise(boxes1, boxes2):\ndef mask...
import copy import math import torch import torch.nn.functional as F from typing import List from torch import nn from torchvision.ops.boxes import nms from models.dino.util import box_ops from models.dino.util.misc import (NestedTensor, nested_tensor_from_tensor_list, accuracy, get_world_size, interpolate, is_dist_avail_and_initialized, inverse_sigmoid) from .backbone import build_backbone from .matcher import build_matcher from .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm, dice_loss) from .deformable_transformer import build_deformable_transformer from .utils import sigmoid_focal_loss, MLP from ..registry import MODULE_BUILD_FUNCS from .dn_components import prepare_for_cdn,dn_post_process
10,832
else: box_embed_layerlist = [copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers)] if dec_pred_class_embed_share: class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)] else: class_embed_layerlist = [copy.deepcopy(_class_embed) for i in range(transformer.num_decoder_layers)] self.bbox_embed = nn.ModuleList(box_embed_layerlist) self.class_embed = nn.ModuleList(class_embed_layerlist) self.transformer.decoder.bbox_embed = self.bbox_embed self.transformer.decoder.class_embed = self.class_embed # two stage self.two_stage_type = two_stage_type self.two_stage_add_query_num = two_stage_add_query_num assert two_stage_type in ['no', 'standard'], "unknown param {} of two_stage_type".format(two_stage_type) if two_stage_type != 'no': if two_stage_bbox_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_bbox_embed = _bbox_embed else: self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed) if two_stage_class_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_class_embed = _class_embed else: self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed) self.refpoint_embed = None if self.two_stage_add_query_num > 0: self.init_ref_points(two_stage_add_query_num) self.decoder_sa_type = decoder_sa_type assert decoder_sa_type in ['sa', 'ca_label', 'ca_content'] if decoder_sa_type == 'ca_label': self.label_embedding = nn.Embedding(num_classes, hidden_dim) for layer in self.transformer.decoder.layers: layer.label_embedding = self.label_embedding else: for layer in self.transformer.decoder.layers: layer.label_embedding = None self.label_embedding = None self._reset_parameters() def _reset_parameters(self): # init input_proj for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) def init_ref_points(self, use_num_queries): self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim) if self.random_refpoints_xy: self.refpoint_embed.weight.data[:, :2].uniform_(0,1) self.refpoint_embed.weight.data[:, :2] = inverse_sigmoid(self.refpoint_embed.weight.data[:, :2]) self.refpoint_embed.weight.data[:, :2].requires_grad = False if self.fix_refpoints_hw > 0: print("fix_refpoints_hw: {}".format(self.fix_refpoints_hw)) assert self.random_refpoints_xy self.refpoint_embed.weight.data[:, 2:] = self.fix_refpoints_hw self.refpoint_embed.weight.data[:, 2:] = inverse_sigmoid(self.refpoint_embed.weight.data[:, 2:]) self.refpoint_embed.weight.data[:, 2:].requires_grad = False elif int(self.fix_refpoints_hw) == -1: pass elif int(self.fix_refpoints_hw) == -2: print('learn a shared h and w') assert self.random_refpoints_xy self.refpoint_embed = nn.Embedding(use_num_queries, 2) self.refpoint_embed.weight.data[:, :2].uniform_(0,1) self.refpoint_embed.weight.data[:, :2] = inverse_sigmoid(self.refpoint_embed.weight.data[:, :2]) self.refpoint_embed.weight.data[:, :2].requires_grad = False self.hw_embed = nn.Embedding(1, 1) else: raise NotImplementedError('Unknown fix_refpoints_hw {}'.format(self.fix_refpoints_hw)) def forward(self, samples: NestedTensor, targets:List=None): """ The forward expects a NestedTensor, which consists of: - samples.tensor: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x num_classes] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if isinstance(samples, (list, torch.Tensor)): samples = nested_tensor_from_tensor_list(samples) features, poss = self.backbone(samples) srcs = [] masks = [] for l, feat in enumerate(features): src, mask = feat.decompose() srcs.append(self.input_proj[l](src)) masks.append(mask) assert mask is not None if self.num_feature_levels > len(srcs): _len_srcs = len(srcs) for l in range(_len_srcs, self.num_feature_levels): if l == _len_srcs: src = self.input_proj[l](features[-1].tensors) else: src = self.input_proj[l](srcs[-1]) m = samples.mask mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0] pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype) srcs.append(src) masks.append(mask) poss.append(pos_l) if self.dn_number > 0 or targets is not None: input_query_label, input_query_bbox, attn_mask, dn_meta =\
# ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR model and criterion classes. # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ class DINO(nn.Module): """ This is the Cross-Attention Detector module that performs object detection """ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False, iter_update=False, query_dim=2, random_refpoints_xy=False, fix_refpoints_hw=-1, num_feature_levels=1, nheads=8, # two stage two_stage_type='no', # ['no', 'standard'] two_stage_add_query_num=0, dec_pred_class_embed_share=True, dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, decoder_sa_type = 'sa', num_patterns = 0, dn_number = 100, dn_box_noise_scale = 0.4, dn_label_noise_ratio = 0.5, dn_labelbook_size = 100, ): """ Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_classes: number of object classes num_queries: number of object queries, ie detection slot. This is the maximal number of objects Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. fix_refpoints_hw: -1(default): learn w and h for each box seperately >0 : given fixed number -2 : learn a shared w and h """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.num_classes = num_classes self.hidden_dim = hidden_dim = transformer.d_model self.num_feature_levels = num_feature_levels self.nheads = nheads self.label_enc = nn.Embedding(dn_labelbook_size + 1, hidden_dim) # setting query dim self.query_dim = query_dim assert query_dim == 4 self.random_refpoints_xy = random_refpoints_xy self.fix_refpoints_hw = fix_refpoints_hw # for dn training self.num_patterns = num_patterns self.dn_number = dn_number self.dn_box_noise_scale = dn_box_noise_scale self.dn_label_noise_ratio = dn_label_noise_ratio self.dn_labelbook_size = dn_labelbook_size # prepare input projection layers if num_feature_levels > 1: num_backbone_outs = len(backbone.num_channels) input_proj_list = [] for _ in range(num_backbone_outs): in_channels = backbone.num_channels[_] input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append(nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, hidden_dim), )) in_channels = hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: assert two_stage_type == 'no', "two_stage_type should be no if num_feature_levels=1 !!!" self.input_proj = nn.ModuleList([ nn.Sequential( nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), )]) self.backbone = backbone self.aux_loss = aux_loss self.box_pred_damping = box_pred_damping = None self.iter_update = iter_update assert iter_update, "Why not iter_update?" # prepare pred layers self.dec_pred_class_embed_share = dec_pred_class_embed_share self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share # prepare class & box embed _class_embed = nn.Linear(hidden_dim, num_classes) _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3) # init the two embed layers prior_prob = 0.01 bias_value = -math.log((1 - prior_prob) / prior_prob) _class_embed.bias.data = torch.ones(self.num_classes) * bias_value nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0) nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0) if dec_pred_bbox_embed_share: box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)] else: box_embed_layerlist = [copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers)] if dec_pred_class_embed_share: class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)] else: class_embed_layerlist = [copy.deepcopy(_class_embed) for i in range(transformer.num_decoder_layers)] self.bbox_embed = nn.ModuleList(box_embed_layerlist) self.class_embed = nn.ModuleList(class_embed_layerlist) self.transformer.decoder.bbox_embed = self.bbox_embed self.transformer.decoder.class_embed = self.class_embed # two stage self.two_stage_type = two_stage_type self.two_stage_add_query_num = two_stage_add_query_num assert two_stage_type in ['no', 'standard'], "unknown param {} of two_stage_type".format(two_stage_type) if two_stage_type != 'no': if two_stage_bbox_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_bbox_embed = _bbox_embed else: self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed) if two_stage_class_embed_share: assert dec_pred_class_embed_share and dec_pred_bbox_embed_share self.transformer.enc_out_class_embed = _class_embed else: self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed) self.refpoint_embed = None if self.two_stage_add_query_num > 0: self.init_ref_points(two_stage_add_query_num) self.decoder_sa_type = decoder_sa_type assert decoder_sa_type in ['sa', 'ca_label', 'ca_content'] if decoder_sa_type == 'ca_label': self.label_embedding = nn.Embedding(num_classes, hidden_dim) for layer in self.transformer.decoder.layers: layer.label_embedding = self.label_embedding else: for layer in self.transformer.decoder.layers: layer.label_embedding = None self.label_embedding = None self._reset_parameters() def _reset_parameters(self): # init input_proj for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) def init_ref_points(self, use_num_queries): self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim) if self.random_refpoints_xy: self.refpoint_embed.weight.data[:, :2].uniform_(0,1) self.refpoint_embed.weight.data[:, :2] = inverse_sigmoid(self.refpoint_embed.weight.data[:, :2]) self.refpoint_embed.weight.data[:, :2].requires_grad = False if self.fix_refpoints_hw > 0: print("fix_refpoints_hw: {}".format(self.fix_refpoints_hw)) assert self.random_refpoints_xy self.refpoint_embed.weight.data[:, 2:] = self.fix_refpoints_hw self.refpoint_embed.weight.data[:, 2:] = inverse_sigmoid(self.refpoint_embed.weight.data[:, 2:]) self.refpoint_embed.weight.data[:, 2:].requires_grad = False elif int(self.fix_refpoints_hw) == -1: pass elif int(self.fix_refpoints_hw) == -2: print('learn a shared h and w') assert self.random_refpoints_xy self.refpoint_embed = nn.Embedding(use_num_queries, 2) self.refpoint_embed.weight.data[:, :2].uniform_(0,1) self.refpoint_embed.weight.data[:, :2] = inverse_sigmoid(self.refpoint_embed.weight.data[:, :2]) self.refpoint_embed.weight.data[:, :2].requires_grad = False self.hw_embed = nn.Embedding(1, 1) else: raise NotImplementedError('Unknown fix_refpoints_hw {}'.format(self.fix_refpoints_hw)) def forward(self, samples: NestedTensor, targets:List=None): """ The forward expects a NestedTensor, which consists of: - samples.tensor: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x num_classes] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if isinstance(samples, (list, torch.Tensor)): samples = nested_tensor_from_tensor_list(samples) features, poss = self.backbone(samples) srcs = [] masks = [] for l, feat in enumerate(features): src, mask = feat.decompose() srcs.append(self.input_proj[l](src)) masks.append(mask) assert mask is not None if self.num_feature_levels > len(srcs): _len_srcs = len(srcs) for l in range(_len_srcs, self.num_feature_levels): if l == _len_srcs: src = self.input_proj[l](features[-1].tensors) else: src = self.input_proj[l](srcs[-1]) m = samples.mask mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0] pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype) srcs.append(src) masks.append(mask) poss.append(pos_l) if self.dn_number > 0 or targets is not None: input_query_label, input_query_bbox, attn_mask, dn_meta =\
prepare_for_cdn(dn_args=(targets, self.dn_number, self.dn_label_noise_ratio, self.dn_box_noise_scale),
18
2023-12-04 00:27:58+00:00
16k
girgle/DouZero_For_New_HLDDZ
main.py
[ { "identifier": "GameHelper", "path": "GameHelper.py", "snippet": "class GameHelper:\n def __init__(self):\n self.ScreenZoomRate = None\n self.counter = QTime()\n self.Pics = {}\n self.PicsCV = {}\n st = time.time()\n self.Handle = win32gui.FindWindow(\"Unity...
import GameHelper as gh import os import sys import time import threading import pyautogui import win32gui import multiprocessing as mp import DetermineColor as DC import cv2 import numpy as np import traceback import BidModel import LandlordModel import FarmerModel from GameHelper import GameHelper from PIL import Image from skimage.metrics import structural_similarity as ssim from collections import defaultdict from douzero.env.move_detector import get_move_type from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtWidgets import QTableWidgetItem, QInputDialog, QMessageBox from PyQt5.QtGui import QPixmap, QIcon from PyQt5.QtCore import QTime, QEventLoop, Qt from MainWindow import Ui_Form from douzero.env.game import GameEnv from douzero.evaluation.deep_agent import DeepAgent
12,150
# -*- coding: utf-8 -*- # Created by: Raf # Modify by: Vincentzyx EnvCard2RealCard = {3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'T', 11: 'J', 12: 'Q', 13: 'K', 14: 'A', 17: '2', 20: 'X', 30: 'D'} RealCard2EnvCard = {'3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, '2': 17, 'X': 20, 'D': 30} AllEnvCard = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30] AllCards = ['D', 'X', '2', 'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3'] helper = GameHelper()
# -*- coding: utf-8 -*- # Created by: Raf # Modify by: Vincentzyx EnvCard2RealCard = {3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'T', 11: 'J', 12: 'Q', 13: 'K', 14: 'A', 17: '2', 20: 'X', 30: 'D'} RealCard2EnvCard = {'3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, '2': 17, 'X': 20, 'D': 30} AllEnvCard = [3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 17, 17, 17, 17, 20, 30] AllCards = ['D', 'X', '2', 'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3'] helper = GameHelper()
class MyPyQT_Form(QtWidgets.QWidget, Ui_Form):
2
2023-12-01 04:04:30+00:00
16k
yongzhuo/MacroGPT-Pretrain
macro_gpt/ft_gpt/train.pt.speed.py
[ { "identifier": "CUDA_VISIBLE_DEVICES", "path": "macro_gpt/ft_gpt/config_macrogpt_1b3_float32.py", "snippet": "CUDA_VISIBLE_DEVICES = \"0\"" }, { "identifier": "USE_TORCH", "path": "macro_gpt/ft_gpt/config_macrogpt_1b3_float32.py", "snippet": "USE_TORCH = \"1\"" }, { "identifier"...
import random import copy import sys import os import torch.distributed as dist import bitsandbytes as bnb import torch.nn as nn import transformers import torch from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import CUDA_VISIBLE_DEVICES, USE_TORCH, CPU_NUMS # from config from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from peft import (get_peft_model_state_dict, get_peft_model, LoraConfig) from transformers import AutoModelForCausalLM, AutoTokenizer from transformers.modeling_utils import unwrap_model from tensorboardX import SummaryWriter from datasets import load_dataset from macro_gpt.models.llama.modeling_llama import LlamaForCausalLM as LLMForCausalLM from macro_gpt.models.llama.tokenization_llama import LlamaTokenizer as LLMTokenizer from macro_gpt.models.llama.modeling_llama import LlamaConfig as LLMConfig from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_PRETRAIN, DATA_PATH, MODEL_SAVE_DIR, REPO_ID from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MICRO_BATCH_SIZE, BATCH_SIZE, GRADIENT_ACCUMULATION_STEPS from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LEARNING_RATE, EPOCHS, SAVE_STEPS, VAL_SET_SIZE, TARGET_MODULES from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import IS_PARALLELIZABLE, MODEL_PARALLEL, USE_CACHE from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import MAX_LENGTH_Q, MAX_LENGTH_A, MAX_LENGTH_QA from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import LORA_DROPOUT, LORA_ALPHA, LORA_R from macro_gpt.ft_gpt.config_macrogpt_1b3_float32 import PATH_MODEL_CONFIG, PATH_TOKENIZER_PRETRAIN
13,834
# ID_MASK = 64789 # ID_PAD = 2 ID_EOP = 50256 ID_SOP = 50256 ID_BOS = 50256 ID_EOS = 50256 ID_PAD = 50256 IDS_ORG = [ID_PAD] # { "<|endoftext|>": 50256, # "### End": 50257, # "### Instruction:": 50258, # "### Response:\n": 50259 # } # model = GPT2LMHeadModel.from_pretrained(PATH_MODEL_PRETRAIN) gpt2_config = LLMConfig.from_json_file(PATH_MODEL_CONFIG) model = LLMForCausalLM(gpt2_config) model.init_weights() model.gradient_checkpointing_enable() model.enable_input_require_grads() model.is_parallelizable = IS_PARALLELIZABLE model.model_parallel = MODEL_PARALLEL model.config.use_cache = USE_CACHE model = model.cuda() print_rank_0_named_parameters(model) tensorboardx_witer = SummaryWriter(logdir=MODEL_SAVE_DIR) # files = dfs_file(DATA_PATH) # files = [files for file in files if "data_merge.0" in file or "data_merge.1" in file] ### 只有一个train的情况 # data = load_dataset("json", data_files={"train": files}) data = load_dataset("json", data_files=DATA_PATH) # data = load_dataset("json", data_dir=DATA_PATH) # if VAL_SET_SIZE > 0: # # train_val = data["train"].train_test_split(test_size=min(VAL_SET_SIZE, # # int(len(data["train"])/10000)), shuffle=True, seed=42) # VAL_SET_SIZE = max(min(VAL_SET_SIZE, int(len(data["train"])/10000)), 1) # generate_prompt(data["train"][0], is_logger=True) # train_val = data["train"].train_test_split(test_size=VAL_SET_SIZE, shuffle=True, seed=42) # train_data = train_val["train"].shuffle().map(generate_prompt) # val_data = train_val["test"].shuffle().map(generate_prompt) # else: generate_prompt(data["train"][0], is_logger=True) train_data = data["train"].shuffle().map(generate_prompt) val_data = None class CustomTrainer(transformers.Trainer): def compute_loss(self, model, inputs, return_outputs=False): inputs = {k: v.cuda() for k, v in inputs.items()} outputs = model(**inputs) # if contain labels, will calculate loss if local_rank_is_0: logs = {} tr_loss_scalar = self._nested_gather(outputs.loss.detach()).mean().item() logs["loss"] = round(tr_loss_scalar, 4) logs["lr"] = self.lr_scheduler.get_last_lr()[0] step = self.state.global_step for k, v in logs.items(): tensorboardx_witer.add_scalar(k, v, step) self.log(logs) if self.label_smoother is not None and "labels" in inputs: labels = inputs.pop("labels") else: labels = None # Save past state if it exists # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index] if labels is not None: if unwrap_model(model)._get_name() in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values(): loss = self.label_smoother(outputs, labels, shift_labels=True) else: loss = self.label_smoother(outputs, labels) else: if isinstance(outputs, dict) and "loss" not in outputs: raise ValueError( "The model did not return a loss from the inputs, only the following keys: " f"{','.join(outputs.keys())}. For reference, the inputs it received are {','.join(inputs.keys())}." ) # We don't use .loss here since the model may return tuples instead of ModelOutput. loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] return (loss, outputs) if return_outputs else loss trainer = CustomTrainer( # data_collator=transformers.DataCollatorForSeq2Seq( # tokenizer, pad_to_multiple_of=8, # return_tensors="pt", padding=True # ), data_collator=data_collator, train_dataset=train_data, eval_dataset=val_data, model=model, args=transformers.TrainingArguments( gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS, per_device_train_batch_size=MICRO_BATCH_SIZE, learning_rate=LEARNING_RATE, num_train_epochs=EPOCHS, max_grad_norm=1.0, logging_steps=20, # warmup_steps=32, # warmup_steps=382, # 618 warmup_ratio=0.01, # warmup_steps=16, evaluation_strategy="no", lr_scheduler_type="constant", #'constant', # "cosine", logging_first_step=False, # evaluation_strategy="steps" if VAL_SET_SIZE > 0 else "no", # eval_steps=SAVE_STEPS if VAL_SET_SIZE > 0 else None, save_strategy="steps", save_total_limit=3,
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2023/3/5 21:04 # @author : Mo # @function: macro-gpt path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) sys.path.append(path_root) os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:3072" # os.environ["CUDA_VISIBLE_DEVICES"] = CUDA_VISIBLE_DEVICES os.environ["USE_TORCH"] = USE_TORCH os.environ["OMP_NUM_THREADS"] = CPU_NUMS # export OMP_NUM_THREADS=1 os.environ["OPENBLAS_NUM_THREADS"] = CPU_NUMS # export OPENBLAS_NUM_THREADS=1 os.environ["MKL_NUM_THREADS"] = CPU_NUMS # export MKL_NUM_THREADS=1 os.environ["VECLIB_MAXIMUM_THREADS"] = CPU_NUMS # export VECLIB_MAXIMUM_THREADS=1 os.environ["NUMEXPR_NUM_THREADS"] = CPU_NUMS # export NUMEXPR_NUM_THREADS=1 def save_model_state(model, config=None, model_save_dir="./", model_name="adapter_model.bin"): """ 仅保存 有梯度 的 模型参数(推荐使用) """ if not os.path.exists(model_save_dir): os.makedirs(model_save_dir) # save config if config: config.save_pretrained(model_save_dir) # config.to_dict() # save model path_model = os.path.join(model_save_dir, model_name) # grad_params_dict = {k: v.to("cpu") for k, v in model.named_parameters() # if v.requires_grad == True} grad_params_dict = {k: v.to("cpu") for k, v in model.named_parameters()} torch.save(grad_params_dict, path_model) print_rank_0("******model_save_path is {}******".format(path_model)) def print_rank_0_named_parameters(model, use_print_rank_0_data=False): """ 打印模型训练参数/数据类型信息 """ trainable_params = 0 all_param = 0 for name, param in model.named_parameters(): if use_print_rank_0_data: print_rank_0((name, param.data.dtype, param.requires_grad, param.data)) else: print_rank_0((name, param.data.dtype, param.requires_grad)) num_params = param.numel() # if using DS Zero 3 and the weights are initialized empty if num_params == 0 and hasattr(param, "ds_numel"): num_params = param.ds_numel all_param += num_params if param.requires_grad: trainable_params += num_params print_rank_0(f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}") def prepare_model_for_half_training(model, output_embedding_layer_name="lm_head", use_gradient_checkpointing=True, layer_norm_names=["layer_norm"]): r""" This method wrapps the entire protocol for preparing a model before running a training. This includes: 1- Cast the layernorm in fp32 2- making output embedding layer require grads 3- Add the upcasting of the lm head to fp32 Args: model, (`transformers.PreTrainedModel`): The loaded model from `transformers` """ # 不要使用 model.half(), 这样会先截取精度再训练了, 最初data就要保持half for name, param in model.named_parameters(): # freeze base model's layers param.requires_grad = False # cast layer norm in fp32 for stability for 8bit models if param.ndim == 1 and any(layer_norm_name in name for layer_norm_name in layer_norm_names): param.data = param.data.to(torch.float32) elif output_embedding_layer_name in name: # lm_head也需要是tf.float32(最后一层) param.data = param.data.to(torch.float32) else: param.data = param.data.to(torch.half) if use_gradient_checkpointing: # For backward compatibility if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) # enable gradient checkpointing for memory efficiency model.gradient_checkpointing_enable() return model def generate_prompt(data_point, is_logger=False): # sorry about the formatting disaster gotta move fast # text_1 = f"指令:\n{data_point.get('instruction', '')}\n问:\n{data_point.get('input', '')}\n答:\n" \ # if data_point.get('input', '') else f"指令:\n{data_point.get('instruction', '')}\n答:\n" # text_2 = f"{data_point.get('output', '')}" text_a = data_point.get('a', '') prompt_str_1 = text_a # end with gMASK, <sop> x = tokenizer.encode(prompt_str_1) if len(x) > MAX_LENGTH_QA - 2: x = x[:MAX_LENGTH_QA - 2] if not x: x = [ID_PAD, ID_EOS] if x and x[-1] != ID_EOS: x += [ID_EOS] out = {"input_ids": x, "labels": []} if is_logger: print_rank_0(prompt_str_1) print_rank_0(out) return out def data_collator(batch): def get_position_ids(seq, bos_token_id): seq_length = len(seq) position_ids = torch.arange(seq_length, dtype=torch.long).unsqueeze(0) return position_ids def get_masks(seq, special_ids=IDS_ORG): """ padding-mask """ # mask until ID_SOP attention_mask = torch.ones((1, len(seq), len(seq))) attention_mask.tril_() # ### 如果 padding-right, 也mask掉 # for idx, s in enumerate(seq): # if s in special_ids: # attention_mask[..., idx] = 1 attention_mask = (attention_mask < 0.5).bool() return attention_mask len_max_batch = [len(batch[i].get("input_ids")) + len(batch[i].get("labels")) + 1 for i in range(len(batch))] len_max_batch = min(MAX_LENGTH_QA, max(len_max_batch)) batch_attention_mask = [] batch_position_ids = [] batch_input_ids = [] batch_labels = [] for ba in batch: x, y = ba.get("input_ids"), ba.get("labels") len_padding = len_max_batch - len(x) - len(y) if tokenizer.padding_side and tokenizer.padding_side == "left": labels = [-100] * len_padding + x + y input_ids = [ID_PAD] * (len_padding) + x + y else: labels = x + y + [-100] * len_padding input_ids = x + y + [ID_PAD] * (len_padding) tensor_position_ids = get_position_ids(input_ids, bos_token_id=ID_SOP) tensor_attention_mask = get_masks(input_ids, special_ids=IDS_ORG) tensor_input_ids = torch.tensor(input_ids, dtype=torch.long) tensor_labels = torch.tensor(labels, dtype=torch.long) batch_attention_mask.append(tensor_attention_mask) batch_position_ids.append(tensor_position_ids) batch_input_ids.append(tensor_input_ids) batch_labels.append(tensor_labels) # print_rank_0(batch_attention_mask) batch_attention_mask = torch.stack(batch_attention_mask) batch_position_ids = torch.stack(batch_position_ids) batch_input_ids = torch.stack(batch_input_ids) batch_labels = torch.stack(batch_labels) input_dict = { # "full_attention_mask": copy.deepcopy(batch_attention_mask), # "attention_mask": batch_attention_mask, # "position_ids": batch_position_ids, "input_ids": batch_input_ids, "labels": batch_labels, } # print_rank_0(input_dict) return input_dict def dfs_file(path_dir): """ 递归获取某个目录下的所有文件(所有层, 包括子目录) Args: path_dir[String]:, path of dir, eg. "/home/data" Returns: data[List]: data of input, eg. ["2020_01_08.txt"] """ path_files = [] for root, dirs, files in os.walk(path_dir): # 分别代表根目录、文件夹、文件 for file in files: # 遍历文件 file_path = os.path.join(root, file) # 获取文件绝对路径 path_files.append(file_path) # 将文件路径添加进列表 files = list(set(path_files)) files.sort() # the same list return files def print_rank_0(*args): """ 只打印 0 号GPU的 """ if torch.distributed.get_rank() == 0: # 一般用0,当然,可以选任意的rank保存。 print(*args) def local_rank_is_0(): """ 判断是哪台机子的 """ flag = False if torch.distributed.get_rank() == 0: flag = True return flag dist.init_process_group(backend="nccl") # torch.distributed.init_process_group() tokenizer = LLMTokenizer.from_pretrained(PATH_MODEL_PRETRAIN) # tokenizer.pad_token = tokenizer.eos_token tokenizer.padding_side = "left" # Allow batched inference # tokenizer.padding_side = "right" # Allow batched inference # ID_gMASK = 64790 # ID_BOS = 64792 # ID_EOS = 64793 # ID_MASK = 64789 # ID_PAD = 2 ID_EOP = 50256 ID_SOP = 50256 ID_BOS = 50256 ID_EOS = 50256 ID_PAD = 50256 IDS_ORG = [ID_PAD] # { "<|endoftext|>": 50256, # "### End": 50257, # "### Instruction:": 50258, # "### Response:\n": 50259 # } # model = GPT2LMHeadModel.from_pretrained(PATH_MODEL_PRETRAIN) gpt2_config = LLMConfig.from_json_file(PATH_MODEL_CONFIG) model = LLMForCausalLM(gpt2_config) model.init_weights() model.gradient_checkpointing_enable() model.enable_input_require_grads() model.is_parallelizable = IS_PARALLELIZABLE model.model_parallel = MODEL_PARALLEL model.config.use_cache = USE_CACHE model = model.cuda() print_rank_0_named_parameters(model) tensorboardx_witer = SummaryWriter(logdir=MODEL_SAVE_DIR) # files = dfs_file(DATA_PATH) # files = [files for file in files if "data_merge.0" in file or "data_merge.1" in file] ### 只有一个train的情况 # data = load_dataset("json", data_files={"train": files}) data = load_dataset("json", data_files=DATA_PATH) # data = load_dataset("json", data_dir=DATA_PATH) # if VAL_SET_SIZE > 0: # # train_val = data["train"].train_test_split(test_size=min(VAL_SET_SIZE, # # int(len(data["train"])/10000)), shuffle=True, seed=42) # VAL_SET_SIZE = max(min(VAL_SET_SIZE, int(len(data["train"])/10000)), 1) # generate_prompt(data["train"][0], is_logger=True) # train_val = data["train"].train_test_split(test_size=VAL_SET_SIZE, shuffle=True, seed=42) # train_data = train_val["train"].shuffle().map(generate_prompt) # val_data = train_val["test"].shuffle().map(generate_prompt) # else: generate_prompt(data["train"][0], is_logger=True) train_data = data["train"].shuffle().map(generate_prompt) val_data = None class CustomTrainer(transformers.Trainer): def compute_loss(self, model, inputs, return_outputs=False): inputs = {k: v.cuda() for k, v in inputs.items()} outputs = model(**inputs) # if contain labels, will calculate loss if local_rank_is_0: logs = {} tr_loss_scalar = self._nested_gather(outputs.loss.detach()).mean().item() logs["loss"] = round(tr_loss_scalar, 4) logs["lr"] = self.lr_scheduler.get_last_lr()[0] step = self.state.global_step for k, v in logs.items(): tensorboardx_witer.add_scalar(k, v, step) self.log(logs) if self.label_smoother is not None and "labels" in inputs: labels = inputs.pop("labels") else: labels = None # Save past state if it exists # TODO: this needs to be fixed and made cleaner later. if self.args.past_index >= 0: self._past = outputs[self.args.past_index] if labels is not None: if unwrap_model(model)._get_name() in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values(): loss = self.label_smoother(outputs, labels, shift_labels=True) else: loss = self.label_smoother(outputs, labels) else: if isinstance(outputs, dict) and "loss" not in outputs: raise ValueError( "The model did not return a loss from the inputs, only the following keys: " f"{','.join(outputs.keys())}. For reference, the inputs it received are {','.join(inputs.keys())}." ) # We don't use .loss here since the model may return tuples instead of ModelOutput. loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] return (loss, outputs) if return_outputs else loss trainer = CustomTrainer( # data_collator=transformers.DataCollatorForSeq2Seq( # tokenizer, pad_to_multiple_of=8, # return_tensors="pt", padding=True # ), data_collator=data_collator, train_dataset=train_data, eval_dataset=val_data, model=model, args=transformers.TrainingArguments( gradient_accumulation_steps=GRADIENT_ACCUMULATION_STEPS, per_device_train_batch_size=MICRO_BATCH_SIZE, learning_rate=LEARNING_RATE, num_train_epochs=EPOCHS, max_grad_norm=1.0, logging_steps=20, # warmup_steps=32, # warmup_steps=382, # 618 warmup_ratio=0.01, # warmup_steps=16, evaluation_strategy="no", lr_scheduler_type="constant", #'constant', # "cosine", logging_first_step=False, # evaluation_strategy="steps" if VAL_SET_SIZE > 0 else "no", # eval_steps=SAVE_STEPS if VAL_SET_SIZE > 0 else None, save_strategy="steps", save_total_limit=3,
save_steps=SAVE_STEPS,
15
2023-11-30 12:39:19+00:00
16k
owkin/fedeca
fedeca/tests/test_dp_end2end.py
[ { "identifier": "TorchDPFedAvgAlgo", "path": "fedeca/algorithms/torch_dp_fed_avg_algo.py", "snippet": "class TorchDPFedAvgAlgo(TorchFedAvgAlgo):\n \"\"\"To be inherited.\n\n Wraps the necessary operation so a torch model can be trained in the Federated\n Averaging strategy using DP.\n \"\"\"...
import numpy as np import pandas as pd import torch import torch.nn as nn from substrafl.strategies import FedAvg from torch.optim import SGD from fedeca.algorithms.torch_dp_fed_avg_algo import TorchDPFedAvgAlgo from fedeca.fedeca_core import LogisticRegressionTorch from fedeca.tests.common import TestTempDir from fedeca.utils import ( Experiment, make_accuracy_function, make_substrafl_torch_dataset_class, ) from fedeca.utils.survival_utils import CoxData, make_categorical
11,906
"""Tests for DP training.""" # from substrafl.model_loading import download_algo_state # TODO increase rounds and an an assert to pooled equivalence as in # aper simulations class TestDPPropensityEnd2End(TestTempDir): """Webdisco tests class.""" @classmethod def setUpClass( cls, n_clients=3, ndim=10, nsamples=300, seed=43, ): """Initialize tests with data and FedIPTW object. Parameters ---------- n_clients : int, optional The number of clients, by default 3 nsamples : int, optional The number of patients in total. ndim : int, optional The number of dimensions, by default 10 initial_step_size : float, optional The first step size of NR descent, by default 0.95 seed : int, optional The seed, by default 43 standardize_data : bool, optional Whether or not to standardize data, by default True l1_ratio : float, optional The l1 ratio wrt L2., by default 0.0 penalizer : float, optional The weight for the elasticnet penalty, by default 0.0 learning_rate_strategy : str, optional How do we decrease the lr, by default "lifelines" """ super().setUpClass() cls.n_clients = n_clients rng = np.random.default_rng(seed) # Generating data with strong linear relationship simu_coxreg = CoxData( n_samples=nsamples, ndim=ndim, prop_treated=0.5, propensity="linear", dtype="float32", # Strong linearity overlap=100.0, seed=rng, random_censoring=True, censoring_factor=0.3, standardize_features=False, ) X, T, C, treated, _ = simu_coxreg.generate_data() # Will make first columns to be categorical
"""Tests for DP training.""" # from substrafl.model_loading import download_algo_state # TODO increase rounds and an an assert to pooled equivalence as in # aper simulations class TestDPPropensityEnd2End(TestTempDir): """Webdisco tests class.""" @classmethod def setUpClass( cls, n_clients=3, ndim=10, nsamples=300, seed=43, ): """Initialize tests with data and FedIPTW object. Parameters ---------- n_clients : int, optional The number of clients, by default 3 nsamples : int, optional The number of patients in total. ndim : int, optional The number of dimensions, by default 10 initial_step_size : float, optional The first step size of NR descent, by default 0.95 seed : int, optional The seed, by default 43 standardize_data : bool, optional Whether or not to standardize data, by default True l1_ratio : float, optional The l1 ratio wrt L2., by default 0.0 penalizer : float, optional The weight for the elasticnet penalty, by default 0.0 learning_rate_strategy : str, optional How do we decrease the lr, by default "lifelines" """ super().setUpClass() cls.n_clients = n_clients rng = np.random.default_rng(seed) # Generating data with strong linear relationship simu_coxreg = CoxData( n_samples=nsamples, ndim=ndim, prop_treated=0.5, propensity="linear", dtype="float32", # Strong linearity overlap=100.0, seed=rng, random_censoring=True, censoring_factor=0.3, standardize_features=False, ) X, T, C, treated, _ = simu_coxreg.generate_data() # Will make first columns to be categorical
Xcat, Xcont = make_categorical(X, up_to=0)
7
2023-11-27 18:01:37+00:00
16k
cmu-ci-lab/volumetric_opaque_solids
exp_runner.py
[ { "identifier": "Dataset", "path": "models/dataset.py", "snippet": "class Dataset:\n def __init__(self, conf):\n super(Dataset, self).__init__()\n print('Load data: Begin')\n self.device = torch.device('cuda')\n self.conf = conf\n\n self.data_dir = conf.get_string('...
import os import time import logging import argparse import numpy as np import cv2 as cv import trimesh import torch import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from shutil import copyfile from tqdm import tqdm from pyhocon import ConfigFactory from models.dataset import Dataset from models.sampler import PointSampler from models.fields import ( RenderingNetwork, SDFNetwork, SingleVarianceNetwork, NeRF, AnisotropyNetwork ) from models.attenuation_coefficient import AttenuationCoefficient from models.renderer import Renderer from models.util import read_mesh, write_mesh, extract_geometry
12,873
logging.info('End') def save_checkpoint(self): checkpoint = { 'sdf_network_fine': self.sdf_network.state_dict(), 'variance_network_fine': self.deviation_network.state_dict(), 'color_network_fine': self.color_network.state_dict(), 'optimizer': self.optimizer.state_dict(), 'iter_step': self.iter_step, } if self.nerf_outside is not None: checkpoint['nerf'] = self.nerf_outside.state_dict() if self.anisotropy_network is not None: checkpoint['anisotropy_network_fine'] = self.anisotropy_network.state_dict() os.makedirs(os.path.join(self.base_exp_dir, 'checkpoints'), exist_ok=True) torch.save(checkpoint, os.path.join(self.base_exp_dir, 'checkpoints', 'ckpt_{:0>6d}.pth'.format(self.iter_step))) def validate_image(self, idx=-1, resolution_level=-1): if idx < 0: idx = np.random.randint(self.dataset.n_images) print('Validate: iter: {}, camera: {}'.format(self.iter_step, idx)) if resolution_level < 0: resolution_level = self.validate_resolution_level rays_o, rays_d = self.dataset.gen_rays_at(idx, resolution_level=resolution_level) H, W, _ = rays_o.shape rays_o = rays_o.reshape(-1, 3).split(self.batch_size) rays_d = rays_d.reshape(-1, 3).split(self.batch_size) out_rgb_fine = [] out_normal_fine = [] out_depth = [] for rays_o_batch, rays_d_batch in zip(rays_o, rays_d): near, far = self.dataset.near_far_from_sphere(rays_o_batch, rays_d_batch) background_rgb = torch.ones([1, 3]) if self.use_white_bkgd else None render_out = self.renderer.render(rays_o_batch, rays_d_batch, near, far, background_rgb=background_rgb, annealed_anisotropy=self.get_annealed_anisotropy()) def feasible(key): return (key in render_out) and (render_out[key] is not None) if feasible('color_fine'): out_rgb_fine.append(render_out['color_fine'].detach().cpu().numpy()) if feasible('gradients') and feasible('weights'): n_samples = self.point_sampler.n_total_samples normals = render_out['gradients'] * render_out['weights'][:, :n_samples, None] if feasible('inside_sphere'): normals = normals * render_out['inside_sphere'][..., None] normals = normals.sum(dim=1).detach().cpu().numpy() out_normal_fine.append(normals) if feasible('depth'): out_depth.append(render_out['depth']) del render_out img_fine = None if len(out_rgb_fine) > 0: img_fine = (np.concatenate(out_rgb_fine, axis=0).reshape([H, W, 3, -1]) * 256).clip(0, 255) normal_img = None if len(out_normal_fine) > 0: normal_img = np.concatenate(out_normal_fine, axis=0) rot = np.linalg.inv(self.dataset.pose_all[idx, :3, :3].detach().cpu().numpy()) normal_img = (np.matmul(rot[None, :, :], normal_img[:, :, None]) .reshape([H, W, 3, -1]) * 128 + 128).clip(0, 255) depth_fine = None if len(out_depth) > 0: depth_img = (np.concatenate(out_depth, axis=0).reshape([H, W, 3]) * 256).clip(0, 255).astype(np.uint8) depth_img = cv.applyColorMap(depth_img, cv.COLORMAP_MAGMA) os.makedirs(os.path.join(self.base_exp_dir, 'validations_fine'), exist_ok=True) os.makedirs(os.path.join(self.base_exp_dir, 'normals'), exist_ok=True) os.makedirs(os.path.join(self.base_exp_dir, 'depth'), exist_ok=True) if self.mode == 'render': os.makedirs(os.path.join(self.base_exp_dir, 'renders'), exist_ok=True) for i in range(img_fine.shape[-1]): if len(out_rgb_fine) > 0: if self.mode == 'render': cv.imwrite(os.path.join(self.base_exp_dir, 'renders', 'render_{}.png'.format(idx)), img_fine[..., i]) else: cv.imwrite(os.path.join(self.base_exp_dir, 'validations_fine', '{:0>8d}_{}_{}.png'.format(self.iter_step, i, idx)), np.concatenate([img_fine[..., i], self.dataset.image_at(idx, resolution_level=resolution_level)])) if len(out_normal_fine) > 0: cv.imwrite(os.path.join(self.base_exp_dir, 'normals', '{:0>8d}_{}_{}.png'.format(self.iter_step, i, idx)), normal_img[..., i]) if len(out_depth) > 0: cv.imwrite(os.path.join(self.base_exp_dir, 'depth', '{:0>8d}_{}_{}.png'.format(self.iter_step, i, idx)), depth_img) def validate_mesh(self, scale_mesh=True, resolution=64, threshold=0.0): bound_min = torch.tensor(self.dataset.object_bbox_min, dtype=torch.float32) bound_max = torch.tensor(self.dataset.object_bbox_max, dtype=torch.float32) query_func = lambda pts: -self.sdf_network.sdf(pts)
logging.getLogger('matplotlib.font_manager').disabled = True class Runner: def __init__(self, conf_path, mode='train', case='CASE_NAME', is_continue=False, max_n_training_images=-1): self.device = torch.device('cuda') # Configuration self.conf_path = conf_path f = open(self.conf_path) conf_text = f.read() conf_text = conf_text.replace('CASE_NAME', case) f.close() self.conf = ConfigFactory.parse_string(conf_text) self.conf['dataset.data_dir'] = self.conf['dataset.data_dir'].replace('CASE_NAME', case) self.base_exp_dir = self.conf['general.base_exp_dir'] os.makedirs(self.base_exp_dir, exist_ok=True) self.dataset = Dataset(self.conf['dataset']) self.iter_step = 0 # Training parameters self.end_iter = self.conf.get_int('train.end_iter') self.save_freq = self.conf.get_int('train.save_freq') self.report_freq = self.conf.get_int('train.report_freq') self.val_freq = self.conf.get_int('train.val_freq') self.val_mesh_freq = self.conf.get_int('train.val_mesh_freq') self.viz_deviation_freq = self.conf.get_int('train.viz_deviation_freq', 0) self.batch_size = self.conf.get_int('train.batch_size') self.validate_resolution_level = self.conf.get_int('train.validate_resolution_level') self.learning_rate = self.conf.get_float('train.learning_rate') self.learning_rate_alpha = self.conf.get_float('train.learning_rate_alpha') self.use_white_bkgd = self.conf.get_bool('train.use_white_bkgd') self.warm_up_end = self.conf.get_float('train.warm_up_end', default=0.0) self.anneal_end = self.conf.get_float('train.anneal_end', default=0.0) self.max_n_training_images = max_n_training_images # Weights self.igr_weight = self.conf.get_float('train.igr_weight') self.mask_weight = self.conf.get_float('train.mask_weight') self.is_continue = is_continue self.mode = mode self.model_list = [] self.writer = None # Networks params_to_train = [] self.sdf_network = SDFNetwork(**self.conf['model.sdf_network']).to(self.device) self.deviation_network = SingleVarianceNetwork(**self.conf['model.variance_network']).to(self.device) self.color_network = RenderingNetwork(**self.conf['model.rendering_network']).to(self.device) params_to_train += list(self.sdf_network.parameters()) params_to_train += list(self.deviation_network.parameters()) params_to_train += list(self.color_network.parameters()) # optionally initialize a background NeRF network self.nerf_outside = None renders_background = 'model.point_sampler.n_outside' not in self.conf or self.conf['model.point_sampler.n_outside'] > 0 if renders_background: self.nerf_outside = NeRF(**self.conf['model.nerf']).to(self.device) params_to_train += list(self.nerf_outside.parameters()) # optionally initialize a layer to learn a spatially varying anisotropy self.anisotropy_network = None if 'model.anisotropy_network' in self.conf: self.anisotropy_network = AnisotropyNetwork(**self.conf['model.anisotropy_network']).to(self.device) params_to_train += list(self.anisotropy_network.parameters()) self.optimizer = torch.optim.Adam(params_to_train, lr=self.learning_rate) self.atten_coeff = AttenuationCoefficient(**self.conf['model.attenuation_coefficient']) self.point_sampler = PointSampler(**self.conf['model.point_sampler']) self.renderer = Renderer(self.nerf_outside, self.sdf_network, self.deviation_network, self.color_network, self.anisotropy_network, self.atten_coeff, self.point_sampler) # Load checkpoint latest_model_name = None if is_continue: model_list_raw = os.listdir(os.path.join(self.base_exp_dir, 'checkpoints')) model_list = [] for model_name in model_list_raw: if model_name[-3:] == 'pth' and int(model_name[5:-4]) <= self.end_iter: model_list.append(model_name) model_list.sort() latest_model_name = model_list[-1] if latest_model_name is not None: logging.info('Find checkpoint: {}'.format(latest_model_name)) self.load_checkpoint(latest_model_name) # Backup codes and configs for debug if self.mode[:5] == 'train': self.file_backup() def train(self): self.writer = SummaryWriter(log_dir=os.path.join(self.base_exp_dir, 'logs')) self.update_learning_rate() res_step = self.end_iter - self.iter_step image_perm = self.get_image_perm() for iter_i in tqdm(range(res_step)): data = self.dataset.gen_random_rays_at(image_perm[self.iter_step % len(image_perm)], self.batch_size) rays_o, rays_d, true_rgb, mask = data[:, :3], data[:, 3: 6], data[:, 6: 9], data[:, 9: 10] near, far = self.dataset.near_far_from_sphere(rays_o, rays_d) background_rgb = None if self.use_white_bkgd: background_rgb = torch.ones([1, 3]) if self.mask_weight > 0.0: mask = (mask > 0.5).float() else: mask = torch.ones_like(mask) mask_sum = mask.sum() + 1e-5 render_out = self.renderer.render(rays_o, rays_d, near, far, background_rgb=background_rgb, annealed_anisotropy=self.get_annealed_anisotropy()) color_fine = render_out['color_fine'] s_val = render_out['s_val'] gradient_error = render_out['gradient_error'] weight_max = render_out['weight_max'] weight_sum = render_out['weight_sum'] # Loss color_error = (color_fine - true_rgb) * mask color_fine_loss = F.l1_loss(color_error, torch.zeros_like(color_error), reduction='sum') / mask_sum psnr = 20.0 * torch.log10(1.0 / (((color_fine - true_rgb)**2 * mask).sum() / (mask_sum * 3.0)).sqrt()) eikonal_loss = gradient_error mask_loss = F.binary_cross_entropy(weight_sum.clip(1e-3, 1.0 - 1e-3), mask) loss = color_fine_loss +\ eikonal_loss * self.igr_weight +\ mask_loss * self.mask_weight self.optimizer.zero_grad() loss.backward() self.optimizer.step() self.iter_step += 1 self.writer.add_scalar('Loss/loss', loss, self.iter_step) self.writer.add_scalar('Loss/color_loss', color_fine_loss, self.iter_step) self.writer.add_scalar('Loss/eikonal_loss', eikonal_loss, self.iter_step) self.writer.add_scalar('Statistics/s_val', s_val.mean(), self.iter_step) self.writer.add_scalar('Statistics/weight_max', (weight_max * mask).sum() / mask_sum, self.iter_step) self.writer.add_scalar('Statistics/psnr', psnr, self.iter_step) if self.iter_step % self.report_freq == 0: print(self.base_exp_dir) print('iter:{:8>d} loss = {} lr={}'.format(self.iter_step, loss, self.optimizer.param_groups[0]['lr'])) if self.iter_step % self.save_freq == 0: self.save_checkpoint() if self.iter_step % self.val_freq == 0: self.validate_image() if self.iter_step % self.val_mesh_freq == 0: self.validate_mesh() if self.viz_deviation_freq > 0 and self.iter_step % self.viz_deviation_freq == 0: self.visualize_deviation_network() self.update_learning_rate() if self.iter_step % len(image_perm) == 0: image_perm = self.get_image_perm() def get_image_perm(self): if self.max_n_training_images <= 0: return torch.randperm(self.dataset.n_images) else: return torch.randperm(min(self.dataset.n_images, self.max_n_training_images)) def get_annealed_anisotropy(self): # goes from 0 (uniform / isotropic / rough) --> 1 (delta / anisotropic / smooth) if self.anneal_end == 0: return 1.0 else: return np.min([1.0, self.iter_step / self.anneal_end]) def update_learning_rate(self): if self.iter_step < self.warm_up_end: learning_factor = self.iter_step / self.warm_up_end else: alpha = self.learning_rate_alpha progress = (self.iter_step - self.warm_up_end) / (self.end_iter - self.warm_up_end) learning_factor = (np.cos(np.pi * progress) + 1.0) * 0.5 * (1 - alpha) + alpha for g in self.optimizer.param_groups: g['lr'] = self.learning_rate * learning_factor def file_backup(self): dir_lis = self.conf['general.recording'] os.makedirs(os.path.join(self.base_exp_dir, 'recording'), exist_ok=True) for dir_name in dir_lis: cur_dir = os.path.join(self.base_exp_dir, 'recording', dir_name) os.makedirs(cur_dir, exist_ok=True) files = os.listdir(dir_name) for f_name in files: if f_name[-3:] == '.py': copyfile(os.path.join(dir_name, f_name), os.path.join(cur_dir, f_name)) copyfile(self.conf_path, os.path.join(self.base_exp_dir, 'recording', 'config.conf')) def load_checkpoint(self, checkpoint_name): checkpoint = torch.load(os.path.join(self.base_exp_dir, 'checkpoints', checkpoint_name), map_location=self.device) self.sdf_network.load_state_dict(checkpoint['sdf_network_fine']) self.color_network.load_state_dict(checkpoint['color_network_fine']) self.deviation_network.load_state_dict(checkpoint['variance_network_fine']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.iter_step = checkpoint['iter_step'] if 'nerf' in checkpoint: self.nerf_outside.state_dict(checkpoint['nerf']) if 'anisotropy_network_fine' in checkpoint: self.anisotropy_network.state_dict(checkpoint['anisotropy_network_fine']) logging.info('End') def save_checkpoint(self): checkpoint = { 'sdf_network_fine': self.sdf_network.state_dict(), 'variance_network_fine': self.deviation_network.state_dict(), 'color_network_fine': self.color_network.state_dict(), 'optimizer': self.optimizer.state_dict(), 'iter_step': self.iter_step, } if self.nerf_outside is not None: checkpoint['nerf'] = self.nerf_outside.state_dict() if self.anisotropy_network is not None: checkpoint['anisotropy_network_fine'] = self.anisotropy_network.state_dict() os.makedirs(os.path.join(self.base_exp_dir, 'checkpoints'), exist_ok=True) torch.save(checkpoint, os.path.join(self.base_exp_dir, 'checkpoints', 'ckpt_{:0>6d}.pth'.format(self.iter_step))) def validate_image(self, idx=-1, resolution_level=-1): if idx < 0: idx = np.random.randint(self.dataset.n_images) print('Validate: iter: {}, camera: {}'.format(self.iter_step, idx)) if resolution_level < 0: resolution_level = self.validate_resolution_level rays_o, rays_d = self.dataset.gen_rays_at(idx, resolution_level=resolution_level) H, W, _ = rays_o.shape rays_o = rays_o.reshape(-1, 3).split(self.batch_size) rays_d = rays_d.reshape(-1, 3).split(self.batch_size) out_rgb_fine = [] out_normal_fine = [] out_depth = [] for rays_o_batch, rays_d_batch in zip(rays_o, rays_d): near, far = self.dataset.near_far_from_sphere(rays_o_batch, rays_d_batch) background_rgb = torch.ones([1, 3]) if self.use_white_bkgd else None render_out = self.renderer.render(rays_o_batch, rays_d_batch, near, far, background_rgb=background_rgb, annealed_anisotropy=self.get_annealed_anisotropy()) def feasible(key): return (key in render_out) and (render_out[key] is not None) if feasible('color_fine'): out_rgb_fine.append(render_out['color_fine'].detach().cpu().numpy()) if feasible('gradients') and feasible('weights'): n_samples = self.point_sampler.n_total_samples normals = render_out['gradients'] * render_out['weights'][:, :n_samples, None] if feasible('inside_sphere'): normals = normals * render_out['inside_sphere'][..., None] normals = normals.sum(dim=1).detach().cpu().numpy() out_normal_fine.append(normals) if feasible('depth'): out_depth.append(render_out['depth']) del render_out img_fine = None if len(out_rgb_fine) > 0: img_fine = (np.concatenate(out_rgb_fine, axis=0).reshape([H, W, 3, -1]) * 256).clip(0, 255) normal_img = None if len(out_normal_fine) > 0: normal_img = np.concatenate(out_normal_fine, axis=0) rot = np.linalg.inv(self.dataset.pose_all[idx, :3, :3].detach().cpu().numpy()) normal_img = (np.matmul(rot[None, :, :], normal_img[:, :, None]) .reshape([H, W, 3, -1]) * 128 + 128).clip(0, 255) depth_fine = None if len(out_depth) > 0: depth_img = (np.concatenate(out_depth, axis=0).reshape([H, W, 3]) * 256).clip(0, 255).astype(np.uint8) depth_img = cv.applyColorMap(depth_img, cv.COLORMAP_MAGMA) os.makedirs(os.path.join(self.base_exp_dir, 'validations_fine'), exist_ok=True) os.makedirs(os.path.join(self.base_exp_dir, 'normals'), exist_ok=True) os.makedirs(os.path.join(self.base_exp_dir, 'depth'), exist_ok=True) if self.mode == 'render': os.makedirs(os.path.join(self.base_exp_dir, 'renders'), exist_ok=True) for i in range(img_fine.shape[-1]): if len(out_rgb_fine) > 0: if self.mode == 'render': cv.imwrite(os.path.join(self.base_exp_dir, 'renders', 'render_{}.png'.format(idx)), img_fine[..., i]) else: cv.imwrite(os.path.join(self.base_exp_dir, 'validations_fine', '{:0>8d}_{}_{}.png'.format(self.iter_step, i, idx)), np.concatenate([img_fine[..., i], self.dataset.image_at(idx, resolution_level=resolution_level)])) if len(out_normal_fine) > 0: cv.imwrite(os.path.join(self.base_exp_dir, 'normals', '{:0>8d}_{}_{}.png'.format(self.iter_step, i, idx)), normal_img[..., i]) if len(out_depth) > 0: cv.imwrite(os.path.join(self.base_exp_dir, 'depth', '{:0>8d}_{}_{}.png'.format(self.iter_step, i, idx)), depth_img) def validate_mesh(self, scale_mesh=True, resolution=64, threshold=0.0): bound_min = torch.tensor(self.dataset.object_bbox_min, dtype=torch.float32) bound_max = torch.tensor(self.dataset.object_bbox_max, dtype=torch.float32) query_func = lambda pts: -self.sdf_network.sdf(pts)
vertices, triangles = extract_geometry(bound_min, bound_max,
11
2023-11-28 03:13:44+00:00
16k
weijiawu/CisDQ
mask2former_video/data_video/ytvis_eval.py
[ { "identifier": "YTVOS", "path": "mask2former_video/data_video/datasets/ytvis_api/ytvos.py", "snippet": "class YTVOS:\n def __init__(self, annotation_file=None):\n \"\"\"\n Constructor of Microsoft COCO helper class for reading and visualizing annotations.\n :param annotation_fil...
import contextlib import copy import io import itertools import json import logging import numpy as np import os import pycocotools.mask as mask_util import torch import detectron2.utils.comm as comm from collections import OrderedDict from .datasets.ytvis_api.ytvos import YTVOS from .datasets.ytvis_api.ytvoseval import YTVOSeval from tabulate import tabulate from detectron2.config import CfgNode from detectron2.data import MetadataCatalog from detectron2.evaluation import DatasetEvaluator from detectron2.utils.file_io import PathManager from detectron2.utils.logger import create_small_table
12,549
Derive the desired score numbers from summarized COCOeval. Args: coco_eval (None or COCOEval): None represents no predictions from model. iou_type (str): class_names (None or list[str]): if provided, will use it to predict per-category AP. Returns: a dict of {metric name: score} """ metrics = ["AP", "AP50", "AP75", "APs", "APm", "APl", "AR1", "AR10"] if coco_eval is None: self._logger.warn("No predictions from the model!") return {metric: float("nan") for metric in metrics} # the standard metrics results = { metric: float(coco_eval.stats[idx] * 100 if coco_eval.stats[idx] >= 0 else "nan") for idx, metric in enumerate(metrics) } self._logger.info( "Evaluation results for {}: \n".format("segm") + create_small_table(results) ) if not np.isfinite(sum(results.values())): self._logger.info("Some metrics cannot be computed and is shown as NaN.") if class_names is None or len(class_names) <= 1: return results # Compute per-category AP # from https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L222-L252 # noqa precisions = coco_eval.eval["precision"] # precision has dims (iou, recall, cls, area range, max dets) assert len(class_names) == precisions.shape[2] results_per_category = [] for idx, name in enumerate(class_names): # area range index 0: all area ranges # max dets index -1: typically 100 per image precision = precisions[:, :, idx, 0, -1] precision = precision[precision > -1] ap = np.mean(precision) if precision.size else float("nan") results_per_category.append(("{}".format(name), float(ap * 100))) # tabulate it N_COLS = min(6, len(results_per_category) * 2) results_flatten = list(itertools.chain(*results_per_category)) results_2d = itertools.zip_longest(*[results_flatten[i::N_COLS] for i in range(N_COLS)]) table = tabulate( results_2d, tablefmt="pipe", floatfmt=".3f", headers=["category", "AP"] * (N_COLS // 2), numalign="left", ) self._logger.info("Per-category {} AP: \n".format("segm") + table) results.update({"AP-" + name: ap for name, ap in results_per_category}) return results def instances_to_coco_json_video(inputs, outputs): """ Dump an "Instances" object to a COCO-format json that's used for evaluation. Args: instances (Instances): video_id (int): the image id Returns: list[dict]: list of json annotations in COCO format. """ assert len(inputs) == 1, "More than one inputs are loaded for inference!" video_id = inputs[0]["video_id"] video_length = inputs[0]["length"] scores = outputs["pred_scores"] labels = outputs["pred_labels"] masks = outputs["pred_masks"] ytvis_results = [] for instance_id, (s, l, m) in enumerate(zip(scores, labels, masks)): segms = [ mask_util.encode(np.array(_mask[:, :, None], order="F", dtype="uint8"))[0] for _mask in m ] for rle in segms: rle["counts"] = rle["counts"].decode("utf-8") res = { "video_id": video_id, "score": s, "category_id": l, "segmentations": segms, } ytvis_results.append(res) return ytvis_results def _evaluate_predictions_on_coco( coco_gt, coco_results, img_ids=None, ): """ Evaluate the coco results using COCOEval API. """ assert len(coco_results) > 0 coco_results = copy.deepcopy(coco_results) # When evaluating mask AP, if the results contain bbox, cocoapi will # use the box area as the area of the instance, instead of the mask area. # This leads to a different definition of small/medium/large. # We remove the bbox field to let mask AP use mask area. for c in coco_results: c.pop("bbox", None) coco_dt = coco_gt.loadRes(coco_results)
# Copyright (c) Facebook, Inc. and its affiliates. # Modified by Bowen Cheng from https://github.com/sukjunhwang/IFC class YTVISEvaluator(DatasetEvaluator): """ Evaluate AR for object proposals, AP for instance detection/segmentation, AP for keypoint detection outputs using COCO's metrics. See http://cocodataset.org/#detection-eval and http://cocodataset.org/#keypoints-eval to understand its metrics. In addition to COCO, this evaluator is able to support any bounding box detection, instance segmentation, or keypoint detection dataset. """ def __init__( self, dataset_name, tasks=None, distributed=True, output_dir=None, *, use_fast_impl=True, ): """ Args: dataset_name (str): name of the dataset to be evaluated. It must have either the following corresponding metadata: "json_file": the path to the COCO format annotation Or it must be in detectron2's standard dataset format so it can be converted to COCO format automatically. tasks (tuple[str]): tasks that can be evaluated under the given configuration. A task is one of "bbox", "segm", "keypoints". By default, will infer this automatically from predictions. distributed (True): if True, will collect results from all ranks and run evaluation in the main process. Otherwise, will only evaluate the results in the current process. output_dir (str): optional, an output directory to dump all results predicted on the dataset. The dump contains two files: 1. "instances_predictions.pth" a file in torch serialization format that contains all the raw original predictions. 2. "coco_instances_results.json" a json file in COCO's result format. use_fast_impl (bool): use a fast but **unofficial** implementation to compute AP. Although the results should be very close to the official implementation in COCO API, it is still recommended to compute results with the official API for use in papers. The faster implementation also uses more RAM. """ self._logger = logging.getLogger(__name__) self._distributed = distributed self._output_dir = output_dir self._use_fast_impl = use_fast_impl if tasks is not None and isinstance(tasks, CfgNode): self._logger.warning( "COCO Evaluator instantiated using config, this is deprecated behavior." " Please pass in explicit arguments instead." ) self._tasks = None # Infering it from predictions should be better else: self._tasks = tasks self._cpu_device = torch.device("cpu") self._metadata = MetadataCatalog.get(dataset_name) json_file = PathManager.get_local_path(self._metadata.json_file) with contextlib.redirect_stdout(io.StringIO()): self._ytvis_api = YTVOS(json_file) # Test set json files do not contain annotations (evaluation must be # performed using the COCO evaluation server). self._do_evaluation = "annotations" in self._ytvis_api.dataset def reset(self): self._predictions = [] def process(self, inputs, outputs): """ Args: inputs: the inputs to a COCO model (e.g., GeneralizedRCNN). It is a list of dict. Each dict corresponds to an image and contains keys like "height", "width", "file_name", "image_id". outputs: the outputs of a COCO model. It is a list of dicts with key "instances" that contains :class:`Instances`. """ prediction = instances_to_coco_json_video(inputs, outputs) self._predictions.extend(prediction) def evaluate(self): """ Args: img_ids: a list of image IDs to evaluate on. Default to None for the whole dataset """ if self._distributed: comm.synchronize() predictions = comm.gather(self._predictions, dst=0) predictions = list(itertools.chain(*predictions)) if not comm.is_main_process(): return {} else: predictions = self._predictions if len(predictions) == 0: self._logger.warning("[COCOEvaluator] Did not receive valid predictions.") return {} if self._output_dir: PathManager.mkdirs(self._output_dir) file_path = os.path.join(self._output_dir, "instances_predictions.pth") with PathManager.open(file_path, "wb") as f: torch.save(predictions, f) self._results = OrderedDict() self._eval_predictions(predictions) # Copy so the caller can do whatever with results return copy.deepcopy(self._results) def _eval_predictions(self, predictions): """ Evaluate predictions. Fill self._results with the metrics of the tasks. """ self._logger.info("Preparing results for YTVIS format ...") # unmap the category ids for COCO if hasattr(self._metadata, "thing_dataset_id_to_contiguous_id"): dataset_id_to_contiguous_id = self._metadata.thing_dataset_id_to_contiguous_id all_contiguous_ids = list(dataset_id_to_contiguous_id.values()) num_classes = len(all_contiguous_ids) assert min(all_contiguous_ids) == 0 and max(all_contiguous_ids) == num_classes - 1 reverse_id_mapping = {v: k for k, v in dataset_id_to_contiguous_id.items()} for result in predictions: category_id = result["category_id"] assert category_id < num_classes, ( f"A prediction has class={category_id}, " f"but the dataset only has {num_classes} classes and " f"predicted class id should be in [0, {num_classes - 1}]." ) result["category_id"] = reverse_id_mapping[category_id] if self._output_dir: file_path = os.path.join(self._output_dir, "results.json") self._logger.info("Saving results to {}".format(file_path)) with PathManager.open(file_path, "w") as f: f.write(json.dumps(predictions)) f.flush() if not self._do_evaluation: self._logger.info("Annotations are not available for evaluation.") return coco_eval = ( _evaluate_predictions_on_coco( self._ytvis_api, predictions, ) if len(predictions) > 0 else None # cocoapi does not handle empty results very well ) res = self._derive_coco_results( coco_eval, class_names=self._metadata.get("thing_classes") ) self._results["segm"] = res def _derive_coco_results(self, coco_eval, class_names=None): """ Derive the desired score numbers from summarized COCOeval. Args: coco_eval (None or COCOEval): None represents no predictions from model. iou_type (str): class_names (None or list[str]): if provided, will use it to predict per-category AP. Returns: a dict of {metric name: score} """ metrics = ["AP", "AP50", "AP75", "APs", "APm", "APl", "AR1", "AR10"] if coco_eval is None: self._logger.warn("No predictions from the model!") return {metric: float("nan") for metric in metrics} # the standard metrics results = { metric: float(coco_eval.stats[idx] * 100 if coco_eval.stats[idx] >= 0 else "nan") for idx, metric in enumerate(metrics) } self._logger.info( "Evaluation results for {}: \n".format("segm") + create_small_table(results) ) if not np.isfinite(sum(results.values())): self._logger.info("Some metrics cannot be computed and is shown as NaN.") if class_names is None or len(class_names) <= 1: return results # Compute per-category AP # from https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L222-L252 # noqa precisions = coco_eval.eval["precision"] # precision has dims (iou, recall, cls, area range, max dets) assert len(class_names) == precisions.shape[2] results_per_category = [] for idx, name in enumerate(class_names): # area range index 0: all area ranges # max dets index -1: typically 100 per image precision = precisions[:, :, idx, 0, -1] precision = precision[precision > -1] ap = np.mean(precision) if precision.size else float("nan") results_per_category.append(("{}".format(name), float(ap * 100))) # tabulate it N_COLS = min(6, len(results_per_category) * 2) results_flatten = list(itertools.chain(*results_per_category)) results_2d = itertools.zip_longest(*[results_flatten[i::N_COLS] for i in range(N_COLS)]) table = tabulate( results_2d, tablefmt="pipe", floatfmt=".3f", headers=["category", "AP"] * (N_COLS // 2), numalign="left", ) self._logger.info("Per-category {} AP: \n".format("segm") + table) results.update({"AP-" + name: ap for name, ap in results_per_category}) return results def instances_to_coco_json_video(inputs, outputs): """ Dump an "Instances" object to a COCO-format json that's used for evaluation. Args: instances (Instances): video_id (int): the image id Returns: list[dict]: list of json annotations in COCO format. """ assert len(inputs) == 1, "More than one inputs are loaded for inference!" video_id = inputs[0]["video_id"] video_length = inputs[0]["length"] scores = outputs["pred_scores"] labels = outputs["pred_labels"] masks = outputs["pred_masks"] ytvis_results = [] for instance_id, (s, l, m) in enumerate(zip(scores, labels, masks)): segms = [ mask_util.encode(np.array(_mask[:, :, None], order="F", dtype="uint8"))[0] for _mask in m ] for rle in segms: rle["counts"] = rle["counts"].decode("utf-8") res = { "video_id": video_id, "score": s, "category_id": l, "segmentations": segms, } ytvis_results.append(res) return ytvis_results def _evaluate_predictions_on_coco( coco_gt, coco_results, img_ids=None, ): """ Evaluate the coco results using COCOEval API. """ assert len(coco_results) > 0 coco_results = copy.deepcopy(coco_results) # When evaluating mask AP, if the results contain bbox, cocoapi will # use the box area as the area of the instance, instead of the mask area. # This leads to a different definition of small/medium/large. # We remove the bbox field to let mask AP use mask area. for c in coco_results: c.pop("bbox", None) coco_dt = coco_gt.loadRes(coco_results)
coco_eval = YTVOSeval(coco_gt, coco_dt)
1
2023-11-28 10:33:40+00:00
16k
aliyun/pai-python-sdk
pai/api/training_job.py
[ { "identifier": "PaginatedResult", "path": "pai/api/base.py", "snippet": "class PaginatedResult(object):\n \"\"\"A class represent response of a pagination call to PAI service.\"\"\"\n\n items: List[Union[Dict[str, Any], str]] = None\n total_count: int = None\n\n def __init__(self, items: Li...
from typing import Any, Dict, List, Optional from ..api.base import PaginatedResult, ServiceName, WorkspaceScopedResourceAPI from ..libs.alibabacloud_paistudio20220112.models import ( AlgorithmSpec, CreateTrainingJobRequest, CreateTrainingJobRequestComputeResource, CreateTrainingJobRequestHyperParameters, CreateTrainingJobRequestInputChannels, CreateTrainingJobRequestLabels, CreateTrainingJobRequestOutputChannels, CreateTrainingJobRequestScheduler, CreateTrainingJobRequestUserVpc, CreateTrainingJobResponseBody, GetTrainingJobRequest, GetTrainingJobResponseBody, ListTrainingJobLogsRequest, ListTrainingJobLogsResponseBody, ListTrainingJobsRequest, )
11,893
# Copyright 2023 Alibaba, Inc. 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 # # https://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. class TrainingJobAPI(WorkspaceScopedResourceAPI): BACKEND_SERVICE_NAME = ServiceName.PAI_STUDIO _list_method = "list_training_jobs_with_options" _create_method = "create_training_job_with_options" _get_method = "get_training_job_with_options" _list_logs_method = "list_training_job_logs_with_options" # _list_method = "list_training_jobs_with_options" def list( self, page_size: int = 20, page_number: int = 1, order: str = None, sort_by: str = None, status: str = None, training_job_name: str = None, ) -> PaginatedResult: request = ListTrainingJobsRequest( page_size=page_size, page_number=page_number, status=status, training_job_name=training_job_name, order=order, sort_by=sort_by, ) res = self._do_request( method_=self._list_method, tmp_req=request, ) return self.make_paginated_result(res) def get_api_object_by_resource_id(self, resource_id) -> Dict[str, Any]: res: GetTrainingJobResponseBody = self._do_request( method_=self._get_method, training_job_id=resource_id,
# Copyright 2023 Alibaba, Inc. 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 # # https://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. class TrainingJobAPI(WorkspaceScopedResourceAPI): BACKEND_SERVICE_NAME = ServiceName.PAI_STUDIO _list_method = "list_training_jobs_with_options" _create_method = "create_training_job_with_options" _get_method = "get_training_job_with_options" _list_logs_method = "list_training_job_logs_with_options" # _list_method = "list_training_jobs_with_options" def list( self, page_size: int = 20, page_number: int = 1, order: str = None, sort_by: str = None, status: str = None, training_job_name: str = None, ) -> PaginatedResult: request = ListTrainingJobsRequest( page_size=page_size, page_number=page_number, status=status, training_job_name=training_job_name, order=order, sort_by=sort_by, ) res = self._do_request( method_=self._list_method, tmp_req=request, ) return self.make_paginated_result(res) def get_api_object_by_resource_id(self, resource_id) -> Dict[str, Any]: res: GetTrainingJobResponseBody = self._do_request( method_=self._get_method, training_job_id=resource_id,
request=GetTrainingJobRequest(),
13
2023-12-01 01:40:12+00:00
16k
JunMa11/UHNSeg-Quiz
nnunetv2/inference/predict_from_raw_data.py
[ { "identifier": "default_num_processes", "path": "nnunetv2/configuration.py", "snippet": "ANISO_THRESHOLD = 3 # determines when a sample is considered anisotropic (3 means that the spacing in the low" }, { "identifier": "PreprocessAdapterFromNpy", "path": "nnunetv2/inference/data_iterators....
import inspect import multiprocessing import os import traceback import numpy as np import torch import nnunetv2 import argparse import multiprocessing import argparse import multiprocessing from copy import deepcopy from time import sleep from typing import Tuple, Union, List, Optional from acvl_utils.cropping_and_padding.padding import pad_nd_image from batchgenerators.dataloading.multi_threaded_augmenter import MultiThreadedAugmenter from batchgenerators.utilities.file_and_folder_operations import load_json, join, isfile, maybe_mkdir_p, isdir, subdirs, \ save_json from torch import nn from torch._dynamo import OptimizedModule from torch.nn.parallel import DistributedDataParallel from tqdm import tqdm from nnunetv2.configuration import default_num_processes from nnunetv2.inference.data_iterators import PreprocessAdapterFromNpy, preprocessing_iterator_fromfiles, \ preprocessing_iterator_fromnpy from nnunetv2.inference.export_prediction import export_prediction_from_logits, \ convert_predicted_logits_to_segmentation_with_correct_shape from nnunetv2.inference.sliding_window_prediction import compute_gaussian, \ compute_steps_for_sliding_window from nnunetv2.utilities.file_path_utilities import get_output_folder, check_workers_alive_and_busy from nnunetv2.utilities.find_class_by_name import recursive_find_python_class from nnunetv2.utilities.helpers import empty_cache, dummy_context from nnunetv2.utilities.json_export import recursive_fix_for_json_export from nnunetv2.utilities.label_handling.label_handling import determine_num_input_channels from nnunetv2.utilities.plans_handling.plans_handler import PlansManager, ConfigurationManager from nnunetv2.utilities.utils import create_lists_from_splitted_dataset_folder from nnunetv2.paths import nnUNet_results, nnUNet_raw from nnunetv2.imageio.simpleitk_reader_writer import SimpleITKIO
11,147
segs_from_prev_stage_or_list_of_segs_from_prev_stage = [ segs_from_prev_stage_or_list_of_segs_from_prev_stage] if isinstance(truncated_ofname, str): truncated_ofname = [truncated_ofname] if isinstance(properties_or_list_of_properties, dict): properties_or_list_of_properties = [properties_or_list_of_properties] num_processes = min(num_processes, len(list_of_images)) pp = preprocessing_iterator_fromnpy( list_of_images, segs_from_prev_stage_or_list_of_segs_from_prev_stage, properties_or_list_of_properties, truncated_ofname, self.plans_manager, self.dataset_json, self.configuration_manager, num_processes, self.device.type == 'cuda', self.verbose_preprocessing ) return pp def predict_from_list_of_npy_arrays(self, image_or_list_of_images: Union[np.ndarray, List[np.ndarray]], segs_from_prev_stage_or_list_of_segs_from_prev_stage: Union[None, np.ndarray, List[ np.ndarray]], properties_or_list_of_properties: Union[dict, List[dict]], truncated_ofname: Union[str, List[str], None], num_processes: int = 3, save_probabilities: bool = False, num_processes_segmentation_export: int = default_num_processes): iterator = self.get_data_iterator_from_raw_npy_data(image_or_list_of_images, segs_from_prev_stage_or_list_of_segs_from_prev_stage, properties_or_list_of_properties, truncated_ofname, num_processes) return self.predict_from_data_iterator(iterator, save_probabilities, num_processes_segmentation_export) def predict_from_data_iterator(self, data_iterator, save_probabilities: bool = False, num_processes_segmentation_export: int = default_num_processes): """ each element returned by data_iterator must be a dict with 'data', 'ofile' and 'data_properties' keys! If 'ofile' is None, the result will be returned instead of written to a file """ with multiprocessing.get_context("spawn").Pool(num_processes_segmentation_export) as export_pool: worker_list = [i for i in export_pool._pool] r = [] for preprocessed in data_iterator: data = preprocessed['data'] if isinstance(data, str): delfile = data data = torch.from_numpy(np.load(data)) os.remove(delfile) ofile = preprocessed['ofile'] if ofile is not None: print(f'\nPredicting {os.path.basename(ofile)}:') else: print(f'\nPredicting image of shape {data.shape}:') print(f'perform_everything_on_gpu: {self.perform_everything_on_gpu}') properties = preprocessed['data_properties'] # let's not get into a runaway situation where the GPU predicts so fast that the disk has to b swamped with # npy files proceed = not check_workers_alive_and_busy(export_pool, worker_list, r, allowed_num_queued=2) while not proceed: # print('sleeping') sleep(0.1) proceed = not check_workers_alive_and_busy(export_pool, worker_list, r, allowed_num_queued=2) prediction = self.predict_logits_from_preprocessed_data(data).cpu() if ofile is not None: # this needs to go into background processes # export_prediction_from_logits(prediction, properties, configuration_manager, plans_manager, # dataset_json, ofile, save_probabilities) print('sending off prediction to background worker for resampling and export') r.append( export_pool.starmap_async( export_prediction_from_logits, ((prediction, properties, self.configuration_manager, self.plans_manager, self.dataset_json, ofile, save_probabilities),) ) ) else: # convert_predicted_logits_to_segmentation_with_correct_shape(prediction, plans_manager, # configuration_manager, label_manager, # properties, # save_probabilities) print('sending off prediction to background worker for resampling') r.append( export_pool.starmap_async( convert_predicted_logits_to_segmentation_with_correct_shape, ( (prediction, self.plans_manager, self.configuration_manager, self.label_manager, properties, save_probabilities),) ) ) if ofile is not None: print(f'done with {os.path.basename(ofile)}') else: print(f'\nDone with image of shape {data.shape}:') ret = [i.get()[0] for i in r] if isinstance(data_iterator, MultiThreadedAugmenter): data_iterator._finish() # clear lru cache compute_gaussian.cache_clear() # clear device cache
class nnUNetPredictor(object): def __init__(self, tile_step_size: float = 0.5, use_gaussian: bool = True, use_mirroring: bool = True, perform_everything_on_gpu: bool = True, device: torch.device = torch.device('cuda'), verbose: bool = False, verbose_preprocessing: bool = False, allow_tqdm: bool = True): self.verbose = verbose self.verbose_preprocessing = verbose_preprocessing self.allow_tqdm = allow_tqdm self.plans_manager, self.configuration_manager, self.list_of_parameters, self.network, self.dataset_json, \ self.trainer_name, self.allowed_mirroring_axes, self.label_manager = None, None, None, None, None, None, None, None self.tile_step_size = tile_step_size self.use_gaussian = use_gaussian self.use_mirroring = use_mirroring if device.type == 'cuda': # device = torch.device(type='cuda', index=0) # set the desired GPU with CUDA_VISIBLE_DEVICES! # why would I ever want to do that. Stupid dobby. This kills DDP inference... pass if device.type != 'cuda': print(f'perform_everything_on_gpu=True is only supported for cuda devices! Setting this to False') perform_everything_on_gpu = False self.device = device self.perform_everything_on_gpu = perform_everything_on_gpu def initialize_from_trained_model_folder(self, model_training_output_dir: str, use_folds: Union[Tuple[Union[int, str]], None], checkpoint_name: str = 'checkpoint_final.pth'): """ This is used when making predictions with a trained model """ if use_folds is None: use_folds = nnUNetPredictor.auto_detect_available_folds(model_training_output_dir, checkpoint_name) dataset_json = load_json(join(model_training_output_dir, 'dataset.json')) plans = load_json(join(model_training_output_dir, 'plans.json')) plans_manager = PlansManager(plans) if isinstance(use_folds, str): use_folds = [use_folds] parameters = [] for i, f in enumerate(use_folds): f = int(f) if f != 'all' else f checkpoint = torch.load(join(model_training_output_dir, f'fold_{f}', checkpoint_name), map_location=torch.device('cpu')) if i == 0: trainer_name = checkpoint['trainer_name'] configuration_name = checkpoint['init_args']['configuration'] inference_allowed_mirroring_axes = checkpoint['inference_allowed_mirroring_axes'] if \ 'inference_allowed_mirroring_axes' in checkpoint.keys() else None parameters.append(checkpoint['network_weights']) configuration_manager = plans_manager.get_configuration(configuration_name) # restore network num_input_channels = determine_num_input_channels(plans_manager, configuration_manager, dataset_json) trainer_class = recursive_find_python_class(join(nnunetv2.__path__[0], "training", "nnUNetTrainer"), trainer_name, 'nnunetv2.training.nnUNetTrainer') network = trainer_class.build_network_architecture(plans_manager, dataset_json, configuration_manager, num_input_channels, enable_deep_supervision=False) self.plans_manager = plans_manager self.configuration_manager = configuration_manager self.list_of_parameters = parameters self.network = network self.dataset_json = dataset_json self.trainer_name = trainer_name self.allowed_mirroring_axes = inference_allowed_mirroring_axes self.label_manager = plans_manager.get_label_manager(dataset_json) if ('nnUNet_compile' in os.environ.keys()) and (os.environ['nnUNet_compile'].lower() in ('true', '1', 't')) \ and not isinstance(self.network, OptimizedModule): print('compiling network') self.network = torch.compile(self.network) def manual_initialization(self, network: nn.Module, plans_manager: PlansManager, configuration_manager: ConfigurationManager, parameters: Optional[List[dict]], dataset_json: dict, trainer_name: str, inference_allowed_mirroring_axes: Optional[Tuple[int, ...]]): """ This is used by the nnUNetTrainer to initialize nnUNetPredictor for the final validation """ self.plans_manager = plans_manager self.configuration_manager = configuration_manager self.list_of_parameters = parameters self.network = network self.dataset_json = dataset_json self.trainer_name = trainer_name self.allowed_mirroring_axes = inference_allowed_mirroring_axes self.label_manager = plans_manager.get_label_manager(dataset_json) allow_compile = True allow_compile = allow_compile and ('nnUNet_compile' in os.environ.keys()) and (os.environ['nnUNet_compile'].lower() in ('true', '1', 't')) allow_compile = allow_compile and not isinstance(self.network, OptimizedModule) if isinstance(self.network, DistributedDataParallel): allow_compile = allow_compile and isinstance(self.network.module, OptimizedModule) if allow_compile: print('compiling network') self.network = torch.compile(self.network) @staticmethod def auto_detect_available_folds(model_training_output_dir, checkpoint_name): print('use_folds is None, attempting to auto detect available folds') fold_folders = subdirs(model_training_output_dir, prefix='fold_', join=False) fold_folders = [i for i in fold_folders if i != 'fold_all'] fold_folders = [i for i in fold_folders if isfile(join(model_training_output_dir, i, checkpoint_name))] use_folds = [int(i.split('_')[-1]) for i in fold_folders] print(f'found the following folds: {use_folds}') return use_folds def _manage_input_and_output_lists(self, list_of_lists_or_source_folder: Union[str, List[List[str]]], output_folder_or_list_of_truncated_output_files: Union[None, str, List[str]], folder_with_segs_from_prev_stage: str = None, overwrite: bool = True, part_id: int = 0, num_parts: int = 1, save_probabilities: bool = False): if isinstance(list_of_lists_or_source_folder, str): list_of_lists_or_source_folder = create_lists_from_splitted_dataset_folder(list_of_lists_or_source_folder, self.dataset_json['file_ending']) print(f'There are {len(list_of_lists_or_source_folder)} cases in the source folder') list_of_lists_or_source_folder = list_of_lists_or_source_folder[part_id::num_parts] caseids = [os.path.basename(i[0])[:-(len(self.dataset_json['file_ending']) + 5)] for i in list_of_lists_or_source_folder] print( f'I am process {part_id} out of {num_parts} (max process ID is {num_parts - 1}, we start counting with 0!)') print(f'There are {len(caseids)} cases that I would like to predict') if isinstance(output_folder_or_list_of_truncated_output_files, str): output_filename_truncated = [join(output_folder_or_list_of_truncated_output_files, i) for i in caseids] else: output_filename_truncated = output_folder_or_list_of_truncated_output_files seg_from_prev_stage_files = [join(folder_with_segs_from_prev_stage, i + self.dataset_json['file_ending']) if folder_with_segs_from_prev_stage is not None else None for i in caseids] # remove already predicted files form the lists if not overwrite and output_filename_truncated is not None: tmp = [isfile(i + self.dataset_json['file_ending']) for i in output_filename_truncated] if save_probabilities: tmp2 = [isfile(i + '.npz') for i in output_filename_truncated] tmp = [i and j for i, j in zip(tmp, tmp2)] not_existing_indices = [i for i, j in enumerate(tmp) if not j] output_filename_truncated = [output_filename_truncated[i] for i in not_existing_indices] list_of_lists_or_source_folder = [list_of_lists_or_source_folder[i] for i in not_existing_indices] seg_from_prev_stage_files = [seg_from_prev_stage_files[i] for i in not_existing_indices] print(f'overwrite was set to {overwrite}, so I am only working on cases that haven\'t been predicted yet. ' f'That\'s {len(not_existing_indices)} cases.') return list_of_lists_or_source_folder, output_filename_truncated, seg_from_prev_stage_files def predict_from_files(self, list_of_lists_or_source_folder: Union[str, List[List[str]]], output_folder_or_list_of_truncated_output_files: Union[str, None, List[str]], save_probabilities: bool = False, overwrite: bool = True, num_processes_preprocessing: int = default_num_processes, num_processes_segmentation_export: int = default_num_processes, folder_with_segs_from_prev_stage: str = None, num_parts: int = 1, part_id: int = 0): """ This is nnU-Net's default function for making predictions. It works best for batch predictions (predicting many images at once). """ if isinstance(output_folder_or_list_of_truncated_output_files, str): output_folder = output_folder_or_list_of_truncated_output_files elif isinstance(output_folder_or_list_of_truncated_output_files, list): output_folder = os.path.dirname(output_folder_or_list_of_truncated_output_files[0]) else: output_folder = None ######################## # let's store the input arguments so that its clear what was used to generate the prediction if output_folder is not None: my_init_kwargs = {} for k in inspect.signature(self.predict_from_files).parameters.keys(): my_init_kwargs[k] = locals()[k] my_init_kwargs = deepcopy( my_init_kwargs) # let's not unintentionally change anything in-place. Take this as a recursive_fix_for_json_export(my_init_kwargs) maybe_mkdir_p(output_folder) save_json(my_init_kwargs, join(output_folder, 'predict_from_raw_data_args.json')) # we need these two if we want to do things with the predictions like for example apply postprocessing save_json(self.dataset_json, join(output_folder, 'dataset.json'), sort_keys=False) save_json(self.plans_manager.plans, join(output_folder, 'plans.json'), sort_keys=False) ####################### # check if we need a prediction from the previous stage if self.configuration_manager.previous_stage_name is not None: assert folder_with_segs_from_prev_stage is not None, \ f'The requested configuration is a cascaded network. It requires the segmentations of the previous ' \ f'stage ({self.configuration_manager.previous_stage_name}) as input. Please provide the folder where' \ f' they are located via folder_with_segs_from_prev_stage' # sort out input and output filenames list_of_lists_or_source_folder, output_filename_truncated, seg_from_prev_stage_files = \ self._manage_input_and_output_lists(list_of_lists_or_source_folder, output_folder_or_list_of_truncated_output_files, folder_with_segs_from_prev_stage, overwrite, part_id, num_parts, save_probabilities) if len(list_of_lists_or_source_folder) == 0: return data_iterator = self._internal_get_data_iterator_from_lists_of_filenames(list_of_lists_or_source_folder, seg_from_prev_stage_files, output_filename_truncated, num_processes_preprocessing) return self.predict_from_data_iterator(data_iterator, save_probabilities, num_processes_segmentation_export) def _internal_get_data_iterator_from_lists_of_filenames(self, input_list_of_lists: List[List[str]], seg_from_prev_stage_files: Union[List[str], None], output_filenames_truncated: Union[List[str], None], num_processes: int): return preprocessing_iterator_fromfiles(input_list_of_lists, seg_from_prev_stage_files, output_filenames_truncated, self.plans_manager, self.dataset_json, self.configuration_manager, num_processes, self.device.type == 'cuda', self.verbose_preprocessing) # preprocessor = self.configuration_manager.preprocessor_class(verbose=self.verbose_preprocessing) # # hijack batchgenerators, yo # # we use the multiprocessing of the batchgenerators dataloader to handle all the background worker stuff. This # # way we don't have to reinvent the wheel here. # num_processes = max(1, min(num_processes, len(input_list_of_lists))) # ppa = PreprocessAdapter(input_list_of_lists, seg_from_prev_stage_files, preprocessor, # output_filenames_truncated, self.plans_manager, self.dataset_json, # self.configuration_manager, num_processes) # if num_processes == 0: # mta = SingleThreadedAugmenter(ppa, None) # else: # mta = MultiThreadedAugmenter(ppa, None, num_processes, 1, None, pin_memory=pin_memory) # return mta def get_data_iterator_from_raw_npy_data(self, image_or_list_of_images: Union[np.ndarray, List[np.ndarray]], segs_from_prev_stage_or_list_of_segs_from_prev_stage: Union[None, np.ndarray, List[ np.ndarray]], properties_or_list_of_properties: Union[dict, List[dict]], truncated_ofname: Union[str, List[str], None], num_processes: int = 3): list_of_images = [image_or_list_of_images] if not isinstance(image_or_list_of_images, list) else \ image_or_list_of_images if isinstance(segs_from_prev_stage_or_list_of_segs_from_prev_stage, np.ndarray): segs_from_prev_stage_or_list_of_segs_from_prev_stage = [ segs_from_prev_stage_or_list_of_segs_from_prev_stage] if isinstance(truncated_ofname, str): truncated_ofname = [truncated_ofname] if isinstance(properties_or_list_of_properties, dict): properties_or_list_of_properties = [properties_or_list_of_properties] num_processes = min(num_processes, len(list_of_images)) pp = preprocessing_iterator_fromnpy( list_of_images, segs_from_prev_stage_or_list_of_segs_from_prev_stage, properties_or_list_of_properties, truncated_ofname, self.plans_manager, self.dataset_json, self.configuration_manager, num_processes, self.device.type == 'cuda', self.verbose_preprocessing ) return pp def predict_from_list_of_npy_arrays(self, image_or_list_of_images: Union[np.ndarray, List[np.ndarray]], segs_from_prev_stage_or_list_of_segs_from_prev_stage: Union[None, np.ndarray, List[ np.ndarray]], properties_or_list_of_properties: Union[dict, List[dict]], truncated_ofname: Union[str, List[str], None], num_processes: int = 3, save_probabilities: bool = False, num_processes_segmentation_export: int = default_num_processes): iterator = self.get_data_iterator_from_raw_npy_data(image_or_list_of_images, segs_from_prev_stage_or_list_of_segs_from_prev_stage, properties_or_list_of_properties, truncated_ofname, num_processes) return self.predict_from_data_iterator(iterator, save_probabilities, num_processes_segmentation_export) def predict_from_data_iterator(self, data_iterator, save_probabilities: bool = False, num_processes_segmentation_export: int = default_num_processes): """ each element returned by data_iterator must be a dict with 'data', 'ofile' and 'data_properties' keys! If 'ofile' is None, the result will be returned instead of written to a file """ with multiprocessing.get_context("spawn").Pool(num_processes_segmentation_export) as export_pool: worker_list = [i for i in export_pool._pool] r = [] for preprocessed in data_iterator: data = preprocessed['data'] if isinstance(data, str): delfile = data data = torch.from_numpy(np.load(data)) os.remove(delfile) ofile = preprocessed['ofile'] if ofile is not None: print(f'\nPredicting {os.path.basename(ofile)}:') else: print(f'\nPredicting image of shape {data.shape}:') print(f'perform_everything_on_gpu: {self.perform_everything_on_gpu}') properties = preprocessed['data_properties'] # let's not get into a runaway situation where the GPU predicts so fast that the disk has to b swamped with # npy files proceed = not check_workers_alive_and_busy(export_pool, worker_list, r, allowed_num_queued=2) while not proceed: # print('sleeping') sleep(0.1) proceed = not check_workers_alive_and_busy(export_pool, worker_list, r, allowed_num_queued=2) prediction = self.predict_logits_from_preprocessed_data(data).cpu() if ofile is not None: # this needs to go into background processes # export_prediction_from_logits(prediction, properties, configuration_manager, plans_manager, # dataset_json, ofile, save_probabilities) print('sending off prediction to background worker for resampling and export') r.append( export_pool.starmap_async( export_prediction_from_logits, ((prediction, properties, self.configuration_manager, self.plans_manager, self.dataset_json, ofile, save_probabilities),) ) ) else: # convert_predicted_logits_to_segmentation_with_correct_shape(prediction, plans_manager, # configuration_manager, label_manager, # properties, # save_probabilities) print('sending off prediction to background worker for resampling') r.append( export_pool.starmap_async( convert_predicted_logits_to_segmentation_with_correct_shape, ( (prediction, self.plans_manager, self.configuration_manager, self.label_manager, properties, save_probabilities),) ) ) if ofile is not None: print(f'done with {os.path.basename(ofile)}') else: print(f'\nDone with image of shape {data.shape}:') ret = [i.get()[0] for i in r] if isinstance(data_iterator, MultiThreadedAugmenter): data_iterator._finish() # clear lru cache compute_gaussian.cache_clear() # clear device cache
empty_cache(self.device)
11
2023-12-04 19:43:14+00:00
16k
Zuricho/chroma_pipeline
chroma/models/graph_classifier.py
[ { "identifier": "validate_XC", "path": "chroma/data/xcs.py", "snippet": "def validate_XCS(all_atom=None, sequence=True):\n def decorator(func):\n def new_func(*args, **kwargs):" }, { "identifier": "basic", "path": "chroma/layers/basic.py", "snippet": "class NoOp(nn.Module):\ncl...
from types import SimpleNamespace from chroma.data.xcs import validate_XC from chroma.layers import basic from chroma.layers.attention import AttentionChainPool from chroma.layers.basic import NodeProduct, NoOp from chroma.layers.graph import MLP, MaskedNorm from chroma.layers.structure import diffusion from chroma.models.graph_design import BackboneEncoderGNN from chroma.utility.model import load_model as utility_load_model import torch import torch.nn as nn
10,850
if "random_fourier_2mer" in args.edge_features: index = args.edge_features.index("random_fourier_2mer") args.edge_features.pop(index) args.edge_features.append( ( "random_fourier_2mer", { "dim_embedding": args.dim_edges, "trainable": False, "scale": args.fourier_scale, }, ) ) # Encoder GNN process backbone self.encoder = BackboneEncoderGNN( dim_nodes=args.dim_nodes, dim_edges=args.dim_edges, num_neighbors=args.num_neighbors, node_features=args.node_features, edge_features=args.edge_features, num_layers=args.num_layers, node_mlp_layers=args.node_mlp_layers, node_mlp_dim=args.node_mlp_dim, edge_update=args.edge_update, edge_mlp_layers=args.edge_mlp_layers, edge_mlp_dim=args.edge_mlp_dim, mlp_activation=args.mlp_activation, dropout=args.dropout, skip_connect_input=args.skip_connect_input, graph_criterion=args.graph_criterion, graph_random_min_local=args.graph_random_min_local, checkpoint_gradients=checkpoint_gradients, ) self.time_feature_type = args.time_feature_type self.time_log_feature_scaling = time_log_feature_scaling self.use_time_features = use_time_features if self.use_time_features: self.time_features = basic.FourierFeaturization( d_input=1, d_model=dim_nodes, trainable=False, scale=16.0 ) self.sequence_embedding = nn.Embedding(20, dim_nodes) self.noise_perturb = diffusion.DiffusionChainCov( noise_schedule=args.noise_schedule, beta_min=args.noise_beta_min, beta_max=args.noise_beta_max, log_snr_range=args.noise_log_snr_range, covariance_model=args.noise_covariance_model, ) self._init_heads(class_config, dim_nodes, out_mlp_layers, dropout) self.condition_sequence_frequency = 0.3 def _init_heads(self, class_config, dim_nodes, out_mlp_layers, dropout): self.heads = {"chain": {}, "first_order": {}, "second_order": {}, "complex": {}} for label, config in class_config.items(): group = config["level"] if label == "is_interface" or label == "contact": dim_out = 1 else: dim_out = len(config["tokens"]) if group == "chain": pool = AttentionChainPool(8, dim_nodes) elif group == "complex": raise NotImplementedError elif group == "second_order": pool = NoOp() else: pool = NoOp() if group != "second_order": if self.zero_grad_fix: node_norm_layer = MaskedNorm( dim=1, num_features=dim_nodes, affine=True, norm="layer" ) mlp = MLP( dim_nodes, dim_hidden=None, dim_out=dim_out, num_layers_hidden=out_mlp_layers, activation=self.mlp_activation, dropout=dropout, ) head = nn.Sequential(node_norm_layer, mlp) else: mlp = MLP( dim_nodes, dim_hidden=None, dim_out=dim_out, num_layers_hidden=out_mlp_layers, activation="relu", dropout=dropout, ) head = mlp else: head = nn.Sequential(nn.Linear(dim_nodes, 16), NodeProduct(16, 1)) self.heads[group][label] = head, pool self.add_module(f"{label}_head", head) if pool is not None: self.add_module(f"{label}_pool", pool) def _time_features(self, t): h = { "t": lambda: t, "log_snr": lambda: self.noise_perturb.noise_schedule.log_SNR(t), }[self.time_feature_type]() if "log" in self.time_feature_type: h = self.time_log_feature_scaling * h time_h = self.time_features(h[:, None, None]) return time_h
# Copyright Generate Biomedicines, Inc. # # 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. """Models for generating protein sequence and side chain conformations given backbones. These can be used for sequence design and packing. """ class GraphClassifier(nn.Module): """Graph-based protein classification Args: See documention of `structure.protein_graph.ProteinFeatureGraph`, and `graph.GraphNN` for more details. Inputs: X (Tensor): Backbone coordinates with shape `(num_batch, num_residues, num_atoms, 3)`. C (LongTensor): Chain map with shape `(num_batch, num_residues)`. O (Tensor) (optional): One-hot sequence tensor of shape `(num_batch, num_residues)` Outputs: node_h (Tensor): residue-based representations that can be used to project various classification predictions """ def __init__( self, dim_nodes=128, dim_edges=128, num_neighbors=30, node_features=(("internal_coords", {"log_lengths": True}),), edge_features=["random_fourier_2mer", "orientations_2mer", "distances_chain"], num_layers=3, dropout=0.1, node_mlp_layers=1, node_mlp_dim=None, edge_update=True, edge_mlp_layers=1, edge_mlp_dim=None, skip_connect_input=False, mlp_activation="softplus", graph_criterion="knn", graph_random_min_local=20, use_time_features=True, noise_schedule="log_snr", noise_beta_min=0.2, noise_beta_max=70.0, checkpoint_gradients=False, class_config={}, out_mlp_layers=2, noise_covariance_model="globular", noise_log_snr_range=(-7.0, 13.5), time_feature_type="t", time_log_feature_scaling=0.05, fourier_scale=16.0, zero_grad_fix=False, **kwargs, ): """Initialize GraphBackbone network.""" super().__init__() # Save configuration in kwargs self.kwargs = locals() self.kwargs.pop("self") for key in list(self.kwargs.keys()): if key.startswith("__") and key.endswith("__"): self.kwargs.pop(key) args = SimpleNamespace(**self.kwargs) self.class_config = class_config # Important global options self.dim_nodes = args.dim_nodes self.dim_edges = args.dim_edges self.mlp_activation = args.mlp_activation self.zero_grad_fix = zero_grad_fix if "random_fourier_2mer" in args.edge_features: index = args.edge_features.index("random_fourier_2mer") args.edge_features.pop(index) args.edge_features.append( ( "random_fourier_2mer", { "dim_embedding": args.dim_edges, "trainable": False, "scale": args.fourier_scale, }, ) ) # Encoder GNN process backbone self.encoder = BackboneEncoderGNN( dim_nodes=args.dim_nodes, dim_edges=args.dim_edges, num_neighbors=args.num_neighbors, node_features=args.node_features, edge_features=args.edge_features, num_layers=args.num_layers, node_mlp_layers=args.node_mlp_layers, node_mlp_dim=args.node_mlp_dim, edge_update=args.edge_update, edge_mlp_layers=args.edge_mlp_layers, edge_mlp_dim=args.edge_mlp_dim, mlp_activation=args.mlp_activation, dropout=args.dropout, skip_connect_input=args.skip_connect_input, graph_criterion=args.graph_criterion, graph_random_min_local=args.graph_random_min_local, checkpoint_gradients=checkpoint_gradients, ) self.time_feature_type = args.time_feature_type self.time_log_feature_scaling = time_log_feature_scaling self.use_time_features = use_time_features if self.use_time_features: self.time_features = basic.FourierFeaturization( d_input=1, d_model=dim_nodes, trainable=False, scale=16.0 ) self.sequence_embedding = nn.Embedding(20, dim_nodes) self.noise_perturb = diffusion.DiffusionChainCov( noise_schedule=args.noise_schedule, beta_min=args.noise_beta_min, beta_max=args.noise_beta_max, log_snr_range=args.noise_log_snr_range, covariance_model=args.noise_covariance_model, ) self._init_heads(class_config, dim_nodes, out_mlp_layers, dropout) self.condition_sequence_frequency = 0.3 def _init_heads(self, class_config, dim_nodes, out_mlp_layers, dropout): self.heads = {"chain": {}, "first_order": {}, "second_order": {}, "complex": {}} for label, config in class_config.items(): group = config["level"] if label == "is_interface" or label == "contact": dim_out = 1 else: dim_out = len(config["tokens"]) if group == "chain": pool = AttentionChainPool(8, dim_nodes) elif group == "complex": raise NotImplementedError elif group == "second_order": pool = NoOp() else: pool = NoOp() if group != "second_order": if self.zero_grad_fix: node_norm_layer = MaskedNorm( dim=1, num_features=dim_nodes, affine=True, norm="layer" ) mlp = MLP( dim_nodes, dim_hidden=None, dim_out=dim_out, num_layers_hidden=out_mlp_layers, activation=self.mlp_activation, dropout=dropout, ) head = nn.Sequential(node_norm_layer, mlp) else: mlp = MLP( dim_nodes, dim_hidden=None, dim_out=dim_out, num_layers_hidden=out_mlp_layers, activation="relu", dropout=dropout, ) head = mlp else: head = nn.Sequential(nn.Linear(dim_nodes, 16), NodeProduct(16, 1)) self.heads[group][label] = head, pool self.add_module(f"{label}_head", head) if pool is not None: self.add_module(f"{label}_pool", pool) def _time_features(self, t): h = { "t": lambda: t, "log_snr": lambda: self.noise_perturb.noise_schedule.log_SNR(t), }[self.time_feature_type]() if "log" in self.time_feature_type: h = self.time_log_feature_scaling * h time_h = self.time_features(h[:, None, None]) return time_h
@validate_XC()
0
2023-11-28 00:09:40+00:00
16k
BiQiWHU/CMFormer
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "mask2former/config.py", "snippet": "def add_maskformer2_config(cfg):\n \"\"\"\n Add config for MASK_FORMER.\n \"\"\"\n # NOTE: configs from original maskformer\n # data config\n # select the dataset mapper\n cfg.INPUT.DATASET_MAPPER...
from shapely.errors import ShapelyDeprecationWarning from collections import OrderedDict from typing import Any, Dict, List, Set from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.data import MetadataCatalog, build_detection_train_loader from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, ) from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler from detectron2.solver.build import maybe_add_gradient_clipping from detectron2.utils.logger import setup_logger from mask2former import ( COCOInstanceNewBaselineDatasetMapper, COCOPanopticNewBaselineDatasetMapper, InstanceSegEvaluator, MaskFormerInstanceDatasetMapper, MaskFormerPanopticDatasetMapper, MaskFormerSemanticDatasetMapper, SemanticSegmentorWithTTA, add_maskformer2_config, ) import warnings import copy import itertools import logging import os import torch import detectron2.utils.comm as comm
11,205
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings('ignore', category=ShapelyDeprecationWarning) except: pass os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Cityscapes if evaluator_type == "cityscapes_instance": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesInstanceEvaluator(dataset_name) if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesSemSegEvaluator(dataset_name) if evaluator_type == "cityscapes_panoptic_seg": if cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesSemSegEvaluator(dataset_name)) if cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesInstanceEvaluator(dataset_name)) # ADE20K if evaluator_type == "ade20k_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) # LVIS if evaluator_type == "lvis": return LVISEvaluator(dataset_name, output_dir=output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic":
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings('ignore', category=ShapelyDeprecationWarning) except: pass os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Cityscapes if evaluator_type == "cityscapes_instance": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesInstanceEvaluator(dataset_name) if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesSemSegEvaluator(dataset_name) if evaluator_type == "cityscapes_panoptic_seg": if cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesSemSegEvaluator(dataset_name)) if cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesInstanceEvaluator(dataset_name)) # ADE20K if evaluator_type == "ade20k_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) # LVIS if evaluator_type == "lvis": return LVISEvaluator(dataset_name, output_dir=output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic":
mapper = MaskFormerSemanticDatasetMapper(cfg, True)
5
2023-11-29 15:26:53+00:00
16k
PopicLab/insilicoSV
test/test_processing.py
[ { "identifier": "SV_Simulator", "path": "insilicosv/simulate.py", "snippet": "class SV_Simulator:\n def __init__(self, par_file, log_file=None):\n \"\"\"\n par_file: file location to configuration file (.yaml)\n log_file: location to store log file with diagnostic information if ...
from insilicosv.simulate import SV_Simulator from insilicosv.processing import FormatterIO from test_simulate import TestObject from pysam import VariantFile, FastaFile from collections import defaultdict, Counter from insilicosv.utils import NestedDict from insilicosv import utils from insilicosv import constants import unittest import sys import os
14,074
"num_overlap": [2, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap2': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "overlap_events": { "bed": [self.test_overlap_bed, self.test_overlap_bed_2], "allow_types": ["L1HS", "ALR/Alpha"]}, "variant_sets": [{"type": "DEL", "number": 4, "min_length": [1], "max_length": [5], "num_overlap": [3, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap3': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": { "bed": [self.test_overlap_bed, self.test_overlap_bed_2], "allow_types": ["L1", "ALR"]}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [5], "num_overlap": [3, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap4': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": { "bed": [self.test_overlap_bed, self.test_overlap_bed_2], "allow_types": "L1"}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [5], "num_overlap": 2}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap5': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": { "bed": self.test_overlap_bed_3, "allow_types": "ALR"}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [5], "num_overlap": 2}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap6': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [2], "max_length": [4], "num_overlap": [1, 1, 1, 1, 1]}, {"type": "DEL", "number": 5, "min_length": [6], "max_length": [8], "num_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap7': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [1], "num_partial_overlap": [1, 1, 1, 1, 1]}, {"type": "DEL", "number": 5, "min_length": [2], "max_length": [2], "num_partial_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap8': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "dDUP", "number": 5, "min_length": [2, 1], "max_length": [4, 1], "num_overlap": [1, 1, 1, 1, 1]}, {"type": "dDUP", "number": 5, "min_length": [6, 1], "max_length": [8, 1], "num_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap9': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "dDUP", "number": 5, "min_length": [1, 1], "max_length": [1, 1], "num_partial_overlap": [1, 1, 1, 1, 1]}, {"type": "dDUP", "number": 5, "min_length": [1, 1], "max_length": [2, 1], "num_partial_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf) } self.test_objects_alu_mediated = {'alu_med1': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_4}, "variant_sets": [{"type": "DEL", "number": 1, "min_length": [13], "max_length": [15], "num_alu_mediated": 1}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.formatter = FormatterIO(self.par) def tearDown(self): utils.remove_file(self.ins_fasta) utils.remove_file(self.bed) utils.remove_file(self.vcf) utils.remove_file(self.par) def initialize_test(self, test_objects_dict, sv_type, output_type='bed', ins_fasta=None): # function to execute the shared logic for simulating SVs from test objects and generating bed/vcf output config = test_objects_dict[sv_type] config.initialize_files()
class TestProcObject(TestObject): def __init__(self, ref, par, hap1, hap2, bed, vcf): self.vcf = vcf super().__init__(ref, par, hap1, hap2, bed) def extract_bed_records(self): # parse bed record into dict for easy comparison # --> example split bed record: ['chr19', '0', '3', 'chr19', '0', '3', 'DEL', '3', '1/1', 'DEL', '1'] bed_records = [] with open(self.bed) as f: for line in f: ln = line.split() bed_record = {'source_chr': ln[0], 'source_s': ln[1], 'source_e': ln[2], 'target_chr': ln[3], 'target_s': ln[4], 'target_e': ln[5], 'ev_type': ln[6], 'len': ln[7], 'zyg': ln[8], 'parent_type': ln[9], 'sv_id': ln[10]} bed_records.append(bed_record) return bed_records def extract_vcf_records(self): vcf_records = [] vcf = VariantFile(self.vcf) for rec in vcf.fetch(): ln = str(rec).split() # separately parse info field of the form: 'END=45590417;SVTYPE=dDUP;SVLEN=539;TARGET=45581738' info = {field.split('=')[0]: field.split('=')[1] for field in ln[7].split(';')} vcf_record = {'CHROM': ln[0], 'POS': ln[1], 'ID': ln[2], 'REF': ln[3], 'ALT': ln[4], 'QUAL': ln[5], 'FILTER': ln[6], 'INFO': info, 'FORMAT': ln[8], 'SAMPLE': ln[9]} vcf_records.append(vcf_record) return vcf_records class TestProcessing(unittest.TestCase): def setUp(self): # runs before every test self.ref_file = "test/inputs/test.fa" self.par = "test/inputs/par.yaml" self.hap1 = "test/inputs/test1.fa" self.hap2 = "test/inputs/test2.fa" self.bed = "test/inputs/out.bed" self.vcf = "test/inputs/out.vcf" self.ins_fasta = "test/inputs/ins_fasta.fa" self.test_overlap_bed = "test/inputs/example_overlap_events.bed" self.test_overlap_bed_2 = "test/inputs/example_overlap_events_2.bed" # test_overlap_bed_3: events with differing chromosome self.test_overlap_bed_3 = "test/inputs/example_overlap_events_3.bed" self.test_overlap_bed_4 = "test/inputs/example_overlap_events_4.bed" self.test_overlap_bed_11 = "test/inputs/example_overlap_events_11.bed" self.test_objects_simple_events = {'DEL': TestProcObject([self.ref_file, {"chr19": "CTG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "max_tries": 50, "prioritize_top": True}, "variant_sets": [{"type": "DEL", "number": 1, "max_length": [3], "min_length": [3]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'DUP': TestProcObject([self.ref_file, {"chr19": "CTG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "max_tries": 50, "prioritize_top": True}, "variant_sets": [{"type": "DUP", "number": 1, "max_length": [3], "min_length": [3]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'INV': TestProcObject([self.ref_file, {"chr19": "CTG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "max_tries": 50, "prioritize_top": True}, "variant_sets": [{"type": "INV", "number": 1, "max_length": [3], "min_length": [3]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'INS': TestProcObject([self.ref_file, {"chr19": "C"}], [self.par, {"sim_settings": {"reference": self.ref_file, "max_tries": 50, "prioritize_top": True}, "variant_sets": [{"type": "INS", "number": 1, "max_length": [3], "min_length": [3]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_flanked_inversions = {'dupINVdup': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "dupINVdup", "number": 1, "max_length": [2, 2, 2], "min_length": [2, 2, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'delINVdel': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "delINVdel", "number": 1, "max_length": [2, 2, 2], "min_length": [2, 2, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'dupINVdel': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "dupINVdel", "number": 1, "max_length": [2, 2, 2], "min_length": [2, 2, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'delINVdup': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "delINVdup", "number": 1, "max_length": [2, 2, 2], "min_length": [2, 2, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_dispersions = {'dDUP': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "dDUP", "number": 1, "max_length": [3, 3], "min_length": [3, 3]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'INV_dDUP': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "INV_dDUP", "number": 1, "max_length": [3, 3], "min_length": [3, 3]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'TRA': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "TRA", "number": 1, "max_length": [3, 3], "min_length": [3, 3]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_del_inv = {'delINV': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "delINV", "number": 1, "max_length": [3, 3], "min_length": [3, 3]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'INVdel': TestProcObject([self.ref_file, {"chr19": "ACTGTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "INVdel", "number": 1, "max_length": [3, 3], "min_length": [3, 3]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_idel = {'dDUP_iDEL': TestProcObject([self.ref_file, {"chr19": "ACTGTCAG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "dDUP_iDEL", "number": 1, "max_length": [3, 3, 2], "min_length": [3, 3, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'INS_iDEL': TestProcObject([self.ref_file, {"chr19": "ACTGTCAG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "INS_iDEL", "number": 1, "max_length": [3, 3, 2], "min_length": [3, 3, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_dup_inv = {'dup_INV': TestProcObject([self.ref_file, {"chr19": "ACTGTCAG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "dup_INV", "number": 1, "max_length": [4, 4], "min_length": [4, 4]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'INV_dup': TestProcObject([self.ref_file, {"chr19": "ACTGTCAG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "INV_dup", "number": 1, "max_length": [4, 4], "min_length": [4, 4]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_INVdup = {'INVdup': TestProcObject([self.ref_file, {"chr19": "ACTG"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "variant_sets": [{"type": "INVdup", "number": 1, "max_length": [4], "min_length": [4]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_multievent = {'INVdup': TestProcObject([self.ref_file, {"chr19": "ACTGCTAATGCGTTCACTGCTAATGCGTTC"}], [self.par, {"sim_settings": {"reference": self.ref_file, "max_tries": 200, "prioritize_top": True}, "variant_sets": [{"type": "INVdup", "number": 3, "max_length": [4], "min_length": [2]}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.test_objects_overlap_simple = {'overlap1': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": { "bed": [self.test_overlap_bed, self.test_overlap_bed_2], "allow_types": ["L1HS", "ALR/Alpha"]}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [5], "num_overlap": [2, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap2': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True}, "overlap_events": { "bed": [self.test_overlap_bed, self.test_overlap_bed_2], "allow_types": ["L1HS", "ALR/Alpha"]}, "variant_sets": [{"type": "DEL", "number": 4, "min_length": [1], "max_length": [5], "num_overlap": [3, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap3': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": { "bed": [self.test_overlap_bed, self.test_overlap_bed_2], "allow_types": ["L1", "ALR"]}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [5], "num_overlap": [3, 2]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap4': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": { "bed": [self.test_overlap_bed, self.test_overlap_bed_2], "allow_types": "L1"}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [5], "num_overlap": 2}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap5': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": { "bed": self.test_overlap_bed_3, "allow_types": "ALR"}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [5], "num_overlap": 2}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap6': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [2], "max_length": [4], "num_overlap": [1, 1, 1, 1, 1]}, {"type": "DEL", "number": 5, "min_length": [6], "max_length": [8], "num_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap7': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "DEL", "number": 5, "min_length": [1], "max_length": [1], "num_partial_overlap": [1, 1, 1, 1, 1]}, {"type": "DEL", "number": 5, "min_length": [2], "max_length": [2], "num_partial_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap8': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "dDUP", "number": 5, "min_length": [2, 1], "max_length": [4, 1], "num_overlap": [1, 1, 1, 1, 1]}, {"type": "dDUP", "number": 5, "min_length": [6, 1], "max_length": [8, 1], "num_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf), 'overlap9': TestProcObject([self.ref_file, {"chr21": "CCTCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTATCCGTCGTACTAAGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_11, "allow_types": ['Alu', 'L1', 'L2', 'SVA', 'HERVK']}, "variant_sets": [{"type": "dDUP", "number": 5, "min_length": [1, 1], "max_length": [1, 1], "num_partial_overlap": [1, 1, 1, 1, 1]}, {"type": "dDUP", "number": 5, "min_length": [1, 1], "max_length": [2, 1], "num_partial_overlap": [1, 1, 1, 1, 1]}]}], self.hap1, self.hap2, self.bed, self.vcf) } self.test_objects_alu_mediated = {'alu_med1': TestProcObject([self.ref_file, {"chr21": "CTCCGTCGTACTAAGTCGTACTCCGTCGTACTAAGTCGTA"}], [self.par, {"sim_settings": {"reference": self.ref_file, "prioritize_top": True, "fail_if_placement_issues": True}, "overlap_events": {"bed": self.test_overlap_bed_4}, "variant_sets": [{"type": "DEL", "number": 1, "min_length": [13], "max_length": [15], "num_alu_mediated": 1}]}], self.hap1, self.hap2, self.bed, self.vcf)} self.formatter = FormatterIO(self.par) def tearDown(self): utils.remove_file(self.ins_fasta) utils.remove_file(self.bed) utils.remove_file(self.vcf) utils.remove_file(self.par) def initialize_test(self, test_objects_dict, sv_type, output_type='bed', ins_fasta=None): # function to execute the shared logic for simulating SVs from test objects and generating bed/vcf output config = test_objects_dict[sv_type] config.initialize_files()
curr_sim = SV_Simulator(config.par)
0
2023-12-01 14:39:20+00:00
16k
BiQiWHU/BWG
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "mask2former/config.py", "snippet": "def add_maskformer2_config(cfg):\n \"\"\"\n Add config for MASK_FORMER.\n \"\"\"\n # NOTE: configs from original maskformer\n # data config\n # select the dataset mapper\n cfg.INPUT.DATASET_MAPPER...
from shapely.errors import ShapelyDeprecationWarning from collections import OrderedDict from typing import Any, Dict, List, Set from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.data import MetadataCatalog, build_detection_train_loader from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, ) from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler from detectron2.solver.build import maybe_add_gradient_clipping from detectron2.utils.logger import setup_logger from mask2former import ( COCOInstanceNewBaselineDatasetMapper, COCOPanopticNewBaselineDatasetMapper, InstanceSegEvaluator, MaskFormerInstanceDatasetMapper, MaskFormerPanopticDatasetMapper, MaskFormerSemanticDatasetMapper, SemanticSegmentorWithTTA, add_maskformer2_config, ) import warnings import copy import itertools import logging import os import torch import detectron2.utils.comm as comm
11,255
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings('ignore', category=ShapelyDeprecationWarning) except: pass os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Cityscapes if evaluator_type == "cityscapes_instance": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesInstanceEvaluator(dataset_name) if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesSemSegEvaluator(dataset_name) if evaluator_type == "cityscapes_panoptic_seg": if cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesSemSegEvaluator(dataset_name)) if cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesInstanceEvaluator(dataset_name)) # ADE20K if evaluator_type == "ade20k_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) # LVIS if evaluator_type == "lvis": return LVISEvaluator(dataset_name, output_dir=output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic": mapper = MaskFormerSemanticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Panoptic segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_panoptic":
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings('ignore', category=ShapelyDeprecationWarning) except: pass os.environ['DETECTRON2_DATASETS'] = 'E:/DGtask/datasets' # MaskFormer class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Cityscapes if evaluator_type == "cityscapes_instance": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesInstanceEvaluator(dataset_name) if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesSemSegEvaluator(dataset_name) if evaluator_type == "cityscapes_panoptic_seg": if cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesSemSegEvaluator(dataset_name)) if cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesInstanceEvaluator(dataset_name)) # ADE20K if evaluator_type == "ade20k_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) # LVIS if evaluator_type == "lvis": return LVISEvaluator(dataset_name, output_dir=output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic": mapper = MaskFormerSemanticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Panoptic segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_panoptic":
mapper = MaskFormerPanopticDatasetMapper(cfg, True)
4
2023-11-29 17:15:46+00:00
16k
opisaac9001/TTS-With-ooba-and-voice
TTS/vocoder/models/wavernn.py
[ { "identifier": "plot_spectrogram", "path": "TTS/tts/utils/visual.py", "snippet": "def plot_spectrogram(spectrogram, ap=None, fig_size=(16, 10), output_fig=False):\n if isinstance(spectrogram, torch.Tensor):\n spectrogram_ = spectrogram.detach().cpu().numpy().squeeze().T\n else:\n sp...
import sys import time import numpy as np import torch import torch.nn.functional as F from dataclasses import dataclass, field from typing import Dict, List, Tuple from coqpit import Coqpit from torch import nn from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler from TTS.tts.utils.visual import plot_spectrogram from TTS.utils.audio import AudioProcessor from TTS.utils.audio.numpy_transforms import mulaw_decode from TTS.utils.io import load_fsspec from TTS.vocoder.datasets.wavernn_dataset import WaveRNNDataset from TTS.vocoder.layers.losses import WaveRNNLoss from TTS.vocoder.models.base_vocoder import BaseVocoder from TTS.vocoder.utils.distribution import sample_from_discretized_mix_logistic, sample_from_gaussian
12,234
self.args.pad, self.args.num_res_blocks, self.args.feat_dims, self.args.compute_dims, self.args.res_out_dims, self.args.use_aux_net, ) if self.args.use_aux_net: self.I = nn.Linear(self.args.feat_dims + self.aux_dims + 1, self.args.rnn_dims) self.rnn1 = nn.GRU(self.args.rnn_dims, self.args.rnn_dims, batch_first=True) self.rnn2 = nn.GRU(self.args.rnn_dims + self.aux_dims, self.args.rnn_dims, batch_first=True) self.fc1 = nn.Linear(self.args.rnn_dims + self.aux_dims, self.args.fc_dims) self.fc2 = nn.Linear(self.args.fc_dims + self.aux_dims, self.args.fc_dims) self.fc3 = nn.Linear(self.args.fc_dims, self.n_classes) else: self.I = nn.Linear(self.args.feat_dims + 1, self.args.rnn_dims) self.rnn1 = nn.GRU(self.args.rnn_dims, self.args.rnn_dims, batch_first=True) self.rnn2 = nn.GRU(self.args.rnn_dims, self.args.rnn_dims, batch_first=True) self.fc1 = nn.Linear(self.args.rnn_dims, self.args.fc_dims) self.fc2 = nn.Linear(self.args.fc_dims, self.args.fc_dims) self.fc3 = nn.Linear(self.args.fc_dims, self.n_classes) def forward(self, x, mels): bsize = x.size(0) h1 = torch.zeros(1, bsize, self.args.rnn_dims).to(x.device) h2 = torch.zeros(1, bsize, self.args.rnn_dims).to(x.device) mels, aux = self.upsample(mels) if self.args.use_aux_net: aux_idx = [self.aux_dims * i for i in range(5)] a1 = aux[:, :, aux_idx[0] : aux_idx[1]] a2 = aux[:, :, aux_idx[1] : aux_idx[2]] a3 = aux[:, :, aux_idx[2] : aux_idx[3]] a4 = aux[:, :, aux_idx[3] : aux_idx[4]] x = ( torch.cat([x.unsqueeze(-1), mels, a1], dim=2) if self.args.use_aux_net else torch.cat([x.unsqueeze(-1), mels], dim=2) ) x = self.I(x) res = x self.rnn1.flatten_parameters() x, _ = self.rnn1(x, h1) x = x + res res = x x = torch.cat([x, a2], dim=2) if self.args.use_aux_net else x self.rnn2.flatten_parameters() x, _ = self.rnn2(x, h2) x = x + res x = torch.cat([x, a3], dim=2) if self.args.use_aux_net else x x = F.relu(self.fc1(x)) x = torch.cat([x, a4], dim=2) if self.args.use_aux_net else x x = F.relu(self.fc2(x)) return self.fc3(x) def inference(self, mels, batched=None, target=None, overlap=None): self.eval() output = [] start = time.time() rnn1 = self.get_gru_cell(self.rnn1) rnn2 = self.get_gru_cell(self.rnn2) with torch.no_grad(): if isinstance(mels, np.ndarray): mels = torch.FloatTensor(mels).to(str(next(self.parameters()).device)) if mels.ndim == 2: mels = mels.unsqueeze(0) wave_len = (mels.size(-1) - 1) * self.config.audio.hop_length mels = self.pad_tensor(mels.transpose(1, 2), pad=self.args.pad, side="both") mels, aux = self.upsample(mels.transpose(1, 2)) if batched: mels = self.fold_with_overlap(mels, target, overlap) if aux is not None: aux = self.fold_with_overlap(aux, target, overlap) b_size, seq_len, _ = mels.size() h1 = torch.zeros(b_size, self.args.rnn_dims).type_as(mels) h2 = torch.zeros(b_size, self.args.rnn_dims).type_as(mels) x = torch.zeros(b_size, 1).type_as(mels) if self.args.use_aux_net: d = self.aux_dims aux_split = [aux[:, :, d * i : d * (i + 1)] for i in range(4)] for i in range(seq_len): m_t = mels[:, i, :] if self.args.use_aux_net: a1_t, a2_t, a3_t, a4_t = (a[:, i, :] for a in aux_split) x = torch.cat([x, m_t, a1_t], dim=1) if self.args.use_aux_net else torch.cat([x, m_t], dim=1) x = self.I(x) h1 = rnn1(x, h1) x = x + h1 inp = torch.cat([x, a2_t], dim=1) if self.args.use_aux_net else x h2 = rnn2(inp, h2) x = x + h2 x = torch.cat([x, a3_t], dim=1) if self.args.use_aux_net else x x = F.relu(self.fc1(x)) x = torch.cat([x, a4_t], dim=1) if self.args.use_aux_net else x x = F.relu(self.fc2(x)) logits = self.fc3(x) if self.args.mode == "mold": sample = sample_from_discretized_mix_logistic(logits.unsqueeze(0).transpose(1, 2)) output.append(sample.view(-1)) x = sample.transpose(0, 1).type_as(mels) elif self.args.mode == "gauss":
def stream(string, variables): sys.stdout.write(f"\r{string}" % variables) # pylint: disable=abstract-method # relates https://github.com/pytorch/pytorch/issues/42305 class ResBlock(nn.Module): def __init__(self, dims): super().__init__() self.conv1 = nn.Conv1d(dims, dims, kernel_size=1, bias=False) self.conv2 = nn.Conv1d(dims, dims, kernel_size=1, bias=False) self.batch_norm1 = nn.BatchNorm1d(dims) self.batch_norm2 = nn.BatchNorm1d(dims) def forward(self, x): residual = x x = self.conv1(x) x = self.batch_norm1(x) x = F.relu(x) x = self.conv2(x) x = self.batch_norm2(x) return x + residual class MelResNet(nn.Module): def __init__(self, num_res_blocks, in_dims, compute_dims, res_out_dims, pad): super().__init__() k_size = pad * 2 + 1 self.conv_in = nn.Conv1d(in_dims, compute_dims, kernel_size=k_size, bias=False) self.batch_norm = nn.BatchNorm1d(compute_dims) self.layers = nn.ModuleList() for _ in range(num_res_blocks): self.layers.append(ResBlock(compute_dims)) self.conv_out = nn.Conv1d(compute_dims, res_out_dims, kernel_size=1) def forward(self, x): x = self.conv_in(x) x = self.batch_norm(x) x = F.relu(x) for f in self.layers: x = f(x) x = self.conv_out(x) return x class Stretch2d(nn.Module): def __init__(self, x_scale, y_scale): super().__init__() self.x_scale = x_scale self.y_scale = y_scale def forward(self, x): b, c, h, w = x.size() x = x.unsqueeze(-1).unsqueeze(3) x = x.repeat(1, 1, 1, self.y_scale, 1, self.x_scale) return x.view(b, c, h * self.y_scale, w * self.x_scale) class UpsampleNetwork(nn.Module): def __init__( self, feat_dims, upsample_scales, compute_dims, num_res_blocks, res_out_dims, pad, use_aux_net, ): super().__init__() self.total_scale = np.cumproduct(upsample_scales)[-1] self.indent = pad * self.total_scale self.use_aux_net = use_aux_net if use_aux_net: self.resnet = MelResNet(num_res_blocks, feat_dims, compute_dims, res_out_dims, pad) self.resnet_stretch = Stretch2d(self.total_scale, 1) self.up_layers = nn.ModuleList() for scale in upsample_scales: k_size = (1, scale * 2 + 1) padding = (0, scale) stretch = Stretch2d(scale, 1) conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=padding, bias=False) conv.weight.data.fill_(1.0 / k_size[1]) self.up_layers.append(stretch) self.up_layers.append(conv) def forward(self, m): if self.use_aux_net: aux = self.resnet(m).unsqueeze(1) aux = self.resnet_stretch(aux) aux = aux.squeeze(1) aux = aux.transpose(1, 2) else: aux = None m = m.unsqueeze(1) for f in self.up_layers: m = f(m) m = m.squeeze(1)[:, :, self.indent : -self.indent] return m.transpose(1, 2), aux class Upsample(nn.Module): def __init__(self, scale, pad, num_res_blocks, feat_dims, compute_dims, res_out_dims, use_aux_net): super().__init__() self.scale = scale self.pad = pad self.indent = pad * scale self.use_aux_net = use_aux_net self.resnet = MelResNet(num_res_blocks, feat_dims, compute_dims, res_out_dims, pad) def forward(self, m): if self.use_aux_net: aux = self.resnet(m) aux = torch.nn.functional.interpolate(aux, scale_factor=self.scale, mode="linear", align_corners=True) aux = aux.transpose(1, 2) else: aux = None m = torch.nn.functional.interpolate(m, scale_factor=self.scale, mode="linear", align_corners=True) m = m[:, :, self.indent : -self.indent] m = m * 0.045 # empirically found return m.transpose(1, 2), aux @dataclass class WavernnArgs(Coqpit): """🐸 WaveRNN model arguments. rnn_dims (int): Number of hidden channels in RNN layers. Defaults to 512. fc_dims (int): Number of hidden channels in fully-conntected layers. Defaults to 512. compute_dims (int): Number of hidden channels in the feature ResNet. Defaults to 128. res_out_dim (int): Number of hidden channels in the feature ResNet output. Defaults to 128. num_res_blocks (int): Number of residual blocks in the ResNet. Defaults to 10. use_aux_net (bool): enable/disable the feature ResNet. Defaults to True. use_upsample_net (bool): enable/ disable the upsampling networl. If False, basic upsampling is used. Defaults to True. upsample_factors (list): Upsampling factors. The multiply of the values must match the `hop_length`. Defaults to ```[4, 8, 8]```. mode (str): Output mode of the WaveRNN vocoder. `mold` for Mixture of Logistic Distribution, `gauss` for a single Gaussian Distribution and `bits` for quantized bits as the model's output. mulaw (bool): enable / disable the use of Mulaw quantization for training. Only applicable if `mode == 'bits'`. Defaults to `True`. pad (int): Padding applied to the input feature frames against the convolution layers of the feature network. Defaults to 2. """ rnn_dims: int = 512 fc_dims: int = 512 compute_dims: int = 128 res_out_dims: int = 128 num_res_blocks: int = 10 use_aux_net: bool = True use_upsample_net: bool = True upsample_factors: List[int] = field(default_factory=lambda: [4, 8, 8]) mode: str = "mold" # mold [string], gauss [string], bits [int] mulaw: bool = True # apply mulaw if mode is bits pad: int = 2 feat_dims: int = 80 class Wavernn(BaseVocoder): def __init__(self, config: Coqpit): """🐸 WaveRNN model. Original paper - https://arxiv.org/abs/1802.08435 Official implementation - https://github.com/fatchord/WaveRNN Args: config (Coqpit): [description] Raises: RuntimeError: [description] Examples: >>> from TTS.vocoder.configs import WavernnConfig >>> config = WavernnConfig() >>> model = Wavernn(config) Paper Abstract: Sequential models achieve state-of-the-art results in audio, visual and textual domains with respect to both estimating the data distribution and generating high-quality samples. Efficient sampling for this class of models has however remained an elusive problem. With a focus on text-to-speech synthesis, we describe a set of general techniques for reducing sampling time while maintaining high output quality. We first describe a single-layer recurrent neural network, the WaveRNN, with a dual softmax layer that matches the quality of the state-of-the-art WaveNet model. The compact form of the network makes it possible to generate 24kHz 16-bit audio 4x faster than real time on a GPU. Second, we apply a weight pruning technique to reduce the number of weights in the WaveRNN. We find that, for a constant number of parameters, large sparse networks perform better than small dense networks and this relationship holds for sparsity levels beyond 96%. The small number of weights in a Sparse WaveRNN makes it possible to sample high-fidelity audio on a mobile CPU in real time. Finally, we propose a new generation scheme based on subscaling that folds a long sequence into a batch of shorter sequences and allows one to generate multiple samples at once. The Subscale WaveRNN produces 16 samples per step without loss of quality and offers an orthogonal method for increasing sampling efficiency. """ super().__init__(config) if isinstance(self.args.mode, int): self.n_classes = 2**self.args.mode elif self.args.mode == "mold": self.n_classes = 3 * 10 elif self.args.mode == "gauss": self.n_classes = 2 else: raise RuntimeError("Unknown model mode value - ", self.args.mode) self.ap = AudioProcessor(**config.audio.to_dict()) self.aux_dims = self.args.res_out_dims // 4 if self.args.use_upsample_net: assert ( np.cumproduct(self.args.upsample_factors)[-1] == config.audio.hop_length ), " [!] upsample scales needs to be equal to hop_length" self.upsample = UpsampleNetwork( self.args.feat_dims, self.args.upsample_factors, self.args.compute_dims, self.args.num_res_blocks, self.args.res_out_dims, self.args.pad, self.args.use_aux_net, ) else: self.upsample = Upsample( config.audio.hop_length, self.args.pad, self.args.num_res_blocks, self.args.feat_dims, self.args.compute_dims, self.args.res_out_dims, self.args.use_aux_net, ) if self.args.use_aux_net: self.I = nn.Linear(self.args.feat_dims + self.aux_dims + 1, self.args.rnn_dims) self.rnn1 = nn.GRU(self.args.rnn_dims, self.args.rnn_dims, batch_first=True) self.rnn2 = nn.GRU(self.args.rnn_dims + self.aux_dims, self.args.rnn_dims, batch_first=True) self.fc1 = nn.Linear(self.args.rnn_dims + self.aux_dims, self.args.fc_dims) self.fc2 = nn.Linear(self.args.fc_dims + self.aux_dims, self.args.fc_dims) self.fc3 = nn.Linear(self.args.fc_dims, self.n_classes) else: self.I = nn.Linear(self.args.feat_dims + 1, self.args.rnn_dims) self.rnn1 = nn.GRU(self.args.rnn_dims, self.args.rnn_dims, batch_first=True) self.rnn2 = nn.GRU(self.args.rnn_dims, self.args.rnn_dims, batch_first=True) self.fc1 = nn.Linear(self.args.rnn_dims, self.args.fc_dims) self.fc2 = nn.Linear(self.args.fc_dims, self.args.fc_dims) self.fc3 = nn.Linear(self.args.fc_dims, self.n_classes) def forward(self, x, mels): bsize = x.size(0) h1 = torch.zeros(1, bsize, self.args.rnn_dims).to(x.device) h2 = torch.zeros(1, bsize, self.args.rnn_dims).to(x.device) mels, aux = self.upsample(mels) if self.args.use_aux_net: aux_idx = [self.aux_dims * i for i in range(5)] a1 = aux[:, :, aux_idx[0] : aux_idx[1]] a2 = aux[:, :, aux_idx[1] : aux_idx[2]] a3 = aux[:, :, aux_idx[2] : aux_idx[3]] a4 = aux[:, :, aux_idx[3] : aux_idx[4]] x = ( torch.cat([x.unsqueeze(-1), mels, a1], dim=2) if self.args.use_aux_net else torch.cat([x.unsqueeze(-1), mels], dim=2) ) x = self.I(x) res = x self.rnn1.flatten_parameters() x, _ = self.rnn1(x, h1) x = x + res res = x x = torch.cat([x, a2], dim=2) if self.args.use_aux_net else x self.rnn2.flatten_parameters() x, _ = self.rnn2(x, h2) x = x + res x = torch.cat([x, a3], dim=2) if self.args.use_aux_net else x x = F.relu(self.fc1(x)) x = torch.cat([x, a4], dim=2) if self.args.use_aux_net else x x = F.relu(self.fc2(x)) return self.fc3(x) def inference(self, mels, batched=None, target=None, overlap=None): self.eval() output = [] start = time.time() rnn1 = self.get_gru_cell(self.rnn1) rnn2 = self.get_gru_cell(self.rnn2) with torch.no_grad(): if isinstance(mels, np.ndarray): mels = torch.FloatTensor(mels).to(str(next(self.parameters()).device)) if mels.ndim == 2: mels = mels.unsqueeze(0) wave_len = (mels.size(-1) - 1) * self.config.audio.hop_length mels = self.pad_tensor(mels.transpose(1, 2), pad=self.args.pad, side="both") mels, aux = self.upsample(mels.transpose(1, 2)) if batched: mels = self.fold_with_overlap(mels, target, overlap) if aux is not None: aux = self.fold_with_overlap(aux, target, overlap) b_size, seq_len, _ = mels.size() h1 = torch.zeros(b_size, self.args.rnn_dims).type_as(mels) h2 = torch.zeros(b_size, self.args.rnn_dims).type_as(mels) x = torch.zeros(b_size, 1).type_as(mels) if self.args.use_aux_net: d = self.aux_dims aux_split = [aux[:, :, d * i : d * (i + 1)] for i in range(4)] for i in range(seq_len): m_t = mels[:, i, :] if self.args.use_aux_net: a1_t, a2_t, a3_t, a4_t = (a[:, i, :] for a in aux_split) x = torch.cat([x, m_t, a1_t], dim=1) if self.args.use_aux_net else torch.cat([x, m_t], dim=1) x = self.I(x) h1 = rnn1(x, h1) x = x + h1 inp = torch.cat([x, a2_t], dim=1) if self.args.use_aux_net else x h2 = rnn2(inp, h2) x = x + h2 x = torch.cat([x, a3_t], dim=1) if self.args.use_aux_net else x x = F.relu(self.fc1(x)) x = torch.cat([x, a4_t], dim=1) if self.args.use_aux_net else x x = F.relu(self.fc2(x)) logits = self.fc3(x) if self.args.mode == "mold": sample = sample_from_discretized_mix_logistic(logits.unsqueeze(0).transpose(1, 2)) output.append(sample.view(-1)) x = sample.transpose(0, 1).type_as(mels) elif self.args.mode == "gauss":
sample = sample_from_gaussian(logits.unsqueeze(0).transpose(1, 2))
8
2023-11-29 08:15:06+00:00
16k
AILab-CVC/UniRepLKNet
Video/dataset/build.py
[ { "identifier": "RawFrameClsDataset", "path": "Video/dataset/datasets.py", "snippet": "class RawFrameClsDataset(Dataset):\n \"\"\"Load your own raw frame classification dataset.\"\"\"\n\n def __init__(self,\n anno_path,\n data_root,\n mode='train',\n...
import os from .datasets import RawFrameClsDataset, VideoClsDataset from .pretrain_datasets import ( # noqa: F401 DataAugmentationForVideoMAEv2, HybridVideoMAE, VideoMAE, )
11,760
num_segments=1, num_crop=1, new_length=args.num_frames, new_step=args.sampling_rate, transform=transform, temporal_jitter=False, lazy_init=False, num_sample=args.num_sample) print("Data Aug = %s" % str(transform)) return dataset def build_dataset(is_train, test_mode, args): if is_train: mode = 'train' anno_path = os.path.join(args.data_path, 'train.csv') elif test_mode: mode = 'test' anno_path = os.path.join(args.data_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.data_path, 'val.csv') if args.data_set == 'Kinetics-400': if not args.sparse_sample: dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, sparse_sample=False, args=args) else: dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=1, frame_sample_rate=1, num_segment=args.num_frames, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, sparse_sample=True, args=args) nb_classes = 400 elif args.data_set == 'Kinetics-600': dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 600 elif args.data_set == 'Kinetics-700': dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 700 elif args.data_set == 'Kinetics-710': dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 710 elif args.data_set == 'SSV2':
# -------------------------------------------------------- # Based on BEiT, timm, DINO and DeiT code bases # https://github.com/microsoft/unilm/tree/master/beit # https://github.com/rwightman/pytorch-image-models/tree/master/timm # https://github.com/facebookresearch/deit # https://github.com/facebookresearch/dino # --------------------------------------------------------' def build_pretraining_dataset(args): transform = DataAugmentationForVideoMAEv2(args) dataset = VideoMAE( root=args.data_root, setting=args.data_path, train=True, test_mode=False, name_pattern=args.fname_tmpl, video_ext='mp4', is_color=True, modality='rgb', num_segments=1, num_crop=1, new_length=args.num_frames, new_step=args.sampling_rate, transform=transform, temporal_jitter=False, lazy_init=False, num_sample=args.num_sample) print("Data Aug = %s" % str(transform)) return dataset def build_dataset(is_train, test_mode, args): if is_train: mode = 'train' anno_path = os.path.join(args.data_path, 'train.csv') elif test_mode: mode = 'test' anno_path = os.path.join(args.data_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.data_path, 'val.csv') if args.data_set == 'Kinetics-400': if not args.sparse_sample: dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, sparse_sample=False, args=args) else: dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=1, frame_sample_rate=1, num_segment=args.num_frames, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, sparse_sample=True, args=args) nb_classes = 400 elif args.data_set == 'Kinetics-600': dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 600 elif args.data_set == 'Kinetics-700': dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 700 elif args.data_set == 'Kinetics-710': dataset = VideoClsDataset( anno_path=anno_path, data_root=args.data_root, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 710 elif args.data_set == 'SSV2':
dataset = RawFrameClsDataset(
0
2023-11-24 07:28:22+00:00
16k
wenquanlu/HandRefiner
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n ...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import itertools from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from omegaconf import ListConfig from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler
12,446
raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, return_x=False): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None and not self.force_null_conditioning: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox', "txt"]: xc = batch[cond_key] elif cond_key in ['class_label', 'cls']: xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_x: out.extend([x]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c) return loss def forward(self, x, c, *args, **kwargs): t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() if self.model.conditioning_key is not None: assert c is not None if self.cond_stage_trainable: c = self.get_learned_conditioning(c) if self.shorten_cond_schedule: # TODO: drop this option tc = self.cond_ids[t].to(self.device) c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) return self.p_losses(x, c, t, *args, **kwargs) def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is expected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, t, **cond) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if reset_ema: assert exists(ckpt_path) if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) if reset_ema: assert self.use_ema print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) else: self.register_buffer('logvar', logvar) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) elif self.parameterization == "v": lvlb_weights = torch.ones_like(self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))) else: raise NotImplementedError("mu not supported") lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") @torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] if self.make_it_fit: n_params = len([name for name, _ in itertools.chain(self.named_parameters(), self.named_buffers())]) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys:\n {missing}") if len(unexpected) > 0: print(f"\nUnexpected Keys:\n {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def predict_start_from_z_and_v(self, x_t, t, v): # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def predict_eps_from_z_and_v(self, x_t, t, v): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_v(self, x, noise, t): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x ) def get_loss(self, pred, target, masks, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') loss = loss * masks[:,None,:,:] else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): for k in self.ucg_training: p = self.ucg_training[k]["p"] val = self.ucg_training[k]["val"] if val is None: val = "" for i in range(len(batch[k])): if self.ucg_prng.choice(2, p=[1 - p, p]): batch[k][i] = val loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, force_null_conditioning=False, *args, **kwargs): self.force_null_conditioning = force_null_conditioning self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning: conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) reset_ema = kwargs.pop("reset_ema", False) reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True if reset_ema: assert self.use_ema print( f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() def make_cond_schedule(self, ): self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx, dataloader_idx): # only for very first batch if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt: assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously' # set rescale weight to 1./std of encodings print("### USING STD-RESCALING ###") x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer('scale_factor', 1. / z.flatten().std()) print(f"setting self.scale_factor to {self.scale_factor}") print("### USING STD-RESCALING ###") def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append(self.decode_first_stage(zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented") return self.scale_factor * z def get_learned_conditioning(self, c): if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip(L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"]) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, return_x=False): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None and not self.force_null_conditioning: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox', "txt"]: xc = batch[cond_key] elif cond_key in ['class_label', 'cls']: xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_x: out.extend([x]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c) return loss def forward(self, x, c, *args, **kwargs): t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() if self.model.conditioning_key is not None: assert c is not None if self.cond_stage_trainable: c = self.get_learned_conditioning(c) if self.shorten_cond_schedule: # TODO: drop this option tc = self.cond_ids[t].to(self.device) c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) return self.p_losses(x, c, t, *args, **kwargs) def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is expected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, t, **cond) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
9
2023-11-24 10:19:23+00:00
16k
eth-sri/language-model-arithmetic
src/model_arithmetic/model_arithmetic.py
[ { "identifier": "load_model", "path": "src/model_arithmetic/basic_model_loader.py", "snippet": "def load_model(dir_or_model, classification=False, token_classification=False, return_tokenizer=False, dtype=torch.bfloat16, load_dtype=True, \n rl=False, peft_config=None):\n \"\"\"\n Th...
from transformers import PreTrainedModel from .basic_model_loader import load_model, load_tokenizer from .utils import get_max_length, ENABLE_LOGGING, log from collections import namedtuple from transformers import top_k_top_p_filtering from loguru import logger from .operators import Operator from .monitor import Monitor from .runnable_operators import RunnableOperator, PromptedLLM from .input import TokenizedInput from .lm_eval_compatibility import Compatibility import json import numpy as np import torch import os import time import random
13,708
do_speculation_sample = False # speculation sampling not needed if all models have not been run yet: this is the first model on this token if all([logprob is None for logprob in self.model_prediction_history[i][n_token].values()]): do_speculation_sample = False # This means that this token was already fully accepted, so we can just continue (can happen if batch_size > 1 or when end is triggered) if self.max_index_prediction_history(i) > n_token: continue # add the new model logprobs self.model_prediction_history[i][n_token][runnable_operator.id()] = new_model_logprobs[i][-n_generated_tokens + n_token + num_new_tokens[i] - 1] group_model_history = self.group_model_history(self.model_prediction_history[i][n_token]) # group_model_history needs to be separately checked, since it could be that the group is not yet fully calculated # also allow no logprobs runnable operators (would lead to errors) if the formula is not finished yet (if it is finished, you need to) if all([logprob is None for logprob in group_model_history.values()]) or (not runnable_operator.outputs_logprobs and not self.formula.is_finished(group_model_history)): continue # process the logprobs new_model_probs = self.process_logprobs(group_model_history) if self.intermediate_argmax and not self.formula.is_finished(group_model_history): argmax_el = torch.argmax(new_model_probs) new_model_probs = torch.zeros_like(new_model_probs) new_model_probs[argmax_el] = 1.0 if do_speculation_sample: if self.calculate_statistics: self.monitor.add_result(self.expected_acceptance_prob(self.create_sample_logprobs(new_model_probs, temperature, top_k, top_p), self.create_sample_logprobs(self.logprobs_history[i].get(n_token), temperature, top_k, top_p)), indicator="expected_acceptance_prob", runnable_operator=runnable_operator) new_token, kept = self.speculation_sample( token = generated_tokens[i][n_token], previous_models_probs=self.create_sample_logprobs(self.logprobs_history[i][n_token], temperature, top_k, top_p), new_models_probs=self.create_sample_logprobs(new_model_probs, temperature, top_k, top_p), ) if n_token in self.model_prediction_history[i]: self.logprobs_history[i][n_token] = new_model_probs if not kept: # if not kept, we change the generated tokens and remove the model prediction history after that token generated_tokens[i][n_token] = new_token generated_tokens[i] = generated_tokens[i][:n_token + 1] self.clear_model_prediction_history(i, generated_tokens[i], from_=n_token) self.trigger_end[i] = False elif n_token in self.model_prediction_history[i]: self.logprobs_history[i][n_token] = new_model_probs if not kept: break all_kept.append(kept) return all_kept def clear_model_prediction_history(self, index, generated_tokens_index, from_=-1): """Clears the model prediction history for a specific sample in the batch. First deletes all history of finished tokens, then deletes history of tokens that were prediction, but then got removed because of speculation Args: index (int): index of the sample in the batch generated_tokens_index (list[int]): Generated tokens at the index from_ (int, optional): From which token to delete all the history. Defaults to -1. """ all_indices = list(self.model_prediction_history[index].keys()) for token in all_indices: all_none = all([logprob is None for logprob in self.model_prediction_history[index][token].values()]) finished = self.formula.is_finished(self.model_prediction_history[index][token]) if all_none or finished or (from_ != -1 and token > from_): if finished and len(generated_tokens_index) > token and self.calculate_statistics: self.add_monitor_token_probs(generated_tokens_index[token], self.model_prediction_history[index][token], self.logprobs_history[index].get(token)) if finished: for model_index in range(len(self.model_last_token_prediction)): self.model_last_token_prediction[model_index][index] = max(token + 1, self.model_last_token_prediction[model_index][index]) del self.model_prediction_history[index][token] if from_ > -1: for model_index in range(len(self.model_last_token_prediction)): self.model_last_token_prediction[model_index][index] = min(from_ + 1, self.model_last_token_prediction[model_index][index]) def max_index_prediction_history(self, index): """Gets the max index of the model prediction history for a specific runnable operator Args: index (int): index of runnable operator in the list of runnable operators Returns: int: max index of its prediction """ keys = list(self.model_prediction_history[index].keys()) if len(keys) == 0: return 0 return max(self.model_prediction_history[index].keys()) def normal_sample(self, probs): """Samples from a probability distribution Args: probs (torch.tensor): Probability distribution Returns: int: Sampled token """ out = torch.multinomial(probs, 1) return out def KL_divergence(self, p, q): """Compuates KL divergence between two probability distributions Args: p (torch.tensor): probability distribution q (torch.tensor): probability distribution Returns: float: KL divergence """
class ModelArithmetic(PreTrainedModel): """ Main class for prompt arithmetic. Handles the generation of text based on the formula. """ SAVE_FILE = "prompt_arithmetic.json" _supports_sdpa = True def __init__(self, formula : Operator, default_model : str = None, dtype=torch.bfloat16, intermediate_argmax : bool = False, epsilon = 1e-12, retroactive_operators = [], calculate_statistics=True, needs_input_tokens_lm_eval=False, lm_eval_task=None, tokenizer=None): """Initializes the prompt arithmetic model. Args: formula (Operator): The formula for which generations need to be made. default_model (str, optional): Default model for RunnableOperators that don't have a model associated with them. Defaults to None. dtype (torch.dtype, optional): Dtype of the models to load by default. Defaults to torch.bfloat16. intermediate_argmax (bool, optional): Something unimportant that was tried out, but now deprecated. Defaults to False. epsilon (float, optional): Just some small value. Defaults to 1e-12. retroactive_operators (list, optional): The retroactive operators that need to be applied. Defaults to []. calculate_statistics (bool, optional): Whether or not to calculate some statistics, can be a tad bit expensive. Defaults to True. needs_input_tokens_lm_eval (bool, optional): Whether or not lm eval is used and whether or not the task needs the input tokens. Defaults to False. Only set to true for an lm eval task. lm_eval_task (str, optional): Name of the lm eval task. Defaults to None. tokenizer (transformers.tokenization_utils_base.PreTrainedTokenizerBase, optional): Tokenizer to use. Defaults to None. """ self.formula = formula.clone() self.default_model = default_model self.loaded_models = dict() self.model_prediction_history = [] # keeps track of the RunnableOperators predictions for each token (that hasn't finished computing) self.logprobs_history = [] # keeps track of the current probability distribution for which each token has been drawn self.model_last_token_prediction = [] # keeps track of the last token that has been predicted for each RunnableOperator self.output_type = namedtuple("ModelArithmeticOutput", ["logits", "logprobs_per_model"]) self.intermediate_argmax = intermediate_argmax self.retroactive_operators = retroactive_operators self.calculate_statistics = calculate_statistics self.runnable_operators = [] for runnable_operator in self.formula.runnable_operators(): if not any([runnable_operator.same_operator(output) for output in self.runnable_operators]): self.runnable_operators.append(runnable_operator) # sort the prompts by speculative factor, putting the one with highest speculative factor first # => run model with highest speculative factor first, since otherwise the computation might be wasted for the first ones # however, we first need to sort by run_priority and then within that by speculative factor self.runnable_operators = sorted(self.runnable_operators, key=lambda runnable_operator: (runnable_operator.run_priority, runnable_operator.speculative_factor), reverse=True) self.load_all_models(dtype=dtype) if self.default_model not in self.loaded_models: for runnable_operator in self.runnable_operators: if isinstance(runnable_operator, PromptedLLM) and runnable_operator.model is not None: self.default_model = runnable_operator.model break if self.default_model is None: raise ValueError("Default model must be specified if not specified in an llm prompt") self.config = self.loaded_models[str(self.default_model)].config if tokenizer is None: self.tokenizer = load_tokenizer(self.default_model) else: self.tokenizer = tokenizer self.init_runnable_operators() self.model_input_tokens = { runnable_operator.id(): TokenizedInput(runnable_operator, runnable_operator.model, self.loaded_models[str(runnable_operator.model)].config, self.tokenizer) for runnable_operator in self.runnable_operators } self.init_monitor() self.epsilon = epsilon self.word_size = len(self.tokenizer) if Compatibility is not None: self.lm_eval_compatibility = Compatibility( task_name=lm_eval_task, needs_input_tokens_lm_eval=needs_input_tokens_lm_eval, tokenizer=self.tokenizer, device=self.device, max_length=get_max_length(self.config), ) else: self.lm_eval_compatibility = None super().__init__(self.config) def init_monitor(self): """ Initializes the monitor for the prompt arithmetic model. """ self.monitor = Monitor(self.runnable_operators) def init_runnable_operators(self): """Initializes the runnable operators. This is done after the models have been loaded, because the models are needed for the runnable operators. """ for runnable_operator in self.runnable_operators: if runnable_operator.model is None: runnable_operator.model = self.default_model runnable_operator.initialize_after_model_set() def load_all_models(self, dtype=torch.bfloat16): """Loads all the models that are needed for the runnable operators. Models are never loaded twice. Args: dtype (torch.dtype, optional): Default Dtype of the models. Defaults to torch.bfloat16. """ if self.default_model is None: for runnable_operator in self.runnable_operators: if isinstance(runnable_operator, PromptedLLM) and runnable_operator.model is not None: self.default_model = str(runnable_operator.model) break for runnable_operator in self.runnable_operators: if runnable_operator.model is None: assert self.default_model is not None, "Default model must be specified if not specified in prompt" runnable_operator.model = self.default_model if runnable_operator.model not in self.loaded_models: model = runnable_operator.load_model(dtype=dtype) model.eval() if model is not None: self.loaded_models[str(runnable_operator.model)] = model if len(self.loaded_models) == 0: assert self.default_model is not None, "Required to at least have one model, for now" self.loaded_models[str(self.default_model)] = load_model(self.default_model, dtype=dtype) @property def device(self): """Device of the default model. Needed for compatibility with lm_eval Returns: torch.device: Device of the default model. """ return self.loaded_models[str(self.default_model)].device def save_pretrained(self, path : str): """Saves the model to the specified path. Args: path (str): Path to which to save the model """ os.makedirs(path, exist_ok=True) all_settings = { "formula": self.formula.generate_settings(), "default_model": self.default_model, } with open(os.path.join(path, self.SAVE_FILE), "w") as f: json.dump(all_settings, f, indent=4, sort_keys=True) @classmethod def from_pretrained(cls, path : str, dtype=torch.bfloat16): """Loads the model from the specified path. Args: path (str): Path from which to load the model dtype (torch.dtype, optional): Default dtype for the models. Defaults to torch.bfloat16. Returns: ModelArithmetic: model arithmetic model """ with open(os.path.join(path, cls.SAVE_FILE), "r") as f: all_settings = json.load(f) all_settings["formula"] = Operator.load_from_settings(all_settings["formula"]) return cls(**all_settings, dtype=dtype) def forward_model(self, runnable_operator, continuation_tokens, model_new_tokens=None, use_cache=False, do_speculation=False): """Runs a specifc runnable operator on the continuation tokens. Args: runnable_operator (RunnableOperator): The runnable operator to run. continuation_tokens (list[list[int]]): List of tokens that need to be continued. The prompt is not included in these tokens model_new_tokens (list[int], optional): New tokens for the model. Defaults to None. use_cache (bool, optional): Whether or not to allow the model to use cache (eg key-value storage for an LLM). Defaults to False. do_speculation (bool, optional): Whether or not to do speculation sampling. Defaults to False. Returns: torch.tensor: logprobs of the model, one logprob distribution for each new token in each sample """ start_time = time.time() tokenized_input_creator = self.model_input_tokens[runnable_operator.id()] tokenized_inputs = tokenized_input_creator.add_continuation_tokens(continuation_tokens) tokenized_only_input = tokenized_input_creator.get_only_input_tokens() was_none = model_new_tokens is None if was_none: model_new_tokens = torch.tensor([len(continuation_tokens[i]) + 1 for i in range(len(continuation_tokens))]) if len(self.model_prediction_history) < len(continuation_tokens): new_prediction_history = [dict() for _ in range(len(continuation_tokens))] else: new_prediction_history = [self.model_prediction_history[i].get(self.max_index_prediction_history(i), dict()) for i in range(len(continuation_tokens))] logprobs = runnable_operator.run( loaded_models=self.loaded_models, tokenized_inputs=tokenized_inputs, model_new_tokens=model_new_tokens, new_prediction_history=new_prediction_history, other_tokenizer=self.tokenizer, tokenized_only_input=tokenized_only_input, use_cache=use_cache, do_speculation=do_speculation ) logprobs = [logprob.to(self.device) for logprob in logprobs] if was_none: logprobs = torch.stack(logprobs, dim=0) self.monitor.add_result(element=time.time() - start_time, runnable_operator=runnable_operator) return logprobs def group_complete(self, model_history): """Checks which groups of runnable operators have been completely calculated and which haven't. Args: model_history (dict): Dict mapping the runnable operator id to the logprobs of the model Returns: dict[bool]: Dict mapping the group to whether it has been completely calculated or not """ # everything that is a group needs to be either all calculated or all not calculated group_calculated = dict() groups = set([runnable_operator.group for runnable_operator in self.runnable_operators if runnable_operator.group is not None]) completed_groups = {group: True for group in groups} for runnable_operator in self.runnable_operators: if runnable_operator.group is not None: is_calculated = model_history.get(runnable_operator.id()) is not None if runnable_operator.group not in group_calculated: group_calculated[runnable_operator.group] = is_calculated elif group_calculated[runnable_operator.group] != is_calculated: completed_groups[runnable_operator.group] = False return completed_groups def group_model_history(self, model_history): """Sets the model history on which to evaluate the formula based on the groups. Removes predictions if the group hasn't been completely calculated yet. Args: model_history (dict): Dict mapping the runnable operator id to the logprobs of the model Returns: dict: Adjusted dict mapping """ completed_groups = self.group_complete(model_history) grouped_model_history = dict() for runnable_operator in self.runnable_operators: if runnable_operator.group is None or completed_groups[runnable_operator.group]: grouped_model_history[runnable_operator.id()] = model_history[runnable_operator.id()] else: grouped_model_history[runnable_operator.id()] = None return grouped_model_history def create_sample_logprobs(self, logprobs, temperature, top_k, top_p): """Creates the logprobs for each token in each sample. Args: logprobs (torch.tensor): Logprobs of the model temperature (float): temperature to use top_k (int): top_k to use top_p (float): top_p to use Returns: torch.tensor: Logprobs for each token in each sample """ if temperature == 0: logprobs_argmax = torch.argmax(logprobs, dim=-1) logprobs = torch.nn.functional.one_hot(logprobs_argmax, num_classes=logprobs.shape[-1]).float() return logprobs logprobs = logprobs / temperature logprobs = top_k_top_p_filtering(logprobs.unsqueeze(0), top_k=top_k, top_p=top_p) return torch.softmax(logprobs, dim=-1).squeeze() def process_logprobs(self, model_history): """Processes model history to get the probability distribution for the token. Args: model_history (dict): Dict mapping the runnable operator id to the logprobs of the model Returns: _type_: _description_ """ init_time = time.time() logprobs_normalized = self.formula.evaluate(model_history) self.monitor.add_result(element=time.time() - init_time, indicator="formula_evaluation") if not torch.is_tensor(logprobs_normalized): return None # logprobs_normalized = logprobs_normalized / temperature # logprobs_normalized = top_k_top_p_filtering(logprobs_normalized.unsqueeze(0), top_k=top_k, top_p=top_p) return logprobs_normalized def run_retroactive_operators(self, index, tokenized_sentence, temperature, top_k, top_p): """Runs the retroactive operators on the tokenized sentence. Args: index (int): Index of the sentence in the current batch tokenized_sentence (list[int]): Tokenized sentence temperature (float): temperature to use top_k (int): top_k to use top_p (float): top_p to use Returns: list[int]: Adjusted tokenized sentence based on the retroactive operators and whether they accepted it. """ for operator in self.retroactive_operators: accepted = operator.accept(tokenized_sentence, self.tokenizer) if accepted < 0: not_accepted_token = tokenized_sentence[accepted] self.clear_model_prediction_history(index, tokenized_sentence, from_=len(tokenized_sentence) + accepted) tokenized_sentence = tokenized_sentence[:len(tokenized_sentence) + accepted] self.logprobs_history[index][len(tokenized_sentence)][not_accepted_token] = -torch.inf if torch.all(self.logprobs_history[index][len(tokenized_sentence)] == -torch.inf): self.logprobs_history[index][len(tokenized_sentence)] = torch.zeros_like(self.logprobs_history[index][len(tokenized_sentence)]) probs_to_sample = self.create_sample_logprobs( self.logprobs_history[index][len(tokenized_sentence)], temperature=temperature, top_k=top_k, top_p=top_p ) new_token = torch.multinomial(probs_to_sample, 1).item() tokenized_sentence.append(new_token) return self.run_retroactive_operators(index, tokenized_sentence, temperature, top_k, top_p) return tokenized_sentence def speculation_sample(self, token, previous_models_probs, new_models_probs): """Sample a token based on the previous and new model probabilities in the speculative sampling way. Also returns whether the token was accepted or not. Args: token (int): Token that is currently selected previous_models_probs (torch.tensor): Model probabilities of the previous models new_models_probs (torch.tensor): Model probabilities of the new models Returns: (int, bool): New token and whether or not the input token was accepted """ acceptance_prob = torch.minimum(torch.tensor(1.0), new_models_probs[token] / (previous_models_probs[token] + torch.tensor(self.epsilon))) # TODO: the next line is taking an enormous amount of time because of asynchronous computing on gpu's and requiring it to be returned immediately # Therefore do batch processing acceptance_prob = float(acceptance_prob) self.monitor.add_result(element=float(acceptance_prob), indicator="acceptance_prob") # self.monitor.add_result(element=self.entropy(previous_models_probs).item(), indicator="entropy_previous") # self.monitor.add_result(element=previous_models_probs[token].item(), indicator="probability_previous") if torch.rand(1) < acceptance_prob: return token, True else: new_proba_distrib = torch.relu(new_models_probs - previous_models_probs) new_proba_distrib /= torch.sum(new_proba_distrib) new_token = torch.multinomial(new_proba_distrib, 1).item() return new_token, False def add_new_result(self, generated_tokens, num_new_tokens, runnable_operator, new_model_logprobs, top_p, top_k, temperature): """Adds a new run of a runnable operator to the model prediction history. Also does speculation sampling if needed. Args: generated_tokens (list[list[int]]): Currently generated tokens by the model num_new_tokens (list[int]): Number of new tokens for each sample in the batch runnable_operator (RunnableOperator): Runnable operator that was run new_model_logprobs (List[torch.tensor]): Output of the run function of the runnable operator top_p (flaot): top_p to use top_k (int): top_k to use temperature (float): temperature to use Returns: list[bool]: For each sample in the batch, whether all tokens in that sample were kept or not """ all_kept = [] for i in range(len(generated_tokens)): n_generated_tokens = len(generated_tokens[i]) kept = True for n_token in range(n_generated_tokens - num_new_tokens[i] + 1, n_generated_tokens + 1): # initialize the model prediction history self.model_prediction_history[i][n_token] = self.model_prediction_history[i].get(n_token, {runnable_operator.id(): None for runnable_operator in self.runnable_operators}) # check if we need to do speculation sampling, only needed when a previous token was sampled do_speculation_sample = n_token < n_generated_tokens # speculation sampling not needed if the model was run before if self.model_prediction_history[i][n_token][runnable_operator.id()] is not None: do_speculation_sample = False # speculation sampling not needed if all models have not been run yet: this is the first model on this token if all([logprob is None for logprob in self.model_prediction_history[i][n_token].values()]): do_speculation_sample = False # This means that this token was already fully accepted, so we can just continue (can happen if batch_size > 1 or when end is triggered) if self.max_index_prediction_history(i) > n_token: continue # add the new model logprobs self.model_prediction_history[i][n_token][runnable_operator.id()] = new_model_logprobs[i][-n_generated_tokens + n_token + num_new_tokens[i] - 1] group_model_history = self.group_model_history(self.model_prediction_history[i][n_token]) # group_model_history needs to be separately checked, since it could be that the group is not yet fully calculated # also allow no logprobs runnable operators (would lead to errors) if the formula is not finished yet (if it is finished, you need to) if all([logprob is None for logprob in group_model_history.values()]) or (not runnable_operator.outputs_logprobs and not self.formula.is_finished(group_model_history)): continue # process the logprobs new_model_probs = self.process_logprobs(group_model_history) if self.intermediate_argmax and not self.formula.is_finished(group_model_history): argmax_el = torch.argmax(new_model_probs) new_model_probs = torch.zeros_like(new_model_probs) new_model_probs[argmax_el] = 1.0 if do_speculation_sample: if self.calculate_statistics: self.monitor.add_result(self.expected_acceptance_prob(self.create_sample_logprobs(new_model_probs, temperature, top_k, top_p), self.create_sample_logprobs(self.logprobs_history[i].get(n_token), temperature, top_k, top_p)), indicator="expected_acceptance_prob", runnable_operator=runnable_operator) new_token, kept = self.speculation_sample( token = generated_tokens[i][n_token], previous_models_probs=self.create_sample_logprobs(self.logprobs_history[i][n_token], temperature, top_k, top_p), new_models_probs=self.create_sample_logprobs(new_model_probs, temperature, top_k, top_p), ) if n_token in self.model_prediction_history[i]: self.logprobs_history[i][n_token] = new_model_probs if not kept: # if not kept, we change the generated tokens and remove the model prediction history after that token generated_tokens[i][n_token] = new_token generated_tokens[i] = generated_tokens[i][:n_token + 1] self.clear_model_prediction_history(i, generated_tokens[i], from_=n_token) self.trigger_end[i] = False elif n_token in self.model_prediction_history[i]: self.logprobs_history[i][n_token] = new_model_probs if not kept: break all_kept.append(kept) return all_kept def clear_model_prediction_history(self, index, generated_tokens_index, from_=-1): """Clears the model prediction history for a specific sample in the batch. First deletes all history of finished tokens, then deletes history of tokens that were prediction, but then got removed because of speculation Args: index (int): index of the sample in the batch generated_tokens_index (list[int]): Generated tokens at the index from_ (int, optional): From which token to delete all the history. Defaults to -1. """ all_indices = list(self.model_prediction_history[index].keys()) for token in all_indices: all_none = all([logprob is None for logprob in self.model_prediction_history[index][token].values()]) finished = self.formula.is_finished(self.model_prediction_history[index][token]) if all_none or finished or (from_ != -1 and token > from_): if finished and len(generated_tokens_index) > token and self.calculate_statistics: self.add_monitor_token_probs(generated_tokens_index[token], self.model_prediction_history[index][token], self.logprobs_history[index].get(token)) if finished: for model_index in range(len(self.model_last_token_prediction)): self.model_last_token_prediction[model_index][index] = max(token + 1, self.model_last_token_prediction[model_index][index]) del self.model_prediction_history[index][token] if from_ > -1: for model_index in range(len(self.model_last_token_prediction)): self.model_last_token_prediction[model_index][index] = min(from_ + 1, self.model_last_token_prediction[model_index][index]) def max_index_prediction_history(self, index): """Gets the max index of the model prediction history for a specific runnable operator Args: index (int): index of runnable operator in the list of runnable operators Returns: int: max index of its prediction """ keys = list(self.model_prediction_history[index].keys()) if len(keys) == 0: return 0 return max(self.model_prediction_history[index].keys()) def normal_sample(self, probs): """Samples from a probability distribution Args: probs (torch.tensor): Probability distribution Returns: int: Sampled token """ out = torch.multinomial(probs, 1) return out def KL_divergence(self, p, q): """Compuates KL divergence between two probability distributions Args: p (torch.tensor): probability distribution q (torch.tensor): probability distribution Returns: float: KL divergence """
return torch.sum(p * torch.log((p + self.epsilon) / (q + self.epsilon)))
4
2023-11-21 20:01:08+00:00
16k
huang-yh/SelfOcc
model/encoder/tpvformer/tpvformer_encoder.py
[ { "identifier": "BaseEncoder", "path": "model/encoder/base_encoder.py", "snippet": "class BaseEncoder(BaseModule):\n \"\"\"Further encode 3D representations.\n image backbone -> neck -> lifter -> encoder -> segmentor\n \"\"\"\n\n def __init__(self, init_cfg=None, **kwargs):\n super()....
from mmseg.registry import MODELS from mmcv.cnn.bricks.transformer import build_positional_encoding, build_transformer_layer from mmcv.ops.multi_scale_deform_attn import MultiScaleDeformableAttention from mmengine.model import ModuleList from torch.nn.init import normal_ from mmengine.logging import MMLogger from ..base_encoder import BaseEncoder from ..bevformer.utils import point_sampling from .utils import get_cross_view_ref_points from ..bevformer.mappings import GridMeterMapping from ..bevformer.attention import BEVCrossAttention, BEVDeformableAttention from .attention import TPVCrossAttention, CrossViewHybridAttention from .modules import CameraAwareSE import torch.nn as nn, torch, copy
12,100
torch.zeros(size_h, size_w)], dim=-1) hw_meter = self.mapping.grid2meter(hw_grid)[..., [0, 1]] zh_grid = torch.stack( [torch.arange(size_h, dtype=torch.float).unsqueeze(0).expand(size_d, -1), torch.zeros(size_d, size_h), torch.arange(size_d, dtype=torch.float).unsqueeze(-1).expand(-1, size_h)], dim=-1) zh_meter = self.mapping.grid2meter(zh_grid)[..., [1, 2]] wz_grid = torch.stack( [torch.zeros(size_w, size_d), torch.arange(size_w, dtype=torch.float).unsqueeze(-1).expand(-1, size_d), torch.arange(size_d, dtype=torch.float).unsqueeze(0).expand(size_w, -1)], dim=-1) wz_meter = self.mapping.grid2meter(wz_grid)[..., [0, 2]] positional_encoding.update({'tpv_meters': [hw_meter, zh_meter, wz_meter]}) self.positional_encoding = build_positional_encoding(positional_encoding) self.tpv_size = [size_h, size_w, size_d] # transformer layers if isinstance(transformerlayers, dict): transformerlayers = [ copy.deepcopy(transformerlayers) for _ in range(num_layers)] else: assert isinstance(transformerlayers, list) and \ len(transformerlayers) == num_layers self.num_layers = num_layers self.layers = ModuleList() for i in range(num_layers): self.layers.append(build_transformer_layer(transformerlayers[i])) self.pre_norm = self.layers[0].pre_norm logger.info('use pre_norm: ' + str(self.pre_norm)) # other learnable embeddings self.level_embeds = nn.Parameter( torch.randn(self.num_feature_levels, self.embed_dims)) self.cams_embeds = nn.Parameter( torch.randn(self.num_cams, self.embed_dims)) # prepare reference points used in image cross-attention and cross-view hybrid-attention self.num_points_cross = num_points_cross self.num_points_self = num_points_self uniform_d = torch.linspace(0, size_d - 1, num_points_cross[2]) hw_3d_grid = torch.cat([ hw_grid[..., [0, 1]].unsqueeze(2).expand(-1, -1, num_points_cross[2], -1), uniform_d.reshape(1, 1, -1, 1).expand(size_h, size_w, -1, -1)], dim=-1) ref_3d_hw = self.mapping.grid2meter(hw_3d_grid) # H, W, P0, 3 uniform_w = torch.linspace(0, size_w - 1, num_points_cross[1]) zh_3d_grid = torch.cat([ zh_grid[..., :1].unsqueeze(2).expand(-1, -1, num_points_cross[1], -1), uniform_w.reshape(1, 1, -1, 1).expand(size_d, size_h, -1, -1), zh_grid[..., 2:].unsqueeze(2).expand(-1, -1, num_points_cross[1], -1) ], dim=-1) ref_3d_zh = self.mapping.grid2meter(zh_3d_grid) # Z, H, P1, 3 uniform_h = torch.linspace(0, size_h - 1, num_points_cross[0]) wz_3d_grid = torch.cat([ uniform_h.reshape(1, 1, -1, 1).expand(size_w, size_d, -1, -1), wz_grid[..., [1, 2]].unsqueeze(2).expand(-1, -1, num_points_cross[0], -1) ], dim=-1) ref_3d_wz = self.mapping.grid2meter(wz_3d_grid) # W, Z, P2, 3 self.register_buffer('ref_3d_hw', ref_3d_hw.flatten(0, 1).transpose(0, 1), False) self.register_buffer('ref_3d_zh', ref_3d_zh.flatten(0, 1).transpose(0, 1), False) self.register_buffer('ref_3d_wz', ref_3d_wz.flatten(0, 1).transpose(0, 1), False) cross_view_ref_points = get_cross_view_ref_points(size_h, size_w, size_d, num_points_self) self.register_buffer('cross_view_ref_points', cross_view_ref_points, False) # hw_grid_normed = hw_grid[..., [0, 1]].clone() # hw_grid_normed[..., 0] = hw_grid_normed[..., 0] / (size_h - 1) # hw_grid_normed[..., 1] = hw_grid_normed[..., 1] / (size_w - 1) # zh_grid_normed = zh_grid[..., [2, 0]].clone() # zh_grid_normed[..., 0] = zh_grid_normed[..., 0] / (size_d - 1) # zh_grid_normed[..., 1] = zh_grid_normed[..., 1] / (size_h - 1) # wz_grid_normed = wz_grid[..., [1, 2]].clone() # wz_grid_normed[..., 0] = wz_grid_normed[..., 0] / (size_w - 1) # wz_grid_normed[..., 1] = wz_grid_normed[..., 1] / (size_d - 1) # self.register_buffer('ref_2d_hw', hw_grid_normed, False) # H, W, 2 # self.register_buffer('ref_2d_zh', zh_grid_normed, False) # H, W, 2 # self.register_buffer('ref_2d_wz', wz_grid_normed, False) # H, W, 2 def init_weights(self): """Initialize the transformer weights.""" for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules(): if isinstance(m, BEVCrossAttention) or \ isinstance(m, MultiScaleDeformableAttention) or \ isinstance(m, BEVDeformableAttention) or \ isinstance(m, TPVCrossAttention) or \ isinstance(m, CrossViewHybridAttention): try: m.init_weight() except AttributeError: m.init_weights() normal_(self.level_embeds) normal_(self.cams_embeds) def forward_layers( self, tpv_query, # b, c, h, w key, value, tpv_pos=None, # b, h, w, c spatial_shapes=None, level_start_index=None, img_metas=None, **kwargs ): bs = tpv_query[0].shape[0] reference_points_cams, tpv_masks = [], [] for ref_3d in [self.ref_3d_hw, self.ref_3d_zh, self.ref_3d_wz]:
logger = MMLogger.get_instance('selfocc') @MODELS.register_module() class TPVFormerEncoder(BaseEncoder): def __init__( self, mapping_args: dict, # bev_inner=128, # bev_outer=32, # range_inner=51.2, # range_outer=51.2, # nonlinear_mode='linear_upscale', # z_inner=20, # z_outer=10, # z_ranges=[-5.0, 3.0, 11.0], embed_dims=128, num_cams=6, num_feature_levels=4, positional_encoding=None, num_points_cross=[64, 64, 8], num_points_self=[16, 16, 16], transformerlayers=None, num_layers=None, camera_aware=False, camera_aware_mid_channels=None, init_cfg=None): super().__init__(init_cfg) # self.bev_inner = bev_inner # self.bev_outer = bev_outer # self.range_inner = range_inner # self.range_outer = range_outer # assert nonlinear_mode == 'linear_upscale' # TODO # self.nonlinear_mode = nonlinear_mode # self.z_inner = z_inner # self.z_outer = z_outer # self.z_ranges = z_ranges self.embed_dims = embed_dims self.num_feature_levels = num_feature_levels self.num_cams = num_cams self.camera_aware = camera_aware if camera_aware: if camera_aware_mid_channels is None: camera_aware_mid_channels = embed_dims self.camera_se_net = CameraAwareSE( embed_dims, camera_aware_mid_channels, embed_dims) self.mapping = GridMeterMapping( # bev_inner, # bev_outer, # range_inner, # range_outer, # nonlinear_mode, # z_inner, # z_outer, # z_ranges **mapping_args) size_h = self.mapping.size_h size_w = self.mapping.size_w size_d = self.mapping.size_d hw_grid = torch.stack( [torch.arange(size_h, dtype=torch.float).unsqueeze(-1).expand(-1, size_w), torch.arange(size_w, dtype=torch.float).unsqueeze(0).expand(size_h, -1), torch.zeros(size_h, size_w)], dim=-1) hw_meter = self.mapping.grid2meter(hw_grid)[..., [0, 1]] zh_grid = torch.stack( [torch.arange(size_h, dtype=torch.float).unsqueeze(0).expand(size_d, -1), torch.zeros(size_d, size_h), torch.arange(size_d, dtype=torch.float).unsqueeze(-1).expand(-1, size_h)], dim=-1) zh_meter = self.mapping.grid2meter(zh_grid)[..., [1, 2]] wz_grid = torch.stack( [torch.zeros(size_w, size_d), torch.arange(size_w, dtype=torch.float).unsqueeze(-1).expand(-1, size_d), torch.arange(size_d, dtype=torch.float).unsqueeze(0).expand(size_w, -1)], dim=-1) wz_meter = self.mapping.grid2meter(wz_grid)[..., [0, 2]] positional_encoding.update({'tpv_meters': [hw_meter, zh_meter, wz_meter]}) self.positional_encoding = build_positional_encoding(positional_encoding) self.tpv_size = [size_h, size_w, size_d] # transformer layers if isinstance(transformerlayers, dict): transformerlayers = [ copy.deepcopy(transformerlayers) for _ in range(num_layers)] else: assert isinstance(transformerlayers, list) and \ len(transformerlayers) == num_layers self.num_layers = num_layers self.layers = ModuleList() for i in range(num_layers): self.layers.append(build_transformer_layer(transformerlayers[i])) self.pre_norm = self.layers[0].pre_norm logger.info('use pre_norm: ' + str(self.pre_norm)) # other learnable embeddings self.level_embeds = nn.Parameter( torch.randn(self.num_feature_levels, self.embed_dims)) self.cams_embeds = nn.Parameter( torch.randn(self.num_cams, self.embed_dims)) # prepare reference points used in image cross-attention and cross-view hybrid-attention self.num_points_cross = num_points_cross self.num_points_self = num_points_self uniform_d = torch.linspace(0, size_d - 1, num_points_cross[2]) hw_3d_grid = torch.cat([ hw_grid[..., [0, 1]].unsqueeze(2).expand(-1, -1, num_points_cross[2], -1), uniform_d.reshape(1, 1, -1, 1).expand(size_h, size_w, -1, -1)], dim=-1) ref_3d_hw = self.mapping.grid2meter(hw_3d_grid) # H, W, P0, 3 uniform_w = torch.linspace(0, size_w - 1, num_points_cross[1]) zh_3d_grid = torch.cat([ zh_grid[..., :1].unsqueeze(2).expand(-1, -1, num_points_cross[1], -1), uniform_w.reshape(1, 1, -1, 1).expand(size_d, size_h, -1, -1), zh_grid[..., 2:].unsqueeze(2).expand(-1, -1, num_points_cross[1], -1) ], dim=-1) ref_3d_zh = self.mapping.grid2meter(zh_3d_grid) # Z, H, P1, 3 uniform_h = torch.linspace(0, size_h - 1, num_points_cross[0]) wz_3d_grid = torch.cat([ uniform_h.reshape(1, 1, -1, 1).expand(size_w, size_d, -1, -1), wz_grid[..., [1, 2]].unsqueeze(2).expand(-1, -1, num_points_cross[0], -1) ], dim=-1) ref_3d_wz = self.mapping.grid2meter(wz_3d_grid) # W, Z, P2, 3 self.register_buffer('ref_3d_hw', ref_3d_hw.flatten(0, 1).transpose(0, 1), False) self.register_buffer('ref_3d_zh', ref_3d_zh.flatten(0, 1).transpose(0, 1), False) self.register_buffer('ref_3d_wz', ref_3d_wz.flatten(0, 1).transpose(0, 1), False) cross_view_ref_points = get_cross_view_ref_points(size_h, size_w, size_d, num_points_self) self.register_buffer('cross_view_ref_points', cross_view_ref_points, False) # hw_grid_normed = hw_grid[..., [0, 1]].clone() # hw_grid_normed[..., 0] = hw_grid_normed[..., 0] / (size_h - 1) # hw_grid_normed[..., 1] = hw_grid_normed[..., 1] / (size_w - 1) # zh_grid_normed = zh_grid[..., [2, 0]].clone() # zh_grid_normed[..., 0] = zh_grid_normed[..., 0] / (size_d - 1) # zh_grid_normed[..., 1] = zh_grid_normed[..., 1] / (size_h - 1) # wz_grid_normed = wz_grid[..., [1, 2]].clone() # wz_grid_normed[..., 0] = wz_grid_normed[..., 0] / (size_w - 1) # wz_grid_normed[..., 1] = wz_grid_normed[..., 1] / (size_d - 1) # self.register_buffer('ref_2d_hw', hw_grid_normed, False) # H, W, 2 # self.register_buffer('ref_2d_zh', zh_grid_normed, False) # H, W, 2 # self.register_buffer('ref_2d_wz', wz_grid_normed, False) # H, W, 2 def init_weights(self): """Initialize the transformer weights.""" for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules(): if isinstance(m, BEVCrossAttention) or \ isinstance(m, MultiScaleDeformableAttention) or \ isinstance(m, BEVDeformableAttention) or \ isinstance(m, TPVCrossAttention) or \ isinstance(m, CrossViewHybridAttention): try: m.init_weight() except AttributeError: m.init_weights() normal_(self.level_embeds) normal_(self.cams_embeds) def forward_layers( self, tpv_query, # b, c, h, w key, value, tpv_pos=None, # b, h, w, c spatial_shapes=None, level_start_index=None, img_metas=None, **kwargs ): bs = tpv_query[0].shape[0] reference_points_cams, tpv_masks = [], [] for ref_3d in [self.ref_3d_hw, self.ref_3d_zh, self.ref_3d_wz]:
reference_points_cam, tpv_mask = point_sampling(
1
2023-11-20 12:49:14+00:00
16k
MobileTeleSystems/CoolGraph
cool_graph/runners.py
[ { "identifier": "RawDataProcessor", "path": "cool_graph/data/data_processor.py", "snippet": "class RawDataProcessor:\n \"\"\"\n Preprocessing datasets.\n\n Args:\n groups_names (Dict[int, str]): Name of groups in nodes.\n group_names_node_features (Dict[str, List[str]]): Name of f...
import os import pathlib import hydra import numpy as np import optuna import pandas as pd import torch from datetime import datetime from itertools import product from pathlib import Path from typing import Dict, List, Literal, Optional from hydra import ( compose, core, initialize, initialize_config_dir, initialize_config_module, ) from omegaconf import DictConfig, OmegaConf from optuna.trial import TrialState from sklearn.model_selection import train_test_split from torch_geometric.data import Data from torch_geometric.loader import NeighborLoader, NeighborSampler from tqdm import tqdm from cool_graph.data import RawDataProcessor from cool_graph.data.batch import get_auto_batch_size from cool_graph.data.loaders import create_loaders from cool_graph.logging import setup_mlflow_from_config from cool_graph.parameter_search import ( model_params_to_trial_params, sample_model_params, ) from cool_graph.train import Trainer
12,112
print(" Params: ") for i in trial_dataset["number"].tolist(): if trial_dataset["value"][i] == trial_dataset["value"].max(): print(dict_with_params[i]) return trial_dataset class MultiRunner: """ Runner for heterogeneous graph Args: data (Data): A data object describing a homogeneous graph. The data object can hold node-level, link-level and graph-level attributes. In general, Data tries to mimic the behavior of a regular Python dictionary. In addition, it provides useful functionality for analyzing graph structures, and provides basic PyTorch tensor functionalities. https://pytorch-geometric.readthedocs.io/en/latest/get_started/introduction.html#data-handling-of-graphs config (DictConfig): Config. Defaults to None. config_path (str): Path to config. Defaults to None. overrides (list): Own params. Can ba params from configs and overrides. Defaults to None. train_size (int): Size for train data. Defaults to None. test_size (int): Size for test data. Defaults to None. seed (int): Seed param for training. Defaults to None. train_idx (list): Indices for train data. Defaults to None. test_idx (list): Indices for test data. Defaults to None. """ def __init__( self, data: Data, config: Optional[DictConfig] = None, config_path: Optional[str] = None, overrides: Optional[List] = None, train_size: Optional[int] = None, test_size: Optional[int] = None, seed: Optional[int] = None, train_idx: Optional[List[int]] = None, test_idx: Optional[List[int]] = None, **kwargs, ) -> None: if config is None: if config_path is None: config_path = os.path.join( os.path.dirname(__file__), "./config/full.yaml" ) config = create_cfg( config=config_path, overrides=overrides, path_base="cfg" ) cfg = OmegaConf.to_container(config, resolve=True) self.cfg = cfg self.data = data self.test_size = test_size self.train_size = train_size self.seed = seed self.train_idx = train_idx self.test_idx = test_idx self.node_feature_indices = cfg["data"]["node_feature_indices"] self.target_names = cfg["training"]["targets"] self.groups_names = cfg["data"]["groups_names"] self.target_weights = cfg["training"]["loss"]["target_weights"] self.read_edge_attr = cfg["data"].get("read_edge_attr", True) self.batch_size = cfg["training"]["batch_size"] self.group_mask_col = cfg["data"]["group_mask_col"] self.label_mask_col = cfg["data"]["label_mask_col"] self.label_cols = cfg["data"]["label_cols"] self.label_index_col = cfg["data"]["label_index_col"] self.edge_index_cols = cfg["data"]["edge_index_cols"] self.num_neighbors = cfg["training"]["num_neighbors"] self.features_edges_names = cfg["data"].get("features_edges") self.group_names_node_features = cfg["data"]["features"] self.metrics = cfg["metrics"] self.chkpt_dir = ( pathlib.Path(cfg["logging"]["checkpoint_dir"]) / str(datetime.now())[:19] ) os.makedirs(self.chkpt_dir, exist_ok=True) for k, v in kwargs.items(): setattr(self, k, v) if self.cfg["logging"].get("use_mlflow", False): setup_mlflow_from_config(cfg["logging"]["mlflow"]) def init_loaders(self) -> None: if self.batch_size == "auto": self._batch_size = get_auto_batch_size( [len(v) for _, v in self.group_names_node_features.items()], conv_type=self.cfg["model_params"]["conv_type"], conv1_aggrs=self.cfg["model_params"]["conv1_aggrs"], conv2_aggrs=self.cfg["model_params"].get("conv2_aggrs"), conv3_aggrs=self.cfg["model_params"].get("conv3_aggrs"), n_hops=self.cfg["model_params"]["n_hops"], lin_prep_size_common=self.cfg["model_params"]["lin_prep_size_common"], lin_prep_sizes=self.cfg["model_params"]["lin_prep_sizes"], edge_attr_repr_sizes=self.cfg["model_params"].get( "edge_attr_repr_sizes" ), num_edge_features=len(self.cfg["data"].get("features_edges", [])), device=self.cfg["training"]["device"], num_neighbors=self.cfg["training"]["num_neighbors"], ) else: self._batch_size = self.batch_size if (self.train_idx is None) or (self.test_idx is None): train_idx, test_idx = train_test_split( torch.nonzero(self.data.label_mask)[:, 0], train_size=self.train_size, test_size=self.test_size, random_state=self.seed, shuffle=True, ) self.train_idx = train_idx self.test_idx = test_idx unique_groups = np.unique(self.data.group_mask)
def create_cfg(config: str, overrides: List[str], path_base: str = "cfg") -> Dict: assert path_base in ("cfg", "cwd") core.global_hydra.GlobalHydra.instance().clear() if os.path.isabs(config): config_path = pathlib.Path(config).parent else: config_path = pathlib.Path(os.getcwd()) / pathlib.Path(config).parent config_name = pathlib.Path(config).name.replace(".yaml", "") initialize_config_dir(str(config_path), version_base=None) cfg = compose(config_name=config_name, overrides=overrides) return cfg class ConfigRunner: r"""Runner for cli mode. Using only in cli. This class allows to load data + split data per batchs + split data per train/val + training. See the config full.yaml in ./config for knowing what excactly using as data/logging/model_params/training/metrics. You can use default params, but also you can change it. Steps for changing confis: - make get_config --configs path_where_you_need_configs (default: new path ./configs by itself) """ def __init__(self, config: Optional[DictConfig]) -> None: cfg = OmegaConf.to_container(config, resolve=True) self.cfg = cfg self.target_names = cfg["training"]["targets"] self.groups_names = cfg["data"]["groups_names"] self.target_weights = cfg["training"]["loss"]["target_weights"] self.read_edge_attr = cfg["data"].get("read_edge_attr", True) self.batch_size = cfg["training"]["batch_size"] self.group_mask_col = cfg["data"]["group_mask_col"] self.label_mask_col = cfg["data"]["label_mask_col"] self.label_cols = cfg["data"]["label_cols"] self.label_index_col = cfg["data"]["label_index_col"] self.edge_index_cols = cfg["data"]["edge_index_cols"] self.num_neighbors = cfg["training"]["num_neighbors"] self.features_edges_names = cfg["data"].get("features_edges") self.group_names_node_features = cfg["data"]["features"] self.train_paths = cfg["data"]["train"] self.val_paths = cfg["data"]["validation"] self.metrics = cfg["metrics"] self.chkpt_dir = ( pathlib.Path(cfg["logging"]["checkpoint_dir"]) / str(datetime.now())[:19] ) os.makedirs(self.chkpt_dir, exist_ok=True) if self.cfg["logging"].get("use_mlflow", False): setup_mlflow_from_config(cfg["logging"]["mlflow"]) def init_loaders(self) -> None: """ Using RawDataProcessor from cool_graph.data for preprocessing data from disk. """ self.train_sampler = RawDataProcessor( self.groups_names, self.group_names_node_features, mon_nodes_path=self.train_paths["nodes_path"], mon_edges_path=self.train_paths["edges_path"], mon_labels_path=self.train_paths["labels_path"], edge_index_cols=self.edge_index_cols, label_index_col=self.label_index_col, label_mask_col=self.label_mask_col, read_edge_attr=self.read_edge_attr, group_mask_col=self.group_mask_col, features_edges_names=self.features_edges_names, label_cols=self.label_cols, target_names=self.target_names, ) self.val_sampler = RawDataProcessor( self.groups_names, self.group_names_node_features, mon_nodes_path=self.val_paths["nodes_path"], mon_edges_path=self.val_paths["edges_path"], mon_labels_path=self.val_paths["labels_path"], edge_index_cols=self.edge_index_cols, label_index_col=self.label_index_col, label_mask_col=self.label_mask_col, read_edge_attr=self.read_edge_attr, group_mask_col=self.group_mask_col, features_edges_names=self.features_edges_names, label_cols=self.label_cols, target_names=self.target_names, ) def sample_data( self, seed=0 ) -> Dict[Literal["train", "validation"], List[torch.utils.data.DataLoader]]: """ Sampling data in batches. """ if self.batch_size == "auto": self._batch_size = get_auto_batch_size( [len(v) for _, v in self.group_names_node_features.items()], conv_type=self.cfg["model_params"]["conv_type"], conv1_aggrs=self.cfg["model_params"]["conv1_aggrs"], conv2_aggrs=self.cfg["model_params"].get("conv2_aggrs"), conv3_aggrs=self.cfg["model_params"].get("conv3_aggrs"), n_hops=self.cfg["model_params"]["n_hops"], lin_prep_size_common=self.cfg["model_params"]["lin_prep_size_common"], lin_prep_sizes=self.cfg["model_params"]["lin_prep_sizes"], edge_attr_repr_sizes=self.cfg["model_params"].get( "edge_attr_repr_sizes" ), num_edge_features=len(self.cfg["data"].get("features_edges", [])), device=self.cfg["training"]["device"], num_neighbors=self.cfg["training"]["num_neighbors"], ) else: self._batch_size = self.batch_size train_loaders = self.train_sampler.sample_data( self.num_neighbors, self._batch_size, seed=seed ) val_loaders = self.val_sampler.sample_data( self.num_neighbors, self._batch_size, seed=seed ) return {"train": train_loaders, "validation": val_loaders} def run(self, seed: int = 0) -> Dict[str, float]: """ Train model for train_samples and val_sampler. Args: seed (int): seed for training. Default to 0. Returns: result (dict): Result of training for each 5 epochs with metrics from config. """ if not (hasattr(self, "train_sampler") and hasattr(self, "val_sampler")): self.init_loaders() sampled = self.sample_data(seed=seed) train_loaders = sampled["train"] val_loaders = sampled["validation"] self.trainer = Trainer( train_loaders, val_loaders, self.chkpt_dir, device=self.cfg["training"]["device"], eval_freq=self.cfg["training"]["eval_freq"], fill_value=self.cfg["training"]["loss"].get("fill_value"), initial_lr=self.cfg["training"].get("initial_lr", 0.01), weight_decay=self.cfg["training"].get("weight_decay", 0.0), loss_name=self.cfg["training"]["loss"]["name"], loss_label_smoothing=self.cfg["training"]["loss"].get( "label_smoothing", False ), loss_target_weights=self.cfg["training"]["loss"].get("target_weights"), loss_group_weights=self.cfg["training"]["loss"].get("group_weights"), groups_names=self.cfg["data"]["groups_names"], mlflow_experiment_name=self.cfg["logging"].get("mlflow_experiment_name"), n_epochs=self.cfg["training"].get("n_epochs"), scheduler_params=self.cfg["training"].get("scheduler_params", {}), scheduler_type=self.cfg["training"].get("scheduler_type"), target_names=self.cfg["training"]["targets"], use_mlflow=self.cfg["logging"].get("use_mlflow", False), tqdm_disable=False, **self.cfg["model_params"], groups_names_num_features={ k: len(v) for k, v in self.group_names_node_features.items() }, num_edge_features=len(self.cfg["data"].get("features_edges", [])), metrics=self.metrics, ) result = self.trainer.train() return result class BaseRunner: def __init__( self, data: Data, config: Optional[DictConfig] = None, config_path: Optional[str] = None, overrides: Optional[List] = None, train_size: Optional[int] = None, test_size: Optional[int] = None, seed: Optional[int] = None, train_idx: Optional[List[int]] = None, test_idx: Optional[List[int]] = None, use_edge_attr: bool = False, **kwargs, ) -> None: """ Main class for Basic runner and Runner with Optuna. Args: data (Data): A data object describing a homogeneous graph. The data object can hold node-level, link-level and graph-level attributes. In general, Data tries to mimic the behavior of a regular Python dictionary. In addition, it provides useful functionality for analyzing graph structures, and provides basic PyTorch tensor functionalities. https://pytorch-geometric.readthedocs.io/en/latest/get_started/introduction.html#data-handling-of-graphs config (DictConfig): Config. Defaults to None. config_path (str): Path to config. Defaults to None. overrides (list): Own params. Can ba params from configs and overrides. Defaults to None. train_size (int): Size for train data. Defaults to None. test_size (int): Size for test data. Defaults to None. seed (int): Seed param for training. Defaults to None. train_idx (list): Indices for train data. Defaults to None. test_idx (list): Indices for test data. Defaults to None. use_edge_attr (bool): If attributes exist on edges, it can be used in training. Defaults to False. """ if config is None: if config_path is None: if use_edge_attr: config_path = "./config/in_memory_data2.yaml" else: config_path = "./config/in_memory_data.yaml" config_path = os.path.join(os.path.dirname(__file__), config_path) config = create_cfg( config=config_path, overrides=overrides, path_base="cfg" ) cfg = OmegaConf.to_container(config, resolve=True) self.data = data self.cfg = cfg self.test_size = test_size self.train_size = train_size self.seed = seed self.train_idx = train_idx self.test_idx = test_idx self.use_edge_attr = use_edge_attr if use_edge_attr and data.edge_attr is None: raise BaseException( "data does not contain edge_attr, please set use_edge_attr=False" ) self.target_names = cfg["training"]["targets"] self.target_weights = cfg["training"]["loss"]["target_weights"] self.batch_size = cfg["training"]["batch_size"] self.num_neighbors = cfg["training"]["num_neighbors"] self.metrics = cfg["metrics"] self.data.group_mask = torch.zeros(len(data.x), dtype=torch.int8) self.data.label_mask = torch.ones(len(data.x), dtype=torch.bool) self.groups_names = {0: "x"} self.groups_names_num_features = {"x": data.x.shape[1]} if len(data.y.shape) == 2: self.target_sizes = [] self.target_names = [] self.target_weights = {} for i in range(data.y.shape[1]): y_sub = data.y[:, i] setattr(data, f"y{i}", y_sub) self.target_sizes.append(len(y_sub.unique())) self.target_names.append(f"y{i}") self.target_weights[f"y{i}"] = 1 else: self.target_names = ["y"] self.target_sizes = [len(data.y.unique())] self.target_weights = {"y": 1} if use_edge_attr: self.num_edge_features = data.edge_attr.shape[1] else: self.num_edge_features = 0 self.chkpt_dir = ( pathlib.Path(cfg["logging"]["checkpoint_dir"]) / str(datetime.now())[:19] ) for k, v in kwargs.items(): setattr(self, k, v) if self.cfg["logging"].get("use_mlflow", False): setup_mlflow_from_config(cfg["logging"]["mlflow"]) def init_loaders(self) -> None: """ Sampling data into batches and sampling data with NeighborLoader into list loaders. """ if self.batch_size == "auto": self._batch_size = get_auto_batch_size( [ self.groups_names_num_features[self.groups_names[i]] for i in range(len(self.groups_names)) ], conv_type=self.cfg["model_params"]["conv_type"], conv1_aggrs=self.cfg["model_params"]["conv1_aggrs"], conv2_aggrs=self.cfg["model_params"].get("conv2_aggrs"), conv3_aggrs=self.cfg["model_params"].get("conv3_aggrs"), n_hops=self.cfg["model_params"]["n_hops"], lin_prep_size_common=self.cfg["model_params"]["lin_prep_size_common"], lin_prep_sizes=self.cfg["model_params"]["lin_prep_sizes"], edge_attr_repr_sizes=self.cfg["model_params"].get( "edge_attr_repr_sizes" ), num_edge_features=self.num_edge_features, device=self.cfg["training"]["device"], num_neighbors=self.num_neighbors, ) else: self._batch_size = self.batch_size if (self.train_idx is None) or (self.test_idx is None): train_idx, test_idx = train_test_split( torch.nonzero(self.data.label_mask)[:, 0], train_size=self.train_size, test_size=self.test_size, random_state=self.seed, shuffle=True, ) self.train_idx = train_idx self.test_idx = test_idx def sample_date_prerpoc(sampled_data: Data) -> Data: sampled_data.label_mask[sampled_data.batch_size :] = False for group, name in self.groups_names.items(): x = getattr(sampled_data, name)[sampled_data.group_mask == group] setattr(sampled_data, name, x) return sampled_data loader_train = NeighborLoader( self.data, num_neighbors=self.num_neighbors, batch_size=self._batch_size, shuffle=True, input_nodes=self.train_idx, ) list_loader_train = [] for sampled_data in tqdm(loader_train, desc="Sample data"): list_loader_train.append(sample_date_prerpoc(sampled_data)) self.train_loader = list_loader_train loader_test = NeighborLoader( self.data, num_neighbors=self.num_neighbors, batch_size=self._batch_size, shuffle=True, input_nodes=self.test_idx, ) list_loader_test = [] for sampled_data in tqdm(loader_test, desc="Sample data"): list_loader_test.append(sample_date_prerpoc(sampled_data)) self.test_loader = list_loader_test class Runner(BaseRunner): """ Runner for notebook launch. Args: data (Data): A data object describing a homogeneous graph. The data object can hold node-level, link-level and graph-level attributes. In general, Data tries to mimic the behavior of a regular Python dictionary. In addition, it provides useful functionality for analyzing graph structures, and provides basic PyTorch tensor functionalities. https://pytorch-geometric.readthedocs.io/en/latest/get_started/introduction.html#data-handling-of-graphs config (DictConfig): Config. Defaults to None. config_path (str): Path to config. Defaults to None. overrides (list): Own params. Can ba params from configs and overrides. Defaults to None. train_size (int): Size for train data. Defaults to None. test_size (int): Size for test data. Defaults to None. seed (int): Seed param for training. Defaults to None. train_idx (int): Indices for train data. Defaults to None. test_idx (int): Indices for test data. Defaults to None. use_edge_attr (bool): If attributes exist on edges, it can be used in training. Defaults to False. Examples -------- >>> from cool_graph.runners import Runner >>> from torch_geometric import datasets >>> # loading amazon dataset >>> data = datasets.Amazon(root="./data/Amazon", name="Computers").data >>> runner = Runner(data) >>> result = runner.run() >>> result["best_loss"] {'accuracy': 0.916, 'cross_entropy': 0.286, 'f1_micro': 0.916, 'calc_time': 0.004, 'main_metric': 0.916, 'epoch': 10} Also you can override params in Runner: runner = Runner(data, metrics=['accuracy'], batch_size='auto', train_size=0.7, test_size=0.3, overrides=['training.n_epochs=1'], config_path=path/to/config) result = runner.run() """ def __init__( self, data: Data, config: Optional[DictConfig] = None, config_path: Optional[str] = None, overrides: Optional[List] = None, train_size: Optional[int] = None, test_size: Optional[int] = None, seed: Optional[int] = None, train_idx: Optional[List[int]] = None, test_idx: Optional[List[int]] = None, use_edge_attr: bool = False, **kwargs, ): super().__init__( data, config, config_path, overrides, train_size, test_size, seed, train_idx, test_idx, use_edge_attr, **kwargs, ) def run(self) -> Dict[str, float]: """ Training model with params in_memory_data/in_memory_data2 config. See the configs in ./config for knowing what excactly using as logging/model_params/training/metrics. You can use default params, but also you can change it. Steps for changing confis: - make get_config --configs path_where_you_need_configs (default: new path ./configs by itself) """ if not (hasattr(self, "train_loader") and hasattr(self, "test_loader")): self.init_loaders() self.trainer = Trainer( self.train_loader, self.test_loader, self.chkpt_dir, device=self.cfg["training"]["device"], eval_freq=self.cfg["training"]["eval_freq"], fill_value=self.cfg["training"]["loss"].get("fill_value"), initial_lr=self.cfg["training"].get("initial_lr", 0.01), weight_decay=self.cfg["training"].get("weight_decay", 0.0), loss_name=self.cfg["training"]["loss"]["name"], loss_label_smoothing=self.cfg["training"]["loss"].get( "label_smoothing", False ), loss_target_weights=self.target_weights, loss_group_weights=self.cfg["training"]["loss"].get("group_weights"), groups_names=self.groups_names, mlflow_experiment_name=self.cfg["logging"].get("mlflow_experiment_name"), n_epochs=self.cfg["training"].get("n_epochs"), scheduler_params=self.cfg["training"].get("scheduler_params", {}), scheduler_type=self.cfg["training"].get("scheduler_type"), target_names=self.target_names, use_mlflow=self.cfg["logging"].get("use_mlflow", False), tqdm_disable=False, target_sizes=self.target_sizes, **self.cfg["model_params"], groups_names_num_features=self.groups_names_num_features, num_edge_features=self.num_edge_features, metrics=self.metrics, log_all_metrics=False, ) result = self.trainer.train() return result class HypeRunner(BaseRunner): """ Runner for optimization model with Optuna. https://optuna.readthedocs.io/en/stable/reference/index.html 1st trial - with default config params (hyper_params). Also, 2nd trial - you can add own trial as argument enqueue_trial in optimazire_run method, and next trial optuna optimize model params randomly, if set None randomly optimization after 1st default trial. Args: data (Data): Loaded dataset. config (DictConfig): Confif with patams (model_params, logging, training, metrics). Default to None. config_path (str): Path with config structure (can be loaded with cli get_config). Default to None. overrides (list): Own params in list. Default to None. train_size (int): Own train size. Default to None. test (int): Own test size. Default to None. seed (int): The desired seed. Default to None. train_idx (list): List of train indices. test_idx (list): List of test indices. Examples -------- >>> from cool_graph.runners import HypeRunner >>> from torch_geometric import datasets >>> # loading amazon dataset >>> data = datasets.Amazon(root="./data/Amazon", name="Computers").data >>> runner = HypeRunner(data) >>> result = runner.run(optimize_run) Study statistics: Number of finished trials: 5 Number of complete trials: 5 Best trial: Value: 0.922 Params: {'conv_type': 'GraphConv', 'activation': 'leakyrelu', 'lin_prep_len': 1, 'lin_prep_dropout_rate': 0.4, 'lin_prep_weight_norm_flag': True, 'lin_prep_size_common': 512, 'lin_prep_sizes': [256], 'n_hops': 2, 'conv1_aggrs': {'mean': 128, 'max': 64, 'add': 32}, 'conv1_dropout_rate': 0.2, 'conv2_aggrs': {'mean': 64, 'max': 32, 'add': 16}, 'conv2_dropout_rate': 0.2, 'graph_conv_weight_norm_flag': True} """ def __init__( self, data: Data, config: Optional[DictConfig] = None, config_path: Optional[str] = None, overrides: Optional[List] = None, train_size: Optional[int] = None, test_size: Optional[int] = None, seed: Optional[int] = None, train_idx: Optional[List[int]] = None, test_idx: Optional[List[int]] = None, ): super().__init__( data, config, config_path, overrides, train_size, test_size, seed, train_idx, test_idx, ) if config is None: if config_path is None: config_path = os.path.join( os.path.dirname(__file__), "./config/in_memory_data.yaml" ) config = create_cfg( config=config_path, overrides=overrides, path_base="cfg" ) self.study = optuna.study def optimize_run( self, n_trials: int = 100, storage: Optional[str] = None, study_name: Optional[str] = None, enqueue_trial: Optional[List[Dict]] = None, ) -> pd.DataFrame: if not (hasattr(self, "train_loader") and hasattr(self, "test_loader")): self.init_loaders() """ Method for running objective function in Optuna. Args: n_trials (int, optional): The number of trials for each process. None represents no limit in terms of the number of trials. Defaults to 100. storage (Optional[str], optional): Database URL. If this argument is set to None, in-memory storage is used, and the Study will not be persistent. Defaults to None. study_name (Optional[str], optional): Study name. If this argument is set to None, a unique name is generated automatically. Defaults to None. enqueue_trial (Optional[List[Dict]], optional): Enqueue a trial with given parameter values. Defaults to None. Returns: trials_dataset (pd.DataFrame): Result dataframe with trial params. """ list_with_params = [] def objective(trial) -> float: self.cfg["model_params"] = sample_model_params( trial, conv_type=self.cfg["model_params"]["conv_type"] ) list_with_params.append(self.cfg["model_params"]) self.trainer = Trainer( self.train_loader, self.test_loader, self.chkpt_dir, device=self.cfg["training"]["device"], eval_freq=self.cfg["training"]["eval_freq"], fill_value=self.cfg["training"]["loss"].get("fill_value"), initial_lr=self.cfg["training"].get("initial_lr", 0.01), weight_decay=self.cfg["training"].get("weight_decay", 0.0), loss_name=self.cfg["training"]["loss"]["name"], loss_label_smoothing=self.cfg["training"]["loss"].get( "label_smoothing", False ), loss_target_weights=self.target_weights, loss_group_weights=self.cfg["training"]["loss"].get("group_weights"), groups_names=self.groups_names, mlflow_experiment_name=self.cfg["logging"].get( "mlflow_experiment_name" ), n_epochs=self.cfg["training"].get("n_epochs"), scheduler_params=self.cfg["training"].get("scheduler_params", {}), scheduler_type=self.cfg["training"].get("scheduler_type"), target_names=self.target_names, use_mlflow=self.cfg["logging"].get("use_mlflow", False), tqdm_disable=False, target_sizes=self.target_sizes, **self.cfg["model_params"], groups_names_num_features=self.groups_names_num_features, num_edge_features=self.num_edge_features, metrics=self.metrics, log_all_metrics=False, ) result = self.trainer.train() output = result["best_loss"]["main_metric"] output = round(output, 3) return output # default params for the 1st trial in Optuna optimization trial_params = model_params_to_trial_params(**self.cfg["model_params"]) trial_params["weight_decay"] = self.cfg["training"].get("weight_decay", 0.0) self.study = optuna.create_study( storage=storage, study_name=study_name, direction="maximize", load_if_exists=True, sampler=optuna.samplers.RandomSampler(seed=120), ) # adding a trial_params as a default one to optuna optimization self.study.enqueue_trial(trial_params) # users params for the 2nd trial, # if None use optuna random params to trial if enqueue_trial: for param in enqueue_trial: user_params = model_params_to_trial_params(**param) self.study.enqueue_trial(user_params) self.study.optimize( objective, n_trials=n_trials, n_jobs=1, show_progress_bar=False ) complete_trials = self.study.get_trials( deepcopy=False, states=[TrialState.COMPLETE] ) print("Study statistics: ") print(" Number of finished trials: ", len(self.study.trials)) print(" Number of complete trials: ", len(complete_trials)) trial = self.study.best_trial dict_with_params = dict(enumerate(list_with_params)) print("Best trial:") print(" Value: ", trial.value) trials_dataset = self.study.trials_dataframe() trials_dataset = trials_dataset[ [ "number", "value", "datetime_start", "datetime_complete", "duration", "system_attrs_fixed_params", "state", ] ] trial_dataset = pd.concat( [trials_dataset, pd.DataFrame(dict_with_params).T], axis=1 ) print(" Params: ") for i in trial_dataset["number"].tolist(): if trial_dataset["value"][i] == trial_dataset["value"].max(): print(dict_with_params[i]) return trial_dataset class MultiRunner: """ Runner for heterogeneous graph Args: data (Data): A data object describing a homogeneous graph. The data object can hold node-level, link-level and graph-level attributes. In general, Data tries to mimic the behavior of a regular Python dictionary. In addition, it provides useful functionality for analyzing graph structures, and provides basic PyTorch tensor functionalities. https://pytorch-geometric.readthedocs.io/en/latest/get_started/introduction.html#data-handling-of-graphs config (DictConfig): Config. Defaults to None. config_path (str): Path to config. Defaults to None. overrides (list): Own params. Can ba params from configs and overrides. Defaults to None. train_size (int): Size for train data. Defaults to None. test_size (int): Size for test data. Defaults to None. seed (int): Seed param for training. Defaults to None. train_idx (list): Indices for train data. Defaults to None. test_idx (list): Indices for test data. Defaults to None. """ def __init__( self, data: Data, config: Optional[DictConfig] = None, config_path: Optional[str] = None, overrides: Optional[List] = None, train_size: Optional[int] = None, test_size: Optional[int] = None, seed: Optional[int] = None, train_idx: Optional[List[int]] = None, test_idx: Optional[List[int]] = None, **kwargs, ) -> None: if config is None: if config_path is None: config_path = os.path.join( os.path.dirname(__file__), "./config/full.yaml" ) config = create_cfg( config=config_path, overrides=overrides, path_base="cfg" ) cfg = OmegaConf.to_container(config, resolve=True) self.cfg = cfg self.data = data self.test_size = test_size self.train_size = train_size self.seed = seed self.train_idx = train_idx self.test_idx = test_idx self.node_feature_indices = cfg["data"]["node_feature_indices"] self.target_names = cfg["training"]["targets"] self.groups_names = cfg["data"]["groups_names"] self.target_weights = cfg["training"]["loss"]["target_weights"] self.read_edge_attr = cfg["data"].get("read_edge_attr", True) self.batch_size = cfg["training"]["batch_size"] self.group_mask_col = cfg["data"]["group_mask_col"] self.label_mask_col = cfg["data"]["label_mask_col"] self.label_cols = cfg["data"]["label_cols"] self.label_index_col = cfg["data"]["label_index_col"] self.edge_index_cols = cfg["data"]["edge_index_cols"] self.num_neighbors = cfg["training"]["num_neighbors"] self.features_edges_names = cfg["data"].get("features_edges") self.group_names_node_features = cfg["data"]["features"] self.metrics = cfg["metrics"] self.chkpt_dir = ( pathlib.Path(cfg["logging"]["checkpoint_dir"]) / str(datetime.now())[:19] ) os.makedirs(self.chkpt_dir, exist_ok=True) for k, v in kwargs.items(): setattr(self, k, v) if self.cfg["logging"].get("use_mlflow", False): setup_mlflow_from_config(cfg["logging"]["mlflow"]) def init_loaders(self) -> None: if self.batch_size == "auto": self._batch_size = get_auto_batch_size( [len(v) for _, v in self.group_names_node_features.items()], conv_type=self.cfg["model_params"]["conv_type"], conv1_aggrs=self.cfg["model_params"]["conv1_aggrs"], conv2_aggrs=self.cfg["model_params"].get("conv2_aggrs"), conv3_aggrs=self.cfg["model_params"].get("conv3_aggrs"), n_hops=self.cfg["model_params"]["n_hops"], lin_prep_size_common=self.cfg["model_params"]["lin_prep_size_common"], lin_prep_sizes=self.cfg["model_params"]["lin_prep_sizes"], edge_attr_repr_sizes=self.cfg["model_params"].get( "edge_attr_repr_sizes" ), num_edge_features=len(self.cfg["data"].get("features_edges", [])), device=self.cfg["training"]["device"], num_neighbors=self.cfg["training"]["num_neighbors"], ) else: self._batch_size = self.batch_size if (self.train_idx is None) or (self.test_idx is None): train_idx, test_idx = train_test_split( torch.nonzero(self.data.label_mask)[:, 0], train_size=self.train_size, test_size=self.test_size, random_state=self.seed, shuffle=True, ) self.train_idx = train_idx self.test_idx = test_idx unique_groups = np.unique(self.data.group_mask)
self.train_loader = create_loaders(
2
2023-11-22 09:44:16+00:00
16k
HeliosZhao/Animate124
guidance/cn_utils.py
[ { "identifier": "save_videos_grid", "path": "nerf/utils.py", "snippet": "def save_videos_grid(videos: torch.Tensor, path: str, n_rows=8, fps=8, **kwargs):\n ## videos b f c h w\n videos = rearrange(videos, \"b t c h w -> t b c h w\")\n outputs = []\n for x in videos:\n # x: b,c,h,w\n ...
from typing import List, Optional, Sequence, Tuple, Union, Mapping from dataclasses import dataclass from torch.cuda.amp import custom_bwd, custom_fwd from torch import Tensor from diffusers import AutoencoderKL, UNet2DConditionModel, PNDMScheduler, DDIMScheduler, StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, DiffusionPipeline, ControlNetModel from diffusers.utils.import_utils import is_xformers_available, is_torch_version from os.path import isfile from pathlib import Path from PIL import Image from torchvision.io import read_image from torchvision import transforms from torchvision.transforms import functional as TVF from torchvision.utils import make_grid, save_image from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTokenizer, CLIPProcessor from einops import rearrange from nerf.utils import save_videos_grid, save_tensor2image from controlnet.stable_diffusion_controlnet_img2img import StableDiffusionControlNetImg2ImgPipeline from easydict import EasyDict as edict import os import torch import torch.nn.functional as F import torch.nn as nn import torch.nn.functional as F import numpy as np import logging import torch import argparse import matplotlib.pyplot as plt import glob
13,515
# add noise noise = torch.randn_like(latents) latents_noisy = self.scheduler.add_noise(latents, noise, t) # pred noise latent_model_input = torch.cat([latents_noisy] * 2) down_block_res_samples, mid_block_res_sample = self.controlnet( latent_model_input, t, encoder_hidden_states=cn_text_embeddings, controlnet_cond=controlnet_conditioning_image, conditioning_scale=self.cn_scale, return_dict=False, ) noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, down_block_additional_residuals=down_block_res_samples, mid_block_additional_residual=mid_block_res_sample, ).sample # perform guidance (high scale from paper!) noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_text + guidance_scale * \ (noise_pred_text - noise_pred_uncond) grad_clipd = 0 # ipdb.set_trace() w = (1 - self.alphas[t])[:, None, None, None] # 1,1,1,1 # w = self.alphas[t] ** 0.5 * (1 - self.alphas[t]) # grad_sds = w * (noise_pred - noise) grad_sds = grad_scale * w * (noise_pred - noise) loss_sds = grad_sds.abs().mean().detach() grad_clipd = 0. loss_clipd = 0. grad = grad_clipd + grad_sds if grad_clip is not None: grad = grad.clamp(-grad_clip, grad_clip) grad = torch.nan_to_num(grad) if self.new_sds: targets = (latents - grad).detach() # if self.opt.grad_dyn: targets = ( (latents_noisy - (1 - self.alphas[t]) ** (0.5) * noise_pred) / self.alphas[t] ** (0.5) ).detach() if self.opt.get('mean_sds', False): loss = 0.5 * F.mse_loss(latents.float(), targets, reduction='mean') # * grad_scale else: loss = 0.5 * F.mse_loss(latents.float(), targets, reduction='sum') / latents.shape[0] # * grad_scale # B,4,H,W -> sum over 4,H,W else: # grad = grad * grad_scale # grad = torch.nan_to_num(grad) latents.backward(gradient=grad, retain_graph=True) loss = grad.abs().mean().detach() # B,4,H,W all mean if not enable_clip: loss_sds = loss if save_guidance_path: with torch.no_grad(): # save original input images = [] os.makedirs(os.path.dirname(save_guidance_path), exist_ok=True) timesteps = torch.arange(50, 1000, 300, dtype=torch.long, device=self.device) for t in timesteps: # ipdb.set_trace() if as_latent: pred_rgb_512 = self.decode_latents(latents, video_generation) latents_noisy = self.scheduler.add_noise(latents, noise, t) # pred noise latent_model_input = torch.cat([latents_noisy] * 2) down_block_res_samples, mid_block_res_sample = self.controlnet( latent_model_input, t, encoder_hidden_states=cn_text_embeddings, controlnet_cond=controlnet_conditioning_image, conditioning_scale=self.cn_scale, return_dict=False, ) noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, down_block_additional_residuals=down_block_res_samples, mid_block_additional_residual=mid_block_res_sample ).sample # noise_pred = self.unet(latent_model_input, t, # encoder_hidden_states=text_embeddings).sample # perform guidance (high scale from paper!) noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_text + guidance_scale * \ (noise_pred_text - noise_pred_uncond) pred_original_sample = self.decode_latents((latents_noisy - (1 - self.alphas[t]) ** (0.5) * noise_pred) / self.alphas[t] ** (0.5)) # visualize predicted denoised image # claforte: discuss this with Vikram!! result_hopefully_less_noisy_image = self.decode_latents(latents - w*grad_scale*(noise_pred - noise)) # visualize noisier image result_noisier_image = self.decode_latents(latents_noisy) viz_image_list = [pred_rgb_512, controlnet_conditioning_image.chunk(2,dim=0)[0], pred_original_sample, result_hopefully_less_noisy_image] viz_image_list = [rearrange(_img, "(b f) c h w -> b c f h w", f=num_frame) for _img in viz_image_list] image = torch.cat(viz_image_list, dim=0) images.append(image) n_rows = images[0].size(0) if video_generation: viz_images = torch.cat(images, dim=0).detach().mul(255).to(torch.uint8) # b,c,f,h,w
logger = logging.getLogger(__name__) def spherical_dist_loss(x, y): x = F.normalize(x, dim=-1) y = F.normalize(y, dim=-1) return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) def to_pil(x: torch.Tensor, **kwargs) -> Image.Image: return TVF.to_pil_image(make_grid(x, value_range=(0, 1), **kwargs)) def to_np_img(x: torch.Tensor) -> np.ndarray: return (x.detach().permute(0, 2, 3, 1).cpu().numpy() * 255).round().astype(np.uint8) class SpecifyGradient(torch.autograd.Function): @staticmethod @custom_fwd def forward(ctx, input_tensor, gt_grad): ctx.save_for_backward(gt_grad) # we return a dummy value 1, which will be scaled by amp's scaler so we get the scale in backward. return torch.ones([1], device=input_tensor.device, dtype=input_tensor.dtype) @staticmethod @custom_bwd def backward(ctx, grad_scale): gt_grad, = ctx.saved_tensors gt_grad = gt_grad * grad_scale return gt_grad, None def token_replace(prompt, negative, learned_embeds_path): # Set up automatic token replacement for prompt if '<token>' in prompt or '<token>' in negative: if learned_embeds_path is None: raise ValueError( '--learned_embeds_path must be specified when using <token>') tmp = list(torch.load(learned_embeds_path, map_location='cpu').keys()) if len(tmp) != 1: raise ValueError( 'Something is wrong with the dict passed in for --learned_embeds_path') token = tmp[0] prompt = prompt.replace('<token>', token) negative = negative.replace('<token>', token) logger.info(f'Prompt after replacing <token>: {prompt}') logger.info(f'Negative prompt after replacing <token>: {negative}') return prompt, negative @dataclass class UNet2DConditionOutput: # Not sure how to check what unet_traced.pt contains, and user wants. HalfTensor or FloatTensor sample: torch.HalfTensor def enable_vram(pipe): pipe.enable_sequential_cpu_offload() pipe.enable_vae_slicing() pipe.unet.to(memory_format=torch.channels_last) pipe.enable_attention_slicing(1) # pipe.enable_model_cpu_offload() def get_model_path(sd_version='2.1', clip_version='large', hf_key=None): if hf_key is not None: logger.info(f'[INFO] using hugging face custom model key: {hf_key}') sd_path = hf_key elif sd_version == '2.1': sd_path = "checkpoints/stable-diffusion-2-1-base" elif sd_version == '2.0': sd_path = "checkpoints/stable-diffusion-2-base" elif sd_version == '1.5': sd_path = "checkpoints/stable-diffusion-v1-5" elif 'zeroscope' in sd_version: sd_path = "checkpoints/" + sd_version else: raise ValueError( f'Stable-diffusion version {sd_version} not supported.') if clip_version == 'base': clip_path = "openai/clip-vit-base-patch32" else: clip_path = "openai/clip-vit-large-patch14" return sd_path, clip_path def check_within(x, low, high): if low is None and high is None: return False elif low is None: if x <= high: return True elif high is None: if x >= low: return True elif x >= low and x <= high: return True else: return False return False class ControlNetStableDiffusion(nn.Module): def __init__(self, opt, device, fp16, vram_O, sd_version='2.1', hf_key=None, t_range=[0.02, 0.98], use_clip=False, clip_version='base', clip_iterative=True, clip_t=0.4, **kwargs ): super().__init__() self.device = device self.vram_O = vram_O self.fp16 = fp16 self.opt = opt self.new_sds = opt.get('new_sds', False) self.cn_size = opt.cn_size self.cn_scale = opt.cn_scale logger.info(f'[INFO] loading stable diffusion...') sd_path, clip_path = get_model_path('1.5', clip_version, None) self.precision_t = torch.float16 if fp16 else torch.float32 self.sd_version = sd_path # Create model ## NOTE only sd 1.5 is supported sd_pipe = DiffusionPipeline.from_pretrained( sd_path, torch_dtype=self.precision_t, local_files_only=False) controlnet = ControlNetModel.from_pretrained(opt.cn_key, torch_dtype=self.precision_t, local_files_only=True) pipe = StableDiffusionControlNetImg2ImgPipeline( vae=sd_pipe.vae, text_encoder=sd_pipe.text_encoder, tokenizer=sd_pipe.tokenizer, unet=sd_pipe.unet, controlnet=controlnet, scheduler=sd_pipe.scheduler, safety_checker=sd_pipe.safety_checker, feature_extractor=sd_pipe.feature_extractor, requires_safety_checker=False ).to(device, self.precision_t) self.vae = pipe.vae self.tokenizer = pipe.tokenizer self.text_encoder = pipe.text_encoder self.unet = pipe.unet self.controlnet = pipe.controlnet if kwargs.get('learned_embeds_path', None) is not None: learned_embeds_path = kwargs['learned_embeds_path'] pipe.load_textual_inversion(learned_embeds_path) # ipdb.set_trace() if vram_O: # this will change device from gpu to other types (meta) enable_vram(pipe) else: if is_xformers_available(): pipe.enable_xformers_memory_efficient_attention() pipe.to(device) # if is_torch_version(">=", "2.0.0"): # pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) self.scheduler = DDIMScheduler.from_pretrained( sd_path, subfolder="scheduler", torch_dtype=self.precision_t, local_files_only=False) self.num_train_timesteps = self.scheduler.config.num_train_timesteps self.min_step = int(self.num_train_timesteps * t_range[0]) self.max_step = int(self.num_train_timesteps * t_range[1]) self.alphas = self.scheduler.alphas_cumprod.to( self.device) # for convenience logger.info(f'[INFO] loaded stable diffusion!') # for CLIP self.use_clip = use_clip if self.use_clip: #breakpoint() self.clip_model = CLIPModel.from_pretrained(clip_path).to(device) image_processor = CLIPProcessor.from_pretrained(clip_path).image_processor self.image_processor = transforms.Compose([ transforms.Resize((image_processor.crop_size['height'], image_processor.crop_size['width'])), transforms.Normalize(image_processor.image_mean, image_processor.image_std), ]) for p in self.clip_model.parameters(): p.requires_grad = False self.clip_iterative = clip_iterative self.clip_t = int(self.num_train_timesteps * clip_t) @torch.no_grad() def get_text_embeds(self, prompt): # Tokenize text and get embeddings text_input = self.tokenizer( prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt') text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0] return text_embeddings @torch.no_grad() def get_all_text_embeds(self, prompt): # Tokenize text and get embeddings text_input = self.tokenizer( prompt, padding='max_length', max_length=self.tokenizer.model_max_length, truncation=True, return_tensors='pt') text_embeddings = self.text_encoder(text_input.input_ids.to(self.device)) # text_z = text_z / text_z.norm(dim=-1, keepdim=True) # return all text embeddings and class embeddings return torch.cat([text_embeddings[0], text_embeddings[1].unsqueeze(1)], dim=1) # @torch.no_grad() def get_clip_img_embeds(self, img): img = self.image_processor(img) image_z = self.clip_model.get_image_features(img) image_z = image_z / image_z.norm(dim=-1, keepdim=True) # normalize features return image_z def clip_loss(self, ref_z, pred_rgb): image_z = self.get_clip_img_embeds(pred_rgb) loss = spherical_dist_loss(image_z, ref_z) return loss def set_epoch(self, epoch): self.epoch = epoch def noise_sample(self, step=None, shape=1): return torch.randint(self.min_step, self.max_step+1, (shape,), dtype=torch.long) def train_step(self, text_embeddings, cn_text_embeddings, pred_rgb, cn_rgb, guidance_scale=100, as_latent=False, grad_clip=None, grad_scale=1.0, image_ref_clip=None, text_ref_clip=None, clip_guidance=100, clip_image_loss=False, density=None, save_guidance_path=None, step=None, first_frame=None, depth=None, # b,f,1,h,w, 0-1 start_from_zero=True, ): enable_clip = self.use_clip and clip_guidance > 0 and not as_latent enable_sds = True sd_size = self.cn_size cn_rgb = cn_rgb.detach() video_generation = False batch_size = pred_rgb.size(0) if pred_rgb.ndim == 5: # B,F,C,H,W video_generation = True num_frame = pred_rgb.size(1) pred_rgb = rearrange(pred_rgb, "b f c h w -> (b f) c h w") cn_rgb = rearrange(cn_rgb, "b f c h w -> (b f) c h w") # interp to 512x512 to be fed into vae. ## both should be 0-1 here pred_rgb_512 = F.interpolate( pred_rgb, (sd_size, sd_size), mode='bilinear', align_corners=False) controlnet_conditioning_image = F.interpolate( cn_rgb, (sd_size, sd_size), mode='bilinear', align_corners=False) controlnet_conditioning_image = torch.cat([controlnet_conditioning_image]*2, dim=0) # ipdb.set_trace() if text_embeddings.size(0) != num_frame*2: text_embeddings = torch.cat([text_embeddings[:1].repeat(num_frame, 1, 1), text_embeddings[1:].repeat(num_frame, 1, 1)], dim=0) if cn_text_embeddings.size(0) != num_frame*2: cn_text_embeddings = torch.cat([cn_text_embeddings[:1].repeat(num_frame, 1, 1), cn_text_embeddings[1:].repeat(num_frame, 1, 1)], dim=0) # ipdb.set_trace() # encode image into latents with vae, requires grad! latents = self.encode_imgs(pred_rgb_512) t = self.noise_sample(step=step, shape=batch_size).to(self.device) ## here should we keep a same noise t each frame? Not very necessary? if enable_clip and self.clip_iterative: if t > self.clip_t: enable_clip = False else: enable_sds = False # predict the noise residual with unet, NO grad! with torch.no_grad(): # add noise noise = torch.randn_like(latents) latents_noisy = self.scheduler.add_noise(latents, noise, t) # pred noise latent_model_input = torch.cat([latents_noisy] * 2) down_block_res_samples, mid_block_res_sample = self.controlnet( latent_model_input, t, encoder_hidden_states=cn_text_embeddings, controlnet_cond=controlnet_conditioning_image, conditioning_scale=self.cn_scale, return_dict=False, ) noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, down_block_additional_residuals=down_block_res_samples, mid_block_additional_residual=mid_block_res_sample, ).sample # perform guidance (high scale from paper!) noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_text + guidance_scale * \ (noise_pred_text - noise_pred_uncond) grad_clipd = 0 # ipdb.set_trace() w = (1 - self.alphas[t])[:, None, None, None] # 1,1,1,1 # w = self.alphas[t] ** 0.5 * (1 - self.alphas[t]) # grad_sds = w * (noise_pred - noise) grad_sds = grad_scale * w * (noise_pred - noise) loss_sds = grad_sds.abs().mean().detach() grad_clipd = 0. loss_clipd = 0. grad = grad_clipd + grad_sds if grad_clip is not None: grad = grad.clamp(-grad_clip, grad_clip) grad = torch.nan_to_num(grad) if self.new_sds: targets = (latents - grad).detach() # if self.opt.grad_dyn: targets = ( (latents_noisy - (1 - self.alphas[t]) ** (0.5) * noise_pred) / self.alphas[t] ** (0.5) ).detach() if self.opt.get('mean_sds', False): loss = 0.5 * F.mse_loss(latents.float(), targets, reduction='mean') # * grad_scale else: loss = 0.5 * F.mse_loss(latents.float(), targets, reduction='sum') / latents.shape[0] # * grad_scale # B,4,H,W -> sum over 4,H,W else: # grad = grad * grad_scale # grad = torch.nan_to_num(grad) latents.backward(gradient=grad, retain_graph=True) loss = grad.abs().mean().detach() # B,4,H,W all mean if not enable_clip: loss_sds = loss if save_guidance_path: with torch.no_grad(): # save original input images = [] os.makedirs(os.path.dirname(save_guidance_path), exist_ok=True) timesteps = torch.arange(50, 1000, 300, dtype=torch.long, device=self.device) for t in timesteps: # ipdb.set_trace() if as_latent: pred_rgb_512 = self.decode_latents(latents, video_generation) latents_noisy = self.scheduler.add_noise(latents, noise, t) # pred noise latent_model_input = torch.cat([latents_noisy] * 2) down_block_res_samples, mid_block_res_sample = self.controlnet( latent_model_input, t, encoder_hidden_states=cn_text_embeddings, controlnet_cond=controlnet_conditioning_image, conditioning_scale=self.cn_scale, return_dict=False, ) noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings, down_block_additional_residuals=down_block_res_samples, mid_block_additional_residual=mid_block_res_sample ).sample # noise_pred = self.unet(latent_model_input, t, # encoder_hidden_states=text_embeddings).sample # perform guidance (high scale from paper!) noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_text + guidance_scale * \ (noise_pred_text - noise_pred_uncond) pred_original_sample = self.decode_latents((latents_noisy - (1 - self.alphas[t]) ** (0.5) * noise_pred) / self.alphas[t] ** (0.5)) # visualize predicted denoised image # claforte: discuss this with Vikram!! result_hopefully_less_noisy_image = self.decode_latents(latents - w*grad_scale*(noise_pred - noise)) # visualize noisier image result_noisier_image = self.decode_latents(latents_noisy) viz_image_list = [pred_rgb_512, controlnet_conditioning_image.chunk(2,dim=0)[0], pred_original_sample, result_hopefully_less_noisy_image] viz_image_list = [rearrange(_img, "(b f) c h w -> b c f h w", f=num_frame) for _img in viz_image_list] image = torch.cat(viz_image_list, dim=0) images.append(image) n_rows = images[0].size(0) if video_generation: viz_images = torch.cat(images, dim=0).detach().mul(255).to(torch.uint8) # b,c,f,h,w
save_tensor2image(rearrange(viz_images, 'b c f h w -> b f c h w'), save_guidance_path, n_rows=n_rows)
1
2023-11-23 10:34:08+00:00
16k
alexzhou907/DreamPropeller
threestudio/systems/base.py
[ { "identifier": "Exporter", "path": "threestudio/models/exporters/base.py", "snippet": "class Exporter(BaseObject):\n @dataclass\n class Config(BaseObject.Config):\n save_video: bool = False\n\n cfg: Config\n\n def configure(\n self,\n geometry: BaseImplicitGeometry,\n ...
import os import pytorch_lightning as pl import torch.nn.functional as F import threestudio import torch import numpy as np import copy from dataclasses import dataclass, field from threestudio.models.exporters.base import Exporter, ExporterOutput from threestudio.systems.utils import parse_optimizer, parse_scheduler from threestudio.utils.base import ( Updateable, update_end_if_possible, update_if_possible, ) from threestudio.utils.config import parse_structured from threestudio.utils.misc import C, cleanup, get_device, load_module_weights from threestudio.utils.saving import SaverMixin from threestudio.utils.typing import * from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.utils.config import load_config, parse_structured
12,828
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, device=get_device(), resumed=False, configure=True) -> None: super().__init__()
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, device=get_device(), resumed=False, configure=True) -> None: super().__init__()
self.cfg = parse_structured(self.Config, cfg)
7
2023-11-27 23:39:49+00:00
16k
CineMingle/CineMingle
Movie_Data_Capture.py
[ { "identifier": "get_data_from_json", "path": "scraper.py", "snippet": "def get_data_from_json(\n file_number: str,\n open_cc: opencc.OpenCC,\n specified_source: str, specified_url: str) -> typing.Optional[dict]:\n \n # iterate through all services and fetch the data 从网站上查询片名解...
import argparse import json import os import random import re import sys import time import shutil import typing import urllib3 import signal import platform import config from datetime import datetime, timedelta from lxml import etree from pathlib import Path from opencc import OpenCC from scraper import get_data_from_json from ADC_function import file_modification_days, get_html, parallel_download_files from number_parser import get_number from core import core_main, core_main_no_net_op, moveFailedFolder, debug_print
13,417
is_sym = full_name.is_symlink() if main_mode != 3 and (is_sym or (full_name.stat().st_nlink > 1 and not conf.scan_hardlink())): # 短路布尔 符号链接不取stat(),因为符号链接可能指向不存在目标 continue # 模式不等于3下跳过软连接和未配置硬链接刮削 # 调试用0字节样本允许通过,去除小于120MB的广告'苍老师强力推荐.mp4'(102.2MB)'黑道总裁.mp4'(98.4MB)'有趣的妹子激情表演.MP4'(95MB)'有趣的臺灣妹妹直播.mp4'(15.1MB) movie_size = 0 if is_sym else full_name.stat().st_size # 同上 符号链接不取stat()及st_size,直接赋0跳过小视频检测 # if 0 < movie_size < 125829120: # 1024*1024*120=125829120 # continue if cliRE and not cliRE.search(absf) or trailerRE.search(full_name.name): continue if main_mode == 3: nfo = full_name.with_suffix('.nfo') if not nfo.is_file(): if debug: print(f"[!]Metadata {nfo.name} not found for '{absf}'") elif nfo_skip_days > 0 and file_modification_days(nfo) <= nfo_skip_days: skip_nfo_days_cnt += 1 if debug: print(f"[!]Skip movie by it's .nfo which modified within {nfo_skip_days} days: '{absf}'") continue total.append(absf) if skip_failed_cnt: print(f"[!]Skip {skip_failed_cnt} movies in failed list '{failed_list_txt_path}'.") if skip_nfo_days_cnt: print( f"[!]Skip {skip_nfo_days_cnt} movies in source folder '{source}' who's .nfo modified within {nfo_skip_days} days.") if nfo_skip_days <= 0 or not link_mode or main_mode == 3: return total # 软连接方式,已经成功削刮的也需要从成功目录中检查.nfo更新天数,跳过N天内更新过的 skip_numbers = set() success_folder = Path(conf.success_folder()).resolve() for f in success_folder.glob(r'**/*'): if not re.match(r'\.nfo$', f.suffix, re.IGNORECASE): continue if file_modification_days(f) > nfo_skip_days: continue number = get_number(False, f.stem) if not number: continue skip_numbers.add(number.lower()) rm_list = [] for f in total: n_number = get_number(False, os.path.basename(f)) if n_number and n_number.lower() in skip_numbers: rm_list.append(f) for f in rm_list: total.remove(f) if debug: print(f"[!]Skip file successfully processed within {nfo_skip_days} days: '{f}'") if len(rm_list): print( f"[!]Skip {len(rm_list)} movies in success folder '{success_folder}' who's .nfo modified within {nfo_skip_days} days.") return total def create_failed_folder(failed_folder: str): """ 新建failed文件夹 """ if not os.path.exists(failed_folder): try: os.makedirs(failed_folder) except: print(f"[-]Fatal error! Can not make folder '{failed_folder}'") os._exit(0) def rm_empty_folder(path): """ Recursively removes empty folders from a given path. This function is useful for cleaning up the directory structure by removing folders that no longer contain any files. :param path: The path where empty folders will be searched for and removed. """ abspath = os.path.abspath(path) deleted = set() for current_dir, subdirs, files in os.walk(abspath, topdown=False): try: still_has_subdirs = any(_ for subdir in subdirs if os.path.join(current_dir, subdir) not in deleted) if not any(files) and not still_has_subdirs and not os.path.samefile(path, current_dir): os.rmdir(current_dir) deleted.add(current_dir) print('[+]Deleting empty folder', current_dir) except: pass def create_data_and_move(movie_path: str, zero_op: bool, no_net_op: bool, oCC): """ Processes a movie file, generates necessary data, and moves the file to an appropriate directory based on the outcome. This function is central to the application's file processing logic, including scraping, organizing, and error handling. :param movie_path: Path of the movie file to be processed. :param zero_op: A boolean flag indicating whether to perform a dry run (no actual file operations). :param no_net_op: A boolean flag to indicate whether network operations are to be skipped. :param oCC: An OpenCC instance for language conversion, if required. """ # Normalized number, eg: 111xxx-222.mp4 -> xxx-222.mp4 skip_file_names = config.getInstance().skip_file_names() debug = config.getInstance().debug() n_number = get_number(debug, os.path.basename(movie_path)) movie_path = os.path.abspath(movie_path) # print(movie_path) for skip_name in skip_file_names: if skip_name in movie_path: print('[+]Skipping file:{}'.format(movie_path)) return if debug is True: print(f"[!] [{n_number}] As Number Processing for '{movie_path}'") if zero_op: return if n_number: if no_net_op: core_main_no_net_op(movie_path, n_number) else: core_main(movie_path, n_number, oCC) else: print("[-] number empty ERROR")
def check_update(local_version): """ Check for updates by comparing the local version of the application with the latest version available on GitHub. It fetches the latest release information from GitHub and compares the version numbers. If a new version is available, it prints out the update information. :param local_version: The current local version of the application. """ htmlcode = get_html("https://api.github.com/repos/CineMingle/CineMingle/releases/latest") data = json.loads(htmlcode) remote = int(data["tag_name"].replace(".", "")) local_version = int(local_version.replace(".", "")) if local_version < remote: print("[*]" + ("* New update " + str(data["tag_name"]) + " *").center(54)) print("[*]" + "↓ Download ↓".center(54)) print("[*]https://github.com/CineMingle/CineMingle/releases") print("[*]======================================================") def argparse_function(ver: str) -> typing.Tuple[str, str, str, str, bool, bool, str, str]: """ Parses command-line arguments and returns the parsed values. It sets up the argument parser with various options for the application and returns the parsed arguments and their values. It also loads configuration from a config file. :param ver: The version of the application, used for the version argument. :return: A tuple containing various parsed arguments and flags. """ conf = config.getInstance() parser = argparse.ArgumentParser(epilog=f"Load Config file '{conf.ini_path}'.") parser.add_argument("file", default='', nargs='?', help="Single Movie file path.") parser.add_argument("-p", "--path", default='movies', nargs='?', help="Analysis folder path.") parser.add_argument("-m", "--main-mode", default='', nargs='?', help="Main mode. 1:Scraping 2:Organizing 3:Scraping in analysis folder") parser.add_argument("-n", "--number", default='', nargs='?', help="Custom file number of single movie file.") # parser.add_argument("-C", "--config", default='config.ini', nargs='?', help="The config file Path.") parser.add_argument("-L", "--link-mode", default='', nargs='?', help="Create movie file link. 0:moving movie file, do not create link 1:soft link 2:try hard link first") default_logdir = str(Path.home() / '.mlogs') parser.add_argument("-o", "--log-dir", dest='logdir', default=default_logdir, nargs='?', help=f"""Duplicate stdout and stderr to logfiles in logging folder, default on. default folder for current user: '{default_logdir}'. Change default folder to an empty file, or use --log-dir= to turn log off.""") parser.add_argument("-q", "--regex-query", dest='regexstr', default='', nargs='?', help="python re module regex filepath filtering.") parser.add_argument("-d", "--nfo-skip-days", dest='days', default='', nargs='?', help="Override nfo_skip_days value in config.") parser.add_argument("-c", "--stop-counter", dest='cnt', default='', nargs='?', help="Override stop_counter value in config.") parser.add_argument("-R", "--rerun-delay", dest='delaytm', default='', nargs='?', help="Delay (eg. 1h10m30s or 60 (second)) time and rerun, until all movies proceed. Note: stop_counter value in config or -c must none zero.") parser.add_argument("-i", "--ignore-failed-list", action="store_true", help="Ignore failed list '{}'".format( os.path.join(os.path.abspath(conf.failed_folder()), 'failed_list.txt'))) parser.add_argument("-a", "--auto-exit", action="store_true", help="Auto exit after program complete") parser.add_argument("-g", "--debug", action="store_true", help="Turn on debug mode to generate diagnostic log for issue report.") parser.add_argument("-N", "--no-network-operation", action="store_true", help="No network query, do not get metadata, for cover cropping purposes, only takes effect when main mode is 3.") parser.add_argument("-w", "--website", dest='site', default='', nargs='?', help="Override [priority]website= in config.") parser.add_argument("-D", "--download-images", dest='dnimg', action="store_true", help="Override [common]download_only_missing_images=0 force invoke image downloading.") parser.add_argument("-C", "--config-override", dest='cfgcmd', action='append', nargs=1, help="Common use config override. Grammar: section:key=value[;[section:]key=value] eg. 'de:s=1' or 'debug_mode:switch=1' override[debug_mode]switch=1 Note:this parameters can be used multiple times") parser.add_argument("-z", "--zero-operation", dest='zero_op', action="store_true", help="""Only show job list of files and numbers, and **NO** actual operation is performed. It may help you correct wrong numbers before real job.""") parser.add_argument("-v", "--version", action="version", version=ver) parser.add_argument("-s", "--search", default='', nargs='?', help="Search number") parser.add_argument("-ss", "--specified-source", default='', nargs='?', help="specified Source.") parser.add_argument("-su", "--specified-url", default='', nargs='?', help="specified Url.") args = parser.parse_args() def set_natural_number_or_none(sk, value): if isinstance(value, str) and value.isnumeric() and int(value) >= 0: conf.set_override(f'{sk}={value}') def set_str_or_none(sk, value): if isinstance(value, str) and len(value): conf.set_override(f'{sk}={value}') def set_bool_or_none(sk, value): if isinstance(value, bool) and value: conf.set_override(f'{sk}=1') set_natural_number_or_none("common:main_mode", args.main_mode) set_natural_number_or_none("common:link_mode", args.link_mode) set_str_or_none("common:source_folder", args.path) set_bool_or_none("common:auto_exit", args.auto_exit) set_natural_number_or_none("common:nfo_skip_days", args.days) set_natural_number_or_none("advenced_sleep:stop_counter", args.cnt) set_bool_or_none("common:ignore_failed_list", args.ignore_failed_list) set_str_or_none("advenced_sleep:rerun_delay", args.delaytm) set_str_or_none("priority:website", args.site) if isinstance(args.dnimg, bool) and args.dnimg: conf.set_override("common:download_only_missing_images=0") set_bool_or_none("debug_mode:switch", args.debug) if isinstance(args.cfgcmd, list): for cmd in args.cfgcmd: conf.set_override(cmd[0]) no_net_op = False if conf.main_mode() == 3: no_net_op = args.no_network_operation if no_net_op: conf.set_override("advenced_sleep:stop_counter=0;advenced_sleep:rerun_delay=0s;face:aways_imagecut=1") return args.file, args.number, args.logdir, args.regexstr, args.zero_op, no_net_op, args.search, args.specified_source, args.specified_url class OutLogger(object): def __init__(self, logfile) -> None: self.term = sys.stdout self.log = open(logfile, "w", encoding='utf-8', buffering=1) self.filepath = logfile def __del__(self): self.close() def __enter__(self): pass def __exit__(self, *args): self.close() def write(self, msg): self.term.write(msg) self.log.write(msg) def flush(self): if 'flush' in dir(self.term): self.term.flush() if 'flush' in dir(self.log): self.log.flush() if 'fileno' in dir(self.log): os.fsync(self.log.fileno()) def close(self): if self.term is not None: sys.stdout = self.term self.term = None if self.log is not None: self.log.close() self.log = None class ErrLogger(OutLogger): def __init__(self, logfile) -> None: self.term = sys.stderr self.log = open(logfile, "w", encoding='utf-8', buffering=1) self.filepath = logfile def close(self): if self.term is not None: sys.stderr = self.term self.term = None if self.log is not None: self.log.close() self.log = None def dupe_stdout_to_logfile(logdir: str): """ Duplicates the standard output (stdout) and standard error (stderr) to log files. This function creates log files in the specified directory and redirects stdout and stderr to these files for logging purposes. :param logdir: The directory where log files will be created and saved. """ if not isinstance(logdir, str) or len(logdir) == 0: return log_dir = Path(logdir) if not log_dir.exists(): try: log_dir.mkdir(parents=True, exist_ok=True) except: pass if not log_dir.is_dir(): return # Tips for disabling logs by change directory to a same name empty regular file abslog_dir = log_dir.resolve() log_tmstr = datetime.now().strftime("%Y%m%dT%H%M%S") logfile = abslog_dir / f'mdc_{log_tmstr}.txt' errlog = abslog_dir / f'mdc_{log_tmstr}_err.txt' sys.stdout = OutLogger(logfile) sys.stderr = ErrLogger(errlog) def close_logfile(logdir: str): """ Closes the log files and restores standard output and error streams. This function is typically called at the end of the application to ensure that log files are properly closed. :param logdir: The directory where log files are saved. """ if not isinstance(logdir, str) or len(logdir) == 0 or not os.path.isdir(logdir): return # 日志关闭前保存日志路径 filepath = None try: filepath = sys.stdout.filepath except: pass sys.stdout.close() sys.stderr.close() log_dir = Path(logdir).resolve() if isinstance(filepath, Path): print(f"Log file '{filepath}' saved.") assert (filepath.parent.samefile(log_dir)) # 清理空文件 for f in log_dir.glob(r'*_err.txt'): if f.stat().st_size == 0: try: f.unlink(missing_ok=True) except: pass # 合并日志 只检测日志目录内的文本日志,忽略子目录。三天前的日志,按日合并为单个日志,三个月前的日志, # 按月合并为单个月志,去年及以前的月志,今年4月以后将之按年合并为年志 # 测试步骤: """ LOGDIR=/tmp/mlog mkdir -p $LOGDIR for f in {2016..2020}{01..12}{01..28};do;echo $f>$LOGDIR/mdc_${f}T235959.txt;done for f in {01..09}{01..28};do;echo 2021$f>$LOGDIR/mdc_2021${f}T235959.txt;done for f in {00..23};do;echo 20211001T$f>$LOGDIR/mdc_20211001T${f}5959.txt;done echo "$(ls -1 $LOGDIR|wc -l) files in $LOGDIR" # 1932 files in /tmp/mlog mdc -zgic1 -d0 -m3 -o $LOGDIR # python3 ./Movie_Data_Capture.py -zgic1 -o $LOGDIR ls $LOGDIR # rm -rf $LOGDIR """ today = datetime.today() # 第一步,合并到日。3天前的日志,文件名是同一天的合并为一份日志 for i in range(1): txts = [f for f in log_dir.glob(r'*.txt') if re.match(r'^mdc_\d{8}T\d{6}$', f.stem, re.A)] if not txts or not len(txts): break e = [f for f in txts if '_err' in f.stem] txts.sort() tmstr_3_days_ago = (today.replace(hour=0) - timedelta(days=3)).strftime("%Y%m%dT99") deadline_day = f'mdc_{tmstr_3_days_ago}' day_merge = [f for f in txts if f.stem < deadline_day] if not day_merge or not len(day_merge): break cutday = len('T235959.txt') # cut length mdc_20201201|T235959.txt for f in day_merge: try: day_file_name = str(f)[:-cutday] + '.txt' # mdc_20201201.txt with open(day_file_name, 'a', encoding='utf-8') as m: m.write(f.read_text(encoding='utf-8')) f.unlink(missing_ok=True) except: pass # 第二步,合并到月 for i in range(1): # 利用1次循环的break跳到第二步,避免大块if缩进或者使用goto语法 txts = [f for f in log_dir.glob(r'*.txt') if re.match(r'^mdc_\d{8}$', f.stem, re.A)] if not txts or not len(txts): break txts.sort() tmstr_3_month_ago = (today.replace(day=1) - timedelta(days=3 * 30)).strftime("%Y%m32") deadline_month = f'mdc_{tmstr_3_month_ago}' month_merge = [f for f in txts if f.stem < deadline_month] if not month_merge or not len(month_merge): break tomonth = len('01.txt') # cut length mdc_202012|01.txt for f in month_merge: try: month_file_name = str(f)[:-tomonth] + '.txt' # mdc_202012.txt with open(month_file_name, 'a', encoding='utf-8') as m: m.write(f.read_text(encoding='utf-8')) f.unlink(missing_ok=True) except: pass # 第三步,月合并到年 for i in range(1): if today.month < 4: break mons = [f for f in log_dir.glob(r'*.txt') if re.match(r'^mdc_\d{6}$', f.stem, re.A)] if not mons or not len(mons): break mons.sort() deadline_year = f'mdc_{today.year - 1}13' year_merge = [f for f in mons if f.stem < deadline_year] if not year_merge or not len(year_merge): break toyear = len('12.txt') # cut length mdc_2020|12.txt for f in year_merge: try: year_file_name = str(f)[:-toyear] + '.txt' # mdc_2020.txt with open(year_file_name, 'a', encoding='utf-8') as y: y.write(f.read_text(encoding='utf-8')) f.unlink(missing_ok=True) except: pass # 第四步,压缩年志 如果有压缩需求,请自行手工压缩,或者使用外部脚本来定时完成。推荐nongnu的lzip,对于 # 这种粒度的文本日志,压缩比是目前最好的。lzip -9的运行参数下,日志压缩比要高于xz -9,而且内存占用更少, # 多核利用率更高(plzip多线程版本),解压速度更快。压缩后的大小差不多是未压缩时的2.4%到3.7%左右, # 100MB的日志文件能缩小到3.7MB。 return filepath def signal_handler(*args): """ A signal handler function for handling operating system signals like Ctrl+C (SIGINT). It defines the behavior of the application when such signals are received, such as graceful termination. :param args: Variable argument list, used to handle signal information. """ print('[!]Ctrl+C detected, Exit.') os._exit(9) def sigdebug_handler(*args): """ A signal handler function specifically for toggling debug mode on or off. It alters the debug configuration based on certain system signals (like window size change in Unix systems). :param args: Variable argument list, used to handle signal information. """ conf = config.getInstance() conf.set_override(f"debug_mode:switch={int(not conf.debug())}") print(f"[!]Debug {('oFF', 'On')[int(conf.debug())]}") # 新增失败文件列表跳过处理,及.nfo修改天数跳过处理,提示跳过视频总数,调试模式(-g)下详细被跳过文件,跳过小广告 def movie_lists(source_folder, regexstr: str) -> typing.List[str]: """ Generates a list of movie file paths from the specified source folder. It filters files based on regular expressions and other criteria, such as file type and size. :param source_folder: The folder to scan for movie files. :param regexstr: A regular expression string to filter movie files. :return: A list of paths to the movie files that match the criteria. """ conf = config.getInstance() main_mode = conf.main_mode() debug = conf.debug() nfo_skip_days = conf.nfo_skip_days() link_mode = conf.link_mode() file_type = conf.media_type().lower().split(",") trailerRE = re.compile(r'-trailer\.', re.IGNORECASE) cliRE = None if isinstance(regexstr, str) and len(regexstr): try: cliRE = re.compile(regexstr, re.IGNORECASE) except: pass failed_list_txt_path = Path(conf.failed_folder()).resolve() / 'failed_list.txt' failed_set = set() if (main_mode == 3 or link_mode) and not conf.ignore_failed_list(): try: flist = failed_list_txt_path.read_text(encoding='utf-8').splitlines() failed_set = set(flist) if len(flist) != len(failed_set): # 检查去重并写回,但是不改变failed_list.txt内条目的先后次序,重复的只保留最后的 fset = failed_set.copy() for i in range(len(flist) - 1, -1, -1): fset.remove(flist[i]) if flist[i] in fset else flist.pop(i) failed_list_txt_path.write_text('\n'.join(flist) + '\n', encoding='utf-8') assert len(fset) == 0 and len(flist) == len(failed_set) except: pass if not Path(source_folder).is_dir(): print('[-]Source folder not found!') return [] total = [] # source = Path(source_folder).resolve() source = Path(source_folder) skip_failed_cnt, skip_nfo_days_cnt = 0, 0 escape_folder_set = set(re.split("[,,]", conf.escape_folder())) for full_name in source.glob(r'**/*'): if main_mode != 3 and set(full_name.parent.parts) & escape_folder_set: continue if not full_name.suffix.lower() in file_type: continue absf = str(full_name) if absf in failed_set: skip_failed_cnt += 1 if debug: print('[!]Skip failed movie:', absf) continue is_sym = full_name.is_symlink() if main_mode != 3 and (is_sym or (full_name.stat().st_nlink > 1 and not conf.scan_hardlink())): # 短路布尔 符号链接不取stat(),因为符号链接可能指向不存在目标 continue # 模式不等于3下跳过软连接和未配置硬链接刮削 # 调试用0字节样本允许通过,去除小于120MB的广告'苍老师强力推荐.mp4'(102.2MB)'黑道总裁.mp4'(98.4MB)'有趣的妹子激情表演.MP4'(95MB)'有趣的臺灣妹妹直播.mp4'(15.1MB) movie_size = 0 if is_sym else full_name.stat().st_size # 同上 符号链接不取stat()及st_size,直接赋0跳过小视频检测 # if 0 < movie_size < 125829120: # 1024*1024*120=125829120 # continue if cliRE and not cliRE.search(absf) or trailerRE.search(full_name.name): continue if main_mode == 3: nfo = full_name.with_suffix('.nfo') if not nfo.is_file(): if debug: print(f"[!]Metadata {nfo.name} not found for '{absf}'") elif nfo_skip_days > 0 and file_modification_days(nfo) <= nfo_skip_days: skip_nfo_days_cnt += 1 if debug: print(f"[!]Skip movie by it's .nfo which modified within {nfo_skip_days} days: '{absf}'") continue total.append(absf) if skip_failed_cnt: print(f"[!]Skip {skip_failed_cnt} movies in failed list '{failed_list_txt_path}'.") if skip_nfo_days_cnt: print( f"[!]Skip {skip_nfo_days_cnt} movies in source folder '{source}' who's .nfo modified within {nfo_skip_days} days.") if nfo_skip_days <= 0 or not link_mode or main_mode == 3: return total # 软连接方式,已经成功削刮的也需要从成功目录中检查.nfo更新天数,跳过N天内更新过的 skip_numbers = set() success_folder = Path(conf.success_folder()).resolve() for f in success_folder.glob(r'**/*'): if not re.match(r'\.nfo$', f.suffix, re.IGNORECASE): continue if file_modification_days(f) > nfo_skip_days: continue number = get_number(False, f.stem) if not number: continue skip_numbers.add(number.lower()) rm_list = [] for f in total: n_number = get_number(False, os.path.basename(f)) if n_number and n_number.lower() in skip_numbers: rm_list.append(f) for f in rm_list: total.remove(f) if debug: print(f"[!]Skip file successfully processed within {nfo_skip_days} days: '{f}'") if len(rm_list): print( f"[!]Skip {len(rm_list)} movies in success folder '{success_folder}' who's .nfo modified within {nfo_skip_days} days.") return total def create_failed_folder(failed_folder: str): """ 新建failed文件夹 """ if not os.path.exists(failed_folder): try: os.makedirs(failed_folder) except: print(f"[-]Fatal error! Can not make folder '{failed_folder}'") os._exit(0) def rm_empty_folder(path): """ Recursively removes empty folders from a given path. This function is useful for cleaning up the directory structure by removing folders that no longer contain any files. :param path: The path where empty folders will be searched for and removed. """ abspath = os.path.abspath(path) deleted = set() for current_dir, subdirs, files in os.walk(abspath, topdown=False): try: still_has_subdirs = any(_ for subdir in subdirs if os.path.join(current_dir, subdir) not in deleted) if not any(files) and not still_has_subdirs and not os.path.samefile(path, current_dir): os.rmdir(current_dir) deleted.add(current_dir) print('[+]Deleting empty folder', current_dir) except: pass def create_data_and_move(movie_path: str, zero_op: bool, no_net_op: bool, oCC): """ Processes a movie file, generates necessary data, and moves the file to an appropriate directory based on the outcome. This function is central to the application's file processing logic, including scraping, organizing, and error handling. :param movie_path: Path of the movie file to be processed. :param zero_op: A boolean flag indicating whether to perform a dry run (no actual file operations). :param no_net_op: A boolean flag to indicate whether network operations are to be skipped. :param oCC: An OpenCC instance for language conversion, if required. """ # Normalized number, eg: 111xxx-222.mp4 -> xxx-222.mp4 skip_file_names = config.getInstance().skip_file_names() debug = config.getInstance().debug() n_number = get_number(debug, os.path.basename(movie_path)) movie_path = os.path.abspath(movie_path) # print(movie_path) for skip_name in skip_file_names: if skip_name in movie_path: print('[+]Skipping file:{}'.format(movie_path)) return if debug is True: print(f"[!] [{n_number}] As Number Processing for '{movie_path}'") if zero_op: return if n_number: if no_net_op: core_main_no_net_op(movie_path, n_number) else: core_main(movie_path, n_number, oCC) else: print("[-] number empty ERROR")
moveFailedFolder(movie_path)
7
2023-11-25 03:16:13+00:00
16k
abdulhaim/LMRL-Gym
llm_rl_scripts/chess/ppo/train_ppo_gpt2_offline_endgames.py
[ { "identifier": "train_loop", "path": "LLM_RL/algorithms/ppo/train.py", "snippet": "def train_loop(\n trainer: PPOTrain, \n inference: PPOInference, \n policy: PPOPolicy, \n load_dataset: Callable[[PPOInference, PPOPolicy], Union[PPODataset, PPOIterableDataset]], \n evaluator: Optional[Ca...
from typing import Optional from JaxSeq.bucket_manager import open_with_bucket as open from transformers import AutoTokenizer from JaxSeq.utils import convert_path, load_mesh, get_dtype, setup_experiment_save from JaxSeq.utils import BlockingStrategy, Padding, Truncation, get_weight_decay_mask, create_path, get_enabled_save_path from JaxSeq.models.gpt2.interface import GPT2Inference from JaxSeq.models.gpt2.load import load_train_state, ModelLoadMode from LLM_RL.algorithms.ppo.train import train_loop from LLM_RL.algorithms.ppo.base_interface import ppo_loss_fn, FixedKLController, AdaptiveKLController from transformers.generation import GenerationConfig from jaxtyping import PyTree from LLM_RL.algorithms.ppo.gpt2.interface import GPT2ILQLPolicy, GPT2ILQLInference, GPT2PPOTrain from LLM_RL.heads.linear_head import load_train_state_from_config as load_head_train_state_from_config from LLM_RL.heads.linear_head import LinearHeadConfig from JaxSeq.shard_model import shard_params_from_params from LLM_RL.algorithms.ppo.data import PPODataset from functools import partial from JaxSeq.logs import pull_logs from JaxSeq.utils import multihost_device_get from llm_rl_scripts.chess.env.data import chess_text_trajectory_chain_from_json, get_data_from_bucket, get_random_positions_not_in_test from llm_rl_scripts.chess.env.env import text_env_eval_chess_positions import tyro import jax import jax.numpy as jnp import os import optax import pickle as pkl import re import numpy as np
11,394
b1=0.9, b2=0.95, eps=1e-8, weight_decay=weight_decay, mask=mask, ), every_k_schedule=grad_accum_steps, ) head_prng_key = jax.random.PRNGKey(3) value_head_train_state, value_head = load_head_train_state_from_config( model_config=LinearHeadConfig( input_dim=policy_model.config.n_embd, output_dim=1, use_bias=True, initializer_range=0.0, ), model_dtype=jnp.float32, optim_getter=value_head_optim_getter, mesh=mesh, prng_key=head_prng_key, pad_to_output_dim=None, params_dtype=jnp.float32, ) loss_f = partial(ppo_loss_fn, cliprange_value=cliprange_value, cliprange=cliprange, value_loss_coef=value_loss_coef) ppo_inference = GPT2ILQLInference.load_inference( initial_policy_params=initial_policy_params, policy_params=policy_train_state.params, value_head_params=value_head_train_state.params, initial_policy_model=policy_model, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, ) ppo_trainer = GPT2PPOTrain.load_train( policy_train_state=policy_train_state, value_head_train_state=value_head_train_state, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, ) if use_adaptive_kl: kl_controller = AdaptiveKLController(init_kl_coef=init_kl_coef, target=kl_target, horizon=kl_horizon) else: kl_controller = FixedKLController(kl_coef=init_kl_coef) bucket_name = "rl-llm-bench-dataset" blob_name = "endgames/train_unshuffled.jsonl" data = get_data_from_bucket(bucket_name, blob_name) text_trajectory_chains = chess_text_trajectory_chain_from_json(data) n_rounds = len(text_trajectory_chains) // 256 data_round = 0 def ppo_dataset_loader(ppo_inference:GPT2ILQLInference, policy, num_to_sample=256): nonlocal data_round # num_to_sample = len(text_trajectory_chains) // n_rounds chains_for_round = text_trajectory_chains[data_round*num_to_sample:(data_round+1)*num_to_sample] print("congrats! you are done loading data!!") ppo_data, all_kls = ppo_inference.get_ppo_data_from_text_trajectory_chain( chains_for_round, bsize=ppo_data_bsize, max_length=max_input_length+max_output_length, gamma=gamma, lam=lam, kl_weight=kl_controller.value, use_advantage_whitening=use_advantage_whitening, ) mean_kl = all_kls.mean().item() kl_controller.update(mean_kl, train_bsize) ppo_dataset = PPODataset.from_ppo_data_list( ppo_data, tokenizer, BlockingStrategy(Padding.RIGHT, Truncation.RIGHT, max_input_length+max_output_length), ) if save_dir is not None and save_ppo_dataset: print('saving ppo dataset ...') data_save_path = os.path.join(save_dir, 'data_saves', f'{data_round}') if is_main_process: create_path(data_save_path) # save ppo_dataset with open(get_enabled_save_path( os.path.join(data_save_path, 'ppo_dataset.pkl'), enabled=is_main_process, ), 'wb') as f: pkl.dump(ppo_dataset, f) # save text_trajectory_chains with open(get_enabled_save_path( os.path.join(data_save_path, 'text_trajectory_chains.pkl'), enabled=is_main_process, ), 'wb') as f: pkl.dump(text_trajectory_chains, f) # save raw_results # with open(get_enabled_save_path( # os.path.join(data_save_path, 'raw_results.pkl'), # enabled=is_main_process, # ), 'wb') as f: # pkl.dump(raw_results, f) # save summary_results # with open(get_enabled_save_path( # os.path.join(data_save_path, 'summary_results.json'), # enabled=is_main_process, # ), 'w') as f: # json.dump(summary_results, f) # print('done saving ppo dataset.') data_round += 1 return ppo_dataset def evaluator(inference, policy): bucket_name = "rl-llm-bench-dataset" blob_name = "endgames/test_positions.jsonl"
def main( model_load_mode: ModelLoadMode, model_load_path: str, /, # Mark the end of positional arguments. exp_name: Optional[str]=None, outputs_path: Optional[str]=None, data_mesh_shape: int=1, fsdp_mesh_shape: int=1, model_mesh_shape: int=-1, use_wandb: bool=True, wandb_project: Optional[str]=None, n_rounds: int=1, epochs: int=1, max_steps: Optional[int]=None, num_pos_per_setup: int=1, lr: float=1e-5, weight_decay: float=0.0, train_bsize: int=32, grad_accum_steps: int=1, rollout_bsize: int=32, n_rollouts: int=16, ppo_data_bsize: int=32, gradient_checkpointing: bool=False, gradient_checkpointing_policy: str='nothing_saveable', use_fp16_activations: bool=False, use_fp16_params: bool=False, max_input_length: int=512, max_output_length: int=512, log_every: int=256, eval_every_steps: Optional[int]=None, eval_every_epochs: Optional[int]=None, eval_every_rounds: Optional[int]=1, eval_at_beginning: bool=False, eval_at_end: bool=True, save_every_steps: Optional[int]=None, save_every_epochs: Optional[int]=None, save_every_rounds: Optional[int]=None, save_at_beginning: bool=False, save_at_end: bool=True, save_best: bool=True, max_checkpoints: Optional[int]=None, save_train_state: bool=True, save_ppo_dataset: bool=False, save_bf16: bool=True, policy_do_sample: bool=True, policy_num_beams: int=1, policy_temperature: Optional[float]=None, policy_top_p: Optional[float]=None, policy_top_k: Optional[int]=None, gamma: float=1.0, lam: float=0.95, use_advantage_whitening: bool=True, init_kl_coef: float=0.001, kl_target: Optional[float]=None, kl_horizon: Optional[int]=None, cliprange_value: float=0.2, cliprange: float=0.2, value_loss_coef: float=1.0, force_pad_embeddings: bool=False, should_restore_loop_state: bool=False, on_cloud_bucket: bool=True, ): input_args = locals().copy() print(input_args) use_adaptive_kl = (kl_target is not None and kl_horizon is not None) if not use_adaptive_kl: assert kl_target is None and kl_horizon is None tokenizer = AutoTokenizer.from_pretrained('gpt2') tokenizer.add_special_tokens({'pad_token': '<|pad|>'}) mesh = load_mesh((data_mesh_shape, fsdp_mesh_shape, model_mesh_shape), ('dp', 'fsdp', 'mp')) is_main_process = jax.process_index() == 0 print(f"Mesh: {mesh}") print(f"Is main process: {is_main_process}") def policy_optim_getter(params: PyTree): mask = get_weight_decay_mask(( "".join([r"\['ln_[0-9]+'\]", re.escape("['bias']")]), "".join([r"\['ln_[0-9]+'\]", re.escape("['scale']")]), re.escape("['ln_f']['bias']"), re.escape("['ln_f']['scale']"), "bias", ))(params) return optax.MultiSteps( optax.adamw( learning_rate=lr, b1=0.9, b2=0.95, eps=1e-8, weight_decay=weight_decay, mask=mask, ), every_k_schedule=grad_accum_steps, ) model_dtype = get_dtype(use_fp16=use_fp16_activations) params_dtype = get_dtype(use_fp16=use_fp16_params) model_prng_key = jax.random.PRNGKey(2) policy_train_state, policy_model = load_train_state( model_load_mode=model_load_mode, model_load_path=convert_path(model_load_path) if model_load_mode != ModelLoadMode.HF else model_load_path, model_dtype=model_dtype, optim_getter=policy_optim_getter, tokenizer=tokenizer, mesh=mesh, prng_key=model_prng_key, force_pad_embeddings=force_pad_embeddings, params_dtype=params_dtype, ) policy_model.config.gradient_checkpointing = gradient_checkpointing policy_model.config.gradient_checkpointing_policy = gradient_checkpointing_policy with jax.default_device(jax.devices('cpu')[0]): initial_policy_params = jax.tree_util.tree_map( lambda x: multihost_device_get(x, mesh=mesh).copy(), policy_train_state.params, ) initial_policy_params = shard_params_from_params( model=policy_model, params=initial_policy_params, ) loop_state = dict() if should_restore_loop_state and (model_load_mode in {ModelLoadMode.TRAIN_STATE, ModelLoadMode.TRAIN_STATE_PARAMS, ModelLoadMode.PARAMS}): with open(os.path.join(convert_path(model_load_path), 'loop_state.pkl'), 'rb') as f: loop_state = pkl.load(f) policy_inference = GPT2Inference.load_inference( params=policy_train_state.params, model=policy_model, tokenizer=tokenizer, ) # env = FenChessEnvSingleTurn() policy_prng = jax.random.PRNGKey(0) policy = GPT2ILQLPolicy( inference=policy_inference, prng_key=policy_prng, generation_config=GenerationConfig( do_sample=policy_do_sample, num_beams=policy_num_beams, temperature=policy_temperature, top_p=policy_top_p, top_k=policy_top_k, eos_token_id=tokenizer.encode('\n')[0], pad_token_id=tokenizer.pad_token_id, max_new_tokens=max_output_length, ), blocking_strategy=BlockingStrategy( padding=Padding.LEFT, truncation=Truncation.LEFT, max_length=max_input_length, ), out_str_process=lambda x: x.removesuffix('\n')+'\n', ) def value_head_optim_getter(params: PyTree): mask = get_weight_decay_mask(("bias",))(params) return optax.MultiSteps( optax.adamw( learning_rate=lr, b1=0.9, b2=0.95, eps=1e-8, weight_decay=weight_decay, mask=mask, ), every_k_schedule=grad_accum_steps, ) head_prng_key = jax.random.PRNGKey(3) value_head_train_state, value_head = load_head_train_state_from_config( model_config=LinearHeadConfig( input_dim=policy_model.config.n_embd, output_dim=1, use_bias=True, initializer_range=0.0, ), model_dtype=jnp.float32, optim_getter=value_head_optim_getter, mesh=mesh, prng_key=head_prng_key, pad_to_output_dim=None, params_dtype=jnp.float32, ) loss_f = partial(ppo_loss_fn, cliprange_value=cliprange_value, cliprange=cliprange, value_loss_coef=value_loss_coef) ppo_inference = GPT2ILQLInference.load_inference( initial_policy_params=initial_policy_params, policy_params=policy_train_state.params, value_head_params=value_head_train_state.params, initial_policy_model=policy_model, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, ) ppo_trainer = GPT2PPOTrain.load_train( policy_train_state=policy_train_state, value_head_train_state=value_head_train_state, policy_model=policy_model, value_head_model=value_head, tokenizer=tokenizer, loss_fn=loss_f, ) if use_adaptive_kl: kl_controller = AdaptiveKLController(init_kl_coef=init_kl_coef, target=kl_target, horizon=kl_horizon) else: kl_controller = FixedKLController(kl_coef=init_kl_coef) bucket_name = "rl-llm-bench-dataset" blob_name = "endgames/train_unshuffled.jsonl" data = get_data_from_bucket(bucket_name, blob_name) text_trajectory_chains = chess_text_trajectory_chain_from_json(data) n_rounds = len(text_trajectory_chains) // 256 data_round = 0 def ppo_dataset_loader(ppo_inference:GPT2ILQLInference, policy, num_to_sample=256): nonlocal data_round # num_to_sample = len(text_trajectory_chains) // n_rounds chains_for_round = text_trajectory_chains[data_round*num_to_sample:(data_round+1)*num_to_sample] print("congrats! you are done loading data!!") ppo_data, all_kls = ppo_inference.get_ppo_data_from_text_trajectory_chain( chains_for_round, bsize=ppo_data_bsize, max_length=max_input_length+max_output_length, gamma=gamma, lam=lam, kl_weight=kl_controller.value, use_advantage_whitening=use_advantage_whitening, ) mean_kl = all_kls.mean().item() kl_controller.update(mean_kl, train_bsize) ppo_dataset = PPODataset.from_ppo_data_list( ppo_data, tokenizer, BlockingStrategy(Padding.RIGHT, Truncation.RIGHT, max_input_length+max_output_length), ) if save_dir is not None and save_ppo_dataset: print('saving ppo dataset ...') data_save_path = os.path.join(save_dir, 'data_saves', f'{data_round}') if is_main_process: create_path(data_save_path) # save ppo_dataset with open(get_enabled_save_path( os.path.join(data_save_path, 'ppo_dataset.pkl'), enabled=is_main_process, ), 'wb') as f: pkl.dump(ppo_dataset, f) # save text_trajectory_chains with open(get_enabled_save_path( os.path.join(data_save_path, 'text_trajectory_chains.pkl'), enabled=is_main_process, ), 'wb') as f: pkl.dump(text_trajectory_chains, f) # save raw_results # with open(get_enabled_save_path( # os.path.join(data_save_path, 'raw_results.pkl'), # enabled=is_main_process, # ), 'wb') as f: # pkl.dump(raw_results, f) # save summary_results # with open(get_enabled_save_path( # os.path.join(data_save_path, 'summary_results.json'), # enabled=is_main_process, # ), 'w') as f: # json.dump(summary_results, f) # print('done saving ppo dataset.') data_round += 1 return ppo_dataset def evaluator(inference, policy): bucket_name = "rl-llm-bench-dataset" blob_name = "endgames/test_positions.jsonl"
positions = get_random_positions_not_in_test(bucket_name=bucket_name, blob_name=blob_name, num_pos_per_setup=num_pos_per_setup)
10
2023-11-21 00:16:42+00:00
16k
jzmzhong/Automatic-Prosody-Annotator-with-SSWP-CLAP
src/clap_module/conformer/encoder.py
[ { "identifier": "ConvolutionModule", "path": "src/clap_module/conformer/convolution.py", "snippet": "class ConvolutionModule(nn.Module):\r\n \"\"\"ConvolutionModule in Conformer model.\r\n\r\n Args:\r\n channels (int): The number of channels of conv layers.\r\n kernel_size (int): Ker...
import logging import torch import math from .convolution import ConvolutionModule from .encoder_layer import EncoderLayer from .modules import get_activation from .modules import VGG2L from .modules import ( LegacyRelPositionMultiHeadedAttention, MultiHeadedAttention, RelPositionMultiHeadedAttention, ) from .embedding import ( LegacyRelPositionalEncoding, PositionalEncoding, RelPositionalEncoding, ScaledPositionalEncoding, ) from .modules import LayerNorm from .multi_layer_conv import ( Conv1dLinear, MultiLayeredConv1d, ) from .modules import ( PositionwiseFeedForward, ) from .modules import repeat from .sub_sampling import Conv2dSubsampling from ..feature_fusion import AttentionPool1d, DAF, AFF, iAFF
14,312
# Copyright 2020 Johns Hopkins University (Shinji Watanabe) # Northwestern Polytechnical University (Pengcheng Guo) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Encoder definition.""" class Encoder(torch.nn.Module): """Conformer encoder module. Args: idim (int): Input dimension. attention_dim (int): Dimension of attention. attention_heads (int): The number of heads of multi head attention. linear_units (int): The number of units of position-wise feed forward. num_blocks (int): The number of decoder blocks. dropout_rate (float): Dropout rate. positional_dropout_rate (float): Dropout rate after adding positional encoding. attention_dropout_rate (float): Dropout rate in attention. input_layer (Union[str, torch.nn.Module]): Input layer type. normalize_before (bool): Whether to use layer_norm before the first block. concat_after (bool): Whether to concat attention layer's input and output. if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type (str): "linear", "conv1d", or "conv1d-linear". positionwise_conv_kernel_size (int): Kernel size of positionwise conv1d layer. macaron_style (bool): Whether to use macaron style for positionwise layer. pos_enc_layer_type (str): Encoder positional encoding layer type. selfattention_layer_type (str): Encoder attention layer type. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. zero_triu (bool): Whether to zero the upper triangular part of attention matrix. cnn_module_kernel (int): Kernerl size of convolution module. padding_idx (int): Padding idx for input_layer=embed. stochastic_depth_rate (float): Maximum probability to skip the encoder layer. intermediate_layers (Union[List[int], None]): indices of intermediate CTC layer. indices start from 1. if not None, intermediate outputs are returned (which changes return type signature.) """ def __init__( self, idim, attention_dim=256, attention_heads=4, linear_units=2048, num_blocks=6, dropout_rate=0.1, positional_dropout_rate=0.1, attention_dropout_rate=0.0, input_layer="conv2d", normalize_before=True, concat_after=False, ffn_layer_type="linear", ffn_conv_kernel_size=1, macaron_style=False, pos_enc_layer_type="abs_pos", selfattention_layer_type="selfattn", activation_type="relu", use_cnn_module=True, zero_triu=False, cnn_module_kernel=31, padding_idx=-1, stochastic_depth_rate=0.0, intermediate_layers=None, ctc_softmax=None, conditioning_layer_dim=None, max_seq_len=100, enable_fusion=False, fusion_type="", ): """Construct an Encoder object.""" super(Encoder, self).__init__() self.max_seq_len = max_seq_len activation = get_activation(activation_type) if pos_enc_layer_type == "abs_pos": pos_enc_class = PositionalEncoding elif pos_enc_layer_type == "scaled_abs_pos": pos_enc_class = ScaledPositionalEncoding elif pos_enc_layer_type == "rel_pos": assert selfattention_layer_type == "rel_selfattn" pos_enc_class = RelPositionalEncoding elif pos_enc_layer_type == "legacy_rel_pos": assert selfattention_layer_type == "legacy_rel_selfattn" pos_enc_class = LegacyRelPositionalEncoding else: raise ValueError("unknown pos_enc_layer: " + pos_enc_layer_type) self.conv_subsampling_factor = 1 if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(idim, attention_dim), torch.nn.LayerNorm(attention_dim), torch.nn.Dropout(dropout_rate), pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer == "conv2d":
# Copyright 2020 Johns Hopkins University (Shinji Watanabe) # Northwestern Polytechnical University (Pengcheng Guo) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Encoder definition.""" class Encoder(torch.nn.Module): """Conformer encoder module. Args: idim (int): Input dimension. attention_dim (int): Dimension of attention. attention_heads (int): The number of heads of multi head attention. linear_units (int): The number of units of position-wise feed forward. num_blocks (int): The number of decoder blocks. dropout_rate (float): Dropout rate. positional_dropout_rate (float): Dropout rate after adding positional encoding. attention_dropout_rate (float): Dropout rate in attention. input_layer (Union[str, torch.nn.Module]): Input layer type. normalize_before (bool): Whether to use layer_norm before the first block. concat_after (bool): Whether to concat attention layer's input and output. if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type (str): "linear", "conv1d", or "conv1d-linear". positionwise_conv_kernel_size (int): Kernel size of positionwise conv1d layer. macaron_style (bool): Whether to use macaron style for positionwise layer. pos_enc_layer_type (str): Encoder positional encoding layer type. selfattention_layer_type (str): Encoder attention layer type. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. zero_triu (bool): Whether to zero the upper triangular part of attention matrix. cnn_module_kernel (int): Kernerl size of convolution module. padding_idx (int): Padding idx for input_layer=embed. stochastic_depth_rate (float): Maximum probability to skip the encoder layer. intermediate_layers (Union[List[int], None]): indices of intermediate CTC layer. indices start from 1. if not None, intermediate outputs are returned (which changes return type signature.) """ def __init__( self, idim, attention_dim=256, attention_heads=4, linear_units=2048, num_blocks=6, dropout_rate=0.1, positional_dropout_rate=0.1, attention_dropout_rate=0.0, input_layer="conv2d", normalize_before=True, concat_after=False, ffn_layer_type="linear", ffn_conv_kernel_size=1, macaron_style=False, pos_enc_layer_type="abs_pos", selfattention_layer_type="selfattn", activation_type="relu", use_cnn_module=True, zero_triu=False, cnn_module_kernel=31, padding_idx=-1, stochastic_depth_rate=0.0, intermediate_layers=None, ctc_softmax=None, conditioning_layer_dim=None, max_seq_len=100, enable_fusion=False, fusion_type="", ): """Construct an Encoder object.""" super(Encoder, self).__init__() self.max_seq_len = max_seq_len activation = get_activation(activation_type) if pos_enc_layer_type == "abs_pos": pos_enc_class = PositionalEncoding elif pos_enc_layer_type == "scaled_abs_pos": pos_enc_class = ScaledPositionalEncoding elif pos_enc_layer_type == "rel_pos": assert selfattention_layer_type == "rel_selfattn" pos_enc_class = RelPositionalEncoding elif pos_enc_layer_type == "legacy_rel_pos": assert selfattention_layer_type == "legacy_rel_selfattn" pos_enc_class = LegacyRelPositionalEncoding else: raise ValueError("unknown pos_enc_layer: " + pos_enc_layer_type) self.conv_subsampling_factor = 1 if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(idim, attention_dim), torch.nn.LayerNorm(attention_dim), torch.nn.Dropout(dropout_rate), pos_enc_class(attention_dim, positional_dropout_rate), ) elif input_layer == "conv2d":
self.embed = Conv2dSubsampling(
16
2023-11-25 02:38:32+00:00
16k
facebookresearch/ExPLORe
train_finetuning_pixels.py
[ { "identifier": "DrQLearner", "path": "rlpd/agents/drq/drq_learner.py", "snippet": "class DrQLearner(SACLearner):\n data_augmentation_fn: Callable = struct.field(pytree_node=False)\n\n @classmethod\n def create(\n cls,\n seed: int,\n observation_space: gym.Space,\n a...
import os import numpy as np import tqdm import wandb import matplotlib.pyplot as plt import pickle import roboverse import types import jax import jax.numpy as jnp from absl import app, flags from flax.core import FrozenDict from ml_collections import config_flags from flax.core import frozen_dict from flax.training import checkpoints from rlpd.agents import DrQLearner, PixelRND, PixelRM, PixelBCAgent from rlpd.data import MemoryEfficientReplayBuffer, ReplayBuffer from rlpd.evaluation import evaluate from rlpd.wrappers import wrap_pixels from rlpd.agents.drq.icvf import PixelICVF from rlpd import gc_dataset from gym.wrappers import TimeLimit, FilterObservation, RecordEpisodeStatistics from rlpd.data import Dataset from rlpd.data.cog_datasets import COGDataset from functools import partial
13,592
) def render(env, *args, **kwargs): return env.render_obs() if FLAGS.env_name == "Widow250PickTray-v0": env_name_alt = "pickplace" cog_max_path_length = 40 elif FLAGS.env_name == "Widow250DoubleDrawerOpenGraspNeutral-v0": env_name_alt = "closeddrawer_small" cog_max_path_length = 50 elif FLAGS.env_name == "Widow250DoubleDrawerCloseOpenGraspNeutral-v0": env_name_alt = "blockeddrawer1_small" cog_max_path_length = 80 env = roboverse.make(FLAGS.env_name, transpose_image=False) env.render = types.MethodType(render, env) env = FilterObservation(env, ["image"]) env = TimeLimit(env, max_episode_steps=cog_max_path_length) # TODO env, pixel_keys = wrap(env) env = RecordEpisodeStatistics(env, deque_size=1) env.seed(FLAGS.seed) eval_env = roboverse.make(FLAGS.env_name, transpose_image=False) eval_env.render = types.MethodType(render, eval_env) eval_env = FilterObservation(eval_env, ["image"]) eval_env = TimeLimit(eval_env, max_episode_steps=cog_max_path_length) # TODO eval_env, _ = wrap(eval_env) eval_env.seed(FLAGS.seed + 42) dataset_path = os.path.join("data", env_name_alt) print("Data Path:", dataset_path) np_rng = np.random.default_rng(FLAGS.seed) ds = COGDataset( env=env, dataset_path=dataset_path, capacity=300000, subsample_ratio=FLAGS.dataset_subsample_ratio, np_rng=np_rng, ) ds.seed(FLAGS.seed) ds_minr = ds.dataset_dict["rewards"][: len(ds)].min() assert -10 < ds_minr < 10, "maybe sampling reward outside of buffer range" ds_iterator = ds.get_iterator( sample_args={ "batch_size": int(FLAGS.batch_size * FLAGS.utd_ratio * FLAGS.offline_ratio), "pack_obs_and_next_obs": True, } ) replay_buffer = MemoryEfficientReplayBuffer( env.observation_space, env.action_space, FLAGS.max_steps ) replay_buffer_iterator = replay_buffer.get_iterator( sample_args={ "batch_size": int( FLAGS.batch_size * FLAGS.utd_ratio * (1 - FLAGS.offline_ratio) ), "pack_obs_and_next_obs": True, } ) replay_buffer.seed(FLAGS.seed) ########### MODELS ########### # Crashes on some setups if agent is created before replay buffer. kwargs = dict(FLAGS.config) model_cls = kwargs.pop("model_cls") agent = globals()[model_cls].create( FLAGS.seed, env.observation_space, env.action_space, pixel_keys=pixel_keys, **kwargs, ) if FLAGS.offline_relabel_type != "gt": kwargs = dict(FLAGS.rm_config) model_cls = kwargs.pop("model_cls") rm = globals()[model_cls].create( FLAGS.seed + 123, env.observation_space, env.action_space, pixel_keys=pixel_keys, **kwargs, ) else: rm = None if FLAGS.use_rnd_offline or FLAGS.use_rnd_online: kwargs = dict(FLAGS.rnd_config) model_cls = kwargs.pop("model_cls") rnd = globals()[model_cls].create( FLAGS.seed + 123, env.observation_space, env.action_space, pixel_keys=pixel_keys, **kwargs, ) else: rnd = None # Pre-training record_step = 0 # ICVF training and initialize RM and RND with ICVF encoder if FLAGS.use_icvf: # assert rm is not None or rnd is not None, "ICVF is not needed in this configuration" icvf = PixelICVF.create( FLAGS.seed, env.observation_space, env.action_space, pixel_keys=pixel_keys, **dict(FLAGS.config), )
""" Modified from https://github.com/ikostrikov/rlpd/blob/main/rlpd/train_finetuning_pixels.py Original lincense information: MIT License Copyright (c) 2022 Ilya Kostrikov, Philip J. Ball, Laura Smith Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ #! /usr/bin/env python ### cog imports ### ### cog imports ### FLAGS = flags.FLAGS flags.DEFINE_string("project_name", "explore-cog", "wandb project name.") flags.DEFINE_string("env_name", "cheetah-run-v0", "Environment name.") flags.DEFINE_float( "dataset_subsample_ratio", 0.1, "Ratio of the dataset to subsample (done twice)" ) flags.DEFINE_bool("use_icvf", False, "Whether to use the icvf encoder") flags.DEFINE_float("offline_ratio", 0.5, "Offline ratio.") flags.DEFINE_integer("seed", 42, "Random seed.") flags.DEFINE_integer("eval_episodes", 100, "Number of episodes used for evaluation.") flags.DEFINE_integer("log_interval", 1000, "Logging interval.") flags.DEFINE_integer("eval_interval", 5000, "Eval interval.") flags.DEFINE_integer("batch_size", 256, "Mini batch size.") flags.DEFINE_integer("max_steps", 500000, "Number of training steps.") flags.DEFINE_integer( "start_training", 5000, "Number of training steps to start training." ) flags.DEFINE_boolean("tqdm", True, "Use tqdm progress bar.") flags.DEFINE_string("save_dir", "exp_data_cog", "Directory to save checkpoints.") flags.DEFINE_bool("checkpoint_model", False, "save model") flags.DEFINE_bool("checkpoint_buffer", False, "save replay buffer") flags.DEFINE_integer("utd_ratio", 1, "Update to data ratio.") flags.DEFINE_float("bc_pretrain_rollin", 0.0, "rollin coeff") flags.DEFINE_integer( "bc_pretrain_steps", 10000, "Pre-train BC policy for a number of steps on pure offline data", ) config_flags.DEFINE_config_file( "config", "configs/rlpd_pixels_config.py", "File path to the training hyperparameter configuration.", lock_config=False, ) config_flags.DEFINE_config_file( "rm_config", "configs/pixel_rm_config.py", "File path to the training hyperparameter configuration.", lock_config=False, ) config_flags.DEFINE_config_file( "rnd_config", "configs/pixel_rnd_config.py", "File path to the training hyperparameter configuration.", lock_config=False, ) config_flags.DEFINE_config_file( "bc_config", "configs/pixel_bc_config.py", "File path to the training hyperparameter configuration", lock_config=False, ) flags.DEFINE_string( "offline_relabel_type", "gt", "Whether to use reward from the offline dataset. [gt/pred/min]", ) flags.DEFINE_boolean("use_rnd_offline", False, "Whether to use rnd offline.") flags.DEFINE_boolean("use_rnd_online", False, "Whether to use rnd online.") def combine(one_dict, other_dict): combined = {} for k, v in one_dict.items(): if isinstance(v, FrozenDict) or isinstance(v, dict): if len(v) == 0: combined[k] = v else: combined[k] = combine(v, other_dict[k]) else: tmp = np.empty( (v.shape[0] + other_dict[k].shape[0], *v.shape[1:]), dtype=v.dtype ) tmp[0::2] = v tmp[1::2] = other_dict[k] combined[k] = tmp return FrozenDict(combined) def add_prefix(prefix, dict): return {prefix + k: v for k, v in dict.items()} def main(_): wandb.init(project=FLAGS.project_name, mode="online") wandb.config.update(FLAGS) if FLAGS.save_dir is not None: log_dir = os.path.join( FLAGS.save_dir, f"{FLAGS.env_name}-s{FLAGS.seed}-icvf_{FLAGS.use_icvf}-ours_{FLAGS.use_rnd_offline}", ) print("logging to", log_dir) if FLAGS.checkpoint_model: chkpt_dir = os.path.join(log_dir, "checkpoints") os.makedirs(chkpt_dir, exist_ok=True) if FLAGS.checkpoint_buffer: buffer_dir = os.path.join(log_dir, "buffers") os.makedirs(buffer_dir, exist_ok=True) def wrap(env): return wrap_pixels( env, action_repeat=1, num_stack=1, camera_id=0, ) def render(env, *args, **kwargs): return env.render_obs() if FLAGS.env_name == "Widow250PickTray-v0": env_name_alt = "pickplace" cog_max_path_length = 40 elif FLAGS.env_name == "Widow250DoubleDrawerOpenGraspNeutral-v0": env_name_alt = "closeddrawer_small" cog_max_path_length = 50 elif FLAGS.env_name == "Widow250DoubleDrawerCloseOpenGraspNeutral-v0": env_name_alt = "blockeddrawer1_small" cog_max_path_length = 80 env = roboverse.make(FLAGS.env_name, transpose_image=False) env.render = types.MethodType(render, env) env = FilterObservation(env, ["image"]) env = TimeLimit(env, max_episode_steps=cog_max_path_length) # TODO env, pixel_keys = wrap(env) env = RecordEpisodeStatistics(env, deque_size=1) env.seed(FLAGS.seed) eval_env = roboverse.make(FLAGS.env_name, transpose_image=False) eval_env.render = types.MethodType(render, eval_env) eval_env = FilterObservation(eval_env, ["image"]) eval_env = TimeLimit(eval_env, max_episode_steps=cog_max_path_length) # TODO eval_env, _ = wrap(eval_env) eval_env.seed(FLAGS.seed + 42) dataset_path = os.path.join("data", env_name_alt) print("Data Path:", dataset_path) np_rng = np.random.default_rng(FLAGS.seed) ds = COGDataset( env=env, dataset_path=dataset_path, capacity=300000, subsample_ratio=FLAGS.dataset_subsample_ratio, np_rng=np_rng, ) ds.seed(FLAGS.seed) ds_minr = ds.dataset_dict["rewards"][: len(ds)].min() assert -10 < ds_minr < 10, "maybe sampling reward outside of buffer range" ds_iterator = ds.get_iterator( sample_args={ "batch_size": int(FLAGS.batch_size * FLAGS.utd_ratio * FLAGS.offline_ratio), "pack_obs_and_next_obs": True, } ) replay_buffer = MemoryEfficientReplayBuffer( env.observation_space, env.action_space, FLAGS.max_steps ) replay_buffer_iterator = replay_buffer.get_iterator( sample_args={ "batch_size": int( FLAGS.batch_size * FLAGS.utd_ratio * (1 - FLAGS.offline_ratio) ), "pack_obs_and_next_obs": True, } ) replay_buffer.seed(FLAGS.seed) ########### MODELS ########### # Crashes on some setups if agent is created before replay buffer. kwargs = dict(FLAGS.config) model_cls = kwargs.pop("model_cls") agent = globals()[model_cls].create( FLAGS.seed, env.observation_space, env.action_space, pixel_keys=pixel_keys, **kwargs, ) if FLAGS.offline_relabel_type != "gt": kwargs = dict(FLAGS.rm_config) model_cls = kwargs.pop("model_cls") rm = globals()[model_cls].create( FLAGS.seed + 123, env.observation_space, env.action_space, pixel_keys=pixel_keys, **kwargs, ) else: rm = None if FLAGS.use_rnd_offline or FLAGS.use_rnd_online: kwargs = dict(FLAGS.rnd_config) model_cls = kwargs.pop("model_cls") rnd = globals()[model_cls].create( FLAGS.seed + 123, env.observation_space, env.action_space, pixel_keys=pixel_keys, **kwargs, ) else: rnd = None # Pre-training record_step = 0 # ICVF training and initialize RM and RND with ICVF encoder if FLAGS.use_icvf: # assert rm is not None or rnd is not None, "ICVF is not needed in this configuration" icvf = PixelICVF.create( FLAGS.seed, env.observation_space, env.action_space, pixel_keys=pixel_keys, **dict(FLAGS.config), )
gc_ds = gc_dataset.GCSDataset(ds, **gc_dataset.GCSDataset.get_default_config())
9
2023-11-19 21:28:52+00:00
16k
Luo-Z13/pointobb
PointOBB/mmdet/datasets/cocofmt_obb.py
[ { "identifier": "COCO", "path": "PointOBB/mmdet/datasets/api_wrappers/coco_api.py", "snippet": "class COCO(_COCO):\n def __init__(self, annotation_file=None):\n def get_ann_ids(self, img_ids=[], cat_ids=[], area_rng=[], iscrowd=None):\n def get_cat_ids(self, cat_names=[], sup_names=[], cat_ids=...
import itertools import logging import os.path as osp import warnings import mmcv import numpy as np import tempfile import os import shutil from collections import OrderedDict from mmcv.utils import print_log from terminaltables import AsciiTable from huicv.evaluation.expand_cocofmt_eval import COCOExpandEval from huicv.evaluation.location_evaluation import LocationEvaluator from functools import partial from mmdet.core import eval_recalls from .api_wrappers import COCO, COCOeval from .builder import DATASETS from .coco import CocoDataset from .utils import eval_rbbox_map, obb2poly_np, poly2obb_np from huicv.corner_dataset.corner_dataset_util import generate_corner_dataset from huicv.coarse_utils.noise_data_utils import get_new_json_file_path, generate_pseudo_bbox_for_point from .noise_data_utils import get_new_json_file_path
11,030
"""Dump the detection results to a COCO style json file. There are 3 types of results: proposals, bbox predictions, mask predictions, and they have different data types. This method will automatically recognize the type, and dump them to json files. Args: results (list[list | tuple | ndarray]): Testing results of the dataset. outfile_prefix (str): The filename prefix of the json files. If the prefix is "somepath/xxx", the json files will be named "somepath/xxx.bbox.json", "somepath/xxx.segm.json", "somepath/xxx.proposal.json". Returns: dict[str: str]: Possible keys are "bbox", "segm", "proposal", and \ values are corresponding filenames. """ result_files = dict() if isinstance(results[0], list): json_results = self._det2json(results) result_files['bbox'] = f'{outfile_prefix}.bbox.json' result_files['proposal'] = f'{outfile_prefix}.bbox.json' mmcv.dump(json_results, result_files['bbox']) elif isinstance(results[0], tuple): json_results = self._segm2json(results) result_files['bbox'] = f'{outfile_prefix}.bbox.json' result_files['proposal'] = f'{outfile_prefix}.bbox.json' result_files['segm'] = f'{outfile_prefix}.segm.json' mmcv.dump(json_results[0], result_files['bbox']) mmcv.dump(json_results[1], result_files['segm']) elif isinstance(results[0], np.ndarray): json_results = self._proposal2json(results) result_files['proposal'] = f'{outfile_prefix}.proposal.json' mmcv.dump(json_results, result_files['proposal']) else: raise TypeError('invalid type of results') return result_files def format_results(self, results, jsonfile_prefix=None, **kwargs): """Format the results to json (standard format for COCO evaluation). Args: results (list[tuple | numpy.ndarray]): Testing results of the dataset. jsonfile_prefix (str | None): The prefix of json files. It includes the file path and the prefix of filename, e.g., "a/b/prefix". If not specified, a temp file will be created. Default: None. Returns: tuple: (result_files, tmp_dir), result_files is a dict containing \ the json filepaths, tmp_dir is the temporal directory created \ for saving json files when jsonfile_prefix is not specified. """ assert isinstance(results, list), 'results must be a list' assert len(results) == len(self), ( 'The length of results is not equal to the dataset len: {} != {}'. format(len(results), len(self))) if jsonfile_prefix is None: tmp_dir = tempfile.TemporaryDirectory() jsonfile_prefix = osp.join(tmp_dir.name, 'results') else: tmp_dir = None result_files = self.results2json(results, jsonfile_prefix) return result_files, tmp_dir def evaluate(self, results, metric='bbox', logger=None, jsonfile_prefix=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=None, metric_items=None, cocofmt_kwargs={}, skip_eval=False, use_location_metric=False, location_kwargs={}, use_without_bbox_metric=False, without_bbox_kwargs={}, save_result_file=None, ): # add by hui """Evaluation in COCO protocol. Args: results (list[list | tuple]): Testing results of the dataset. metric (str | list[str]): Metrics to be evaluated. Options are 'bbox', 'segm', 'proposal', 'proposal_fast'. logger (logging.Logger | str | None): Logger used for printing related information during evaluation. Default: None. jsonfile_prefix (str | None): The prefix of json files. It includes the file path and the prefix of filename, e.g., "a/b/prefix". If not specified, a temp file will be created. Default: None. classwise (bool): Whether to evaluating the AP for each class. proposal_nums (Sequence[int]): Proposal number used for evaluating recalls, such as recall@100, recall@1000. Default: (100, 300, 1000). iou_thrs (Sequence[float], optional): IoU threshold used for evaluating recalls/mAPs. If set to a list, the average of all IoUs will also be computed. If not specified, [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95] will be used. Default: None. metric_items (list[str] | str, optional): Metric items that will be returned. If not specified, ``['AR@100', 'AR@300', 'AR@1000', 'AR_s@1000', 'AR_m@1000', 'AR_l@1000' ]`` will be used when ``metric=='proposal'``, ``['mAP', 'mAP_50', 'mAP_75', 'mAP_s', 'mAP_m', 'mAP_l']`` will be used when ``metric=='bbox' or metric=='segm'``. Returns: dict[str, float]: COCO style evaluation metric. """ nproc=4 nproc = min(nproc, os.cpu_count()) iou_thr=0.5 scale_ranges=None annotations = [self.get_ann_info(i) for i in range(len(self))] for ann in annotations: ann['bboxes'] = ann['true_bboxes'] eval_results = {} assert isinstance(iou_thr, float)
# add by hui, if there is not corner dataset, create one def generate_corner_json_file_if_not_exist(ann_file, data_root, corner_kwargs): # generate corner json file name if data_root is not None: if not osp.isabs(ann_file): ann_file = osp.join(data_root, ann_file) origin_ann_file = ann_file max_tile_size, tile_overlap = corner_kwargs['max_tile_size'], corner_kwargs['tile_overlap'] ann_file = "{}_corner_w{}h{}ow{}oh{}.json".format( ann_file[:-5], max_tile_size[0], max_tile_size[1], tile_overlap[0], tile_overlap[1]) ann_dir, ann_file_name = osp.split(ann_file) corner_file_dir = osp.join(ann_dir, 'corner') ann_file = osp.join(corner_file_dir, ann_file_name) # generate corner dataset and save to disk, if it not exists if not osp.exists(ann_file): _ = generate_corner_dataset(origin_ann_file, save_path=ann_file, **corner_kwargs) print("generate corner dataset done, please re-run your code.") exit(0) return ann_file def generate_pesudo_bbox_for_noise_data(ann_file, data_root, noise_kwargs): # ann_file, _ = get_new_json_file_path(ann_file, data_root, 'noise', 'noisept') # assert osp.exists(ann_file), "{} not exist.".format(ann_file) ori_ann_file = ann_file pseudo_wh = noise_kwargs['pseudo_wh'] if isinstance(pseudo_wh, (int, float)): noise_kwargs['pseudo_wh'] = pseudo_wh = (pseudo_wh, pseudo_wh) suffix = 'pseuw{}h{}'.format(*pseudo_wh) ann_file, _ = get_new_json_file_path(ori_ann_file, data_root, None, suffix) if not osp.exists(ann_file): _ = generate_pseudo_bbox_for_point(ori_ann_file, ann_file, **noise_kwargs) print("generate pseudo bbox for dataset done, please re-run your code.") exit(0) return ann_file @DATASETS.register_module() class CocoFmtObbDataset(CocoDataset): CLASSES = None def __init__(self, ann_file, version='le90', data_root=None, corner_kwargs=None, train_ignore_as_bg=True, noise_kwargs=None, merge_after_infer_kwargs=None, min_gt_size=None, **kwargs): # add by hui, if there is not corner dataset, create one if corner_kwargs is not None: assert ann_file[-5:] == '.json', "ann_file must be a json file." ann_file = generate_corner_json_file_if_not_exist(ann_file, data_root, corner_kwargs) print("load corner dataset json file from {}".format(ann_file)) if noise_kwargs is not None: if 'pseudo_wh' in noise_kwargs and noise_kwargs['pseudo_wh'] is not None: ann_file = generate_pesudo_bbox_for_noise_data(ann_file, data_root, noise_kwargs) elif 'wh_suffix' in noise_kwargs: ann_file, _ = get_new_json_file_path(ann_file, data_root, noise_kwargs['sub_dir'], noise_kwargs['wh_suffix']) else: raise ValueError('one of [pseudo_wh, wh_suffix] must be given') print("load noise dataset json file from {}".format(ann_file)) self.train_ignore_as_bg = train_ignore_as_bg self.merge_after_infer_kwargs = merge_after_infer_kwargs self.min_gt_size = min_gt_size self.version = version super(CocoFmtObbDataset, self).__init__( ann_file, data_root=data_root, **kwargs ) def load_annotations(self, ann_file): """Load annotation from COCO style annotation file. Args: ann_file (str): Path of annotation file. Returns: list[dict]: Annotation info from COCO api. """ self.coco = COCO(ann_file) if self.CLASSES is None: self.CLASSES = [cat['name'] for cat in self.coco.dataset['categories']] # add by hui print(f'self classes:{self.CLASSES}') # The order of returned `cat_ids` will not # change with the order of the CLASSES self.cat_ids = self.coco.get_cat_ids(cat_names=self.CLASSES) self.cat2label = {cat_id: i for i, cat_id in enumerate(self.cat_ids)} self.img_ids = self.coco.get_img_ids() data_infos = [] total_ann_ids = [] for i in self.img_ids: info = self.coco.load_imgs([i])[0] info['filename'] = info['file_name'] data_infos.append(info) ann_ids = self.coco.get_ann_ids(img_ids=[i]) total_ann_ids.extend(ann_ids) assert len(set(total_ann_ids)) == len( total_ann_ids), f"Annotation ids in '{ann_file}' are not unique!" return data_infos def _filter_imgs(self, min_size=32): valid_inds = super(CocoFmtObbDataset, self)._filter_imgs(min_size) # filter image only contain ignore_bboxes or too small bbox if self.min_gt_size: new_valid_inds, valid_img_ids = [], [] for i, img_id in enumerate(self.img_ids): valid = False for ann in self.coco.imgToAnns[img_id]: if 'ignore' in ann and ann['ignore']: continue if ann['bbox'][-1] > self.min_gt_size and ann['bbox'][-2] > self.min_gt_size: valid = True if valid: new_valid_inds.append(valid_inds[i]) valid_img_ids.append(img_id) self.img_ids = valid_img_ids valid_inds = new_valid_inds print("valid image count: ", len(valid_inds)) # add by hui return valid_inds def get_ann_info(self, idx): """Get COCO annotation by index. Args: idx (int): Index of data. Returns: dict: Annotation info of specified index. """ img_id = self.data_infos[idx]['id'] ann_ids = self.coco.get_ann_ids(img_ids=[img_id]) ann_info = self.coco.load_anns(ann_ids) return self._parse_ann_info(self.data_infos[idx], ann_info) def _parse_ann_info(self, img_info, ann_info): """Parse bbox and mask annotation. Args: ann_info (list[dict]): Annotation info of an image. with_mask (bool): Whether to parse mask annotations. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore,\ labels, masks, seg_map. "masks" are raw annotations and not \ decoded into binary masks. """ gt_bboxes = [] gt_labels = [] gt_bboxes_ignore = [] gt_masks_ann = [] true_bboxes, anns_id, ann_weight = [], [], [] # add by hui,fei for i, ann in enumerate(ann_info): if self.train_ignore_as_bg and ann.get('ignore', False): # change by hui continue x1, y1, w, h = ann['bbox'] inter_w = max(0, min(x1 + w, img_info['width']) - max(x1, 0)) inter_h = max(0, min(y1 + h, img_info['height']) - max(y1, 0)) if inter_w * inter_h == 0: continue if ann['area'] <= 0 or w < 1 or h < 1: continue if ann['category_id'] not in self.cat_ids: continue bbox = [x1, y1, x1 + w, y1 + h] if ann.get('iscrowd', False): gt_bboxes_ignore.append(bbox) else: if 'true_rbox' in ann: x1,y1,x2,y2,x3,y3,x4,y4 = ann['true_rbox'] poly = np.array((x1,y1,x2,y2,x3,y3,x4,y4), dtype=np.float32) result = poly2obb_np(poly, self.version) if result is not None: x, y, w, h, a = result true_bboxes.append([x, y, w, h, a]) else: print(f'poly is None: {poly}') filename = img_info['file_name'] print(f'image info: {filename}') continue elif 'true_bbox' in ann: x1, y1, w, h = ann['true_bbox'] poly = np.array((x1,y1,x1+w,y1,x1+w,y1+h,x1,y1+h), dtype=np.float32) result = poly2obb_np(poly, 'oc') if result is not None: x, y, w, h, a = result true_bboxes.append([x, y, w, h, a]) else: print(f'poly is None: {poly}') filename = img_info['file_name'] print(f'image info: {filename}') continue gt_bboxes.append(bbox) gt_labels.append(self.cat2label[ann['category_id']]) gt_masks_ann.append(ann.get('segmentation', None)) anns_id.append(ann['id']) if 'ann_weight' in ann: weight = ann['ann_weight'] ann_weight.append(weight) if len(true_bboxes) > 0: # add by hui true_bboxes = np.array(true_bboxes, dtype=np.float32) anns_id = np.array(anns_id, dtype=np.int64) ann_weight = np.array(ann_weight, dtype=np.float32) # add by fei if gt_bboxes: gt_bboxes = np.array(gt_bboxes, dtype=np.float32) gt_labels = np.array(gt_labels, dtype=np.int64) else: gt_bboxes = np.zeros((0, 4), dtype=np.float32) gt_labels = np.array([], dtype=np.int64) if gt_bboxes_ignore: gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32) else: gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32) seg_map = img_info['filename'].replace('jpg', 'png') ann = dict( bboxes=gt_bboxes, labels=gt_labels, anns_id=anns_id, # add by hui bboxes_ignore=gt_bboxes_ignore, masks=gt_masks_ann, seg_map=seg_map, ) if len(true_bboxes) > 0: # add by hui ann['true_bboxes'] = true_bboxes if len(ann_weight) > 0: # add by fei ann['ann_weight'] = ann_weight return ann def _proposal2json(self, results): """Convert proposal results to COCO json style.""" json_results = [] for idx in range(len(self)): img_id = self.img_ids[idx] bboxes = results[idx] for i in range(bboxes.shape[0]): data = dict() data['image_id'] = img_id data['bbox'] = self.xyxy2xywh(bboxes[i]) data['score'] = float(bboxes[i][4]) data['category_id'] = 1 json_results.append(data) return json_results def _det2json(self, results): """Convert detection results to COCO json style.""" json_results = [] for idx in range(len(self)): img_id = self.img_ids[idx] result = results[idx] for label in range(len(result)): bboxes = result[label] for i in range(bboxes.shape[0]): data = dict() data['image_id'] = img_id data['bbox'] = bboxes[i][0:5] data['score'] = float(bboxes[i][5]) data['category_id'] = self.cat_ids[label] if len(bboxes[i]) >= 7: data['ann_id'] = int(bboxes[i][6]) json_results.append(data) return json_results def results2json(self, results, outfile_prefix): """Dump the detection results to a COCO style json file. There are 3 types of results: proposals, bbox predictions, mask predictions, and they have different data types. This method will automatically recognize the type, and dump them to json files. Args: results (list[list | tuple | ndarray]): Testing results of the dataset. outfile_prefix (str): The filename prefix of the json files. If the prefix is "somepath/xxx", the json files will be named "somepath/xxx.bbox.json", "somepath/xxx.segm.json", "somepath/xxx.proposal.json". Returns: dict[str: str]: Possible keys are "bbox", "segm", "proposal", and \ values are corresponding filenames. """ result_files = dict() if isinstance(results[0], list): json_results = self._det2json(results) result_files['bbox'] = f'{outfile_prefix}.bbox.json' result_files['proposal'] = f'{outfile_prefix}.bbox.json' mmcv.dump(json_results, result_files['bbox']) elif isinstance(results[0], tuple): json_results = self._segm2json(results) result_files['bbox'] = f'{outfile_prefix}.bbox.json' result_files['proposal'] = f'{outfile_prefix}.bbox.json' result_files['segm'] = f'{outfile_prefix}.segm.json' mmcv.dump(json_results[0], result_files['bbox']) mmcv.dump(json_results[1], result_files['segm']) elif isinstance(results[0], np.ndarray): json_results = self._proposal2json(results) result_files['proposal'] = f'{outfile_prefix}.proposal.json' mmcv.dump(json_results, result_files['proposal']) else: raise TypeError('invalid type of results') return result_files def format_results(self, results, jsonfile_prefix=None, **kwargs): """Format the results to json (standard format for COCO evaluation). Args: results (list[tuple | numpy.ndarray]): Testing results of the dataset. jsonfile_prefix (str | None): The prefix of json files. It includes the file path and the prefix of filename, e.g., "a/b/prefix". If not specified, a temp file will be created. Default: None. Returns: tuple: (result_files, tmp_dir), result_files is a dict containing \ the json filepaths, tmp_dir is the temporal directory created \ for saving json files when jsonfile_prefix is not specified. """ assert isinstance(results, list), 'results must be a list' assert len(results) == len(self), ( 'The length of results is not equal to the dataset len: {} != {}'. format(len(results), len(self))) if jsonfile_prefix is None: tmp_dir = tempfile.TemporaryDirectory() jsonfile_prefix = osp.join(tmp_dir.name, 'results') else: tmp_dir = None result_files = self.results2json(results, jsonfile_prefix) return result_files, tmp_dir def evaluate(self, results, metric='bbox', logger=None, jsonfile_prefix=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=None, metric_items=None, cocofmt_kwargs={}, skip_eval=False, use_location_metric=False, location_kwargs={}, use_without_bbox_metric=False, without_bbox_kwargs={}, save_result_file=None, ): # add by hui """Evaluation in COCO protocol. Args: results (list[list | tuple]): Testing results of the dataset. metric (str | list[str]): Metrics to be evaluated. Options are 'bbox', 'segm', 'proposal', 'proposal_fast'. logger (logging.Logger | str | None): Logger used for printing related information during evaluation. Default: None. jsonfile_prefix (str | None): The prefix of json files. It includes the file path and the prefix of filename, e.g., "a/b/prefix". If not specified, a temp file will be created. Default: None. classwise (bool): Whether to evaluating the AP for each class. proposal_nums (Sequence[int]): Proposal number used for evaluating recalls, such as recall@100, recall@1000. Default: (100, 300, 1000). iou_thrs (Sequence[float], optional): IoU threshold used for evaluating recalls/mAPs. If set to a list, the average of all IoUs will also be computed. If not specified, [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95] will be used. Default: None. metric_items (list[str] | str, optional): Metric items that will be returned. If not specified, ``['AR@100', 'AR@300', 'AR@1000', 'AR_s@1000', 'AR_m@1000', 'AR_l@1000' ]`` will be used when ``metric=='proposal'``, ``['mAP', 'mAP_50', 'mAP_75', 'mAP_s', 'mAP_m', 'mAP_l']`` will be used when ``metric=='bbox' or metric=='segm'``. Returns: dict[str, float]: COCO style evaluation metric. """ nproc=4 nproc = min(nproc, os.cpu_count()) iou_thr=0.5 scale_ranges=None annotations = [self.get_ann_info(i) for i in range(len(self))] for ann in annotations: ann['bboxes'] = ann['true_bboxes'] eval_results = {} assert isinstance(iou_thr, float)
mean_ap, _ = eval_rbbox_map(
3
2023-11-20 07:50:12+00:00
16k
wangermeng2021/llm-webui
main.py
[ { "identifier": "login_huggingface", "path": "src/utils/common.py", "snippet": "def login_huggingface(token,base_model_name_dropdown):\n if base_model_name_dropdown.lower().find(\"llama\") >= 0:\n if token:\n HUGGINGFACE_HUB_TOKEN = token\n print(\"d1:\",HUGGINGFACE_HUB_T...
import pandas as pd import math import numpy as np import gc import os,requests import subprocess,threading import time import gradio as gr import os import traceback import numpy as np import glob import shutil import torch import socket from src.utils.common import login_huggingface from src.finetune.huggingface_inference import HuggingfaceInference from src.finetune.llama_cpp_inference import LlamaCppInference from src.rag.qa_with_rag import QAWithRAG from src.utils.common import read_yaml,get_first_row_from_dataset,\ get_runs_model_names_from_dir,get_hg_model_names_from_dir,get_hg_model_names_and_gguf_from_dir,validate_model_path,get_runs_models from src.utils.chat_prompts import get_model_type,get_chat_history_prompt,get_model_prompt_template from transformers.training_args import OptimizerNames from huggingface_hub import hf_hub_download from src.utils import download_model from pathlib import Path from src.finetune.qlora_trainer import QloraTrainer from src.finetune.qlora_trainer import TRAINING_STATUS from src.utils.download_huggingface_repo import download_model_wrapper,download_dataset_wrapper
13,257
global chatbot_history, stop_generation_status stop_generation_status = True chatbot_history = [] return gr.update(value=None) def show_chatbot_question1(text): global chatbot_history if not text: raise gr.Error('Enter text') chatbot_history = chatbot_history + [[text, '']] chatbot_history = chatbot_history[-5:] return chatbot_history def show_chatbot_question2(text): global chatbot_history if not text: raise gr.Error('Enter text') chatbot_history = chatbot_history + [[text, '']] chatbot_history = chatbot_history[-5:] return chatbot_history # input_txtbox.submit(add_text) def generate_btn_click1(input_txtbox): global chatbot_history, infer_model, stop_generation_status chatbot_history_np = np.asarray(chatbot_history) chatbot_history_np = chatbot_history_np.flatten() chatbot_history_list = chatbot_history_np.tolist() stop_generation_status = False model_type = "other model" if infer_model: model_type = get_model_type(infer_model.model_path) prompt = get_chat_history_prompt(chatbot_history_list, model_type) print(f"{model_type} input prompt:", prompt) answer = infer_model(prompt) else: raise gr.Error("Model is not loaded!") return chatbot_history,gr.update(value="") print(f"{model_type} output:", answer) for char in answer: if stop_generation_status: break try: chatbot_history[-1][-1] += char except: break time.sleep(0.05) # print("d2:",chatbot_history) yield chatbot_history,gr.update(value="") yield chatbot_history,gr.update(value="") def generate_btn_click2(input_txtbox): global chatbot_history, infer_model, stop_generation_status chatbot_history_np = np.asarray(chatbot_history) chatbot_history_np = chatbot_history_np.flatten() chatbot_history_list = chatbot_history_np.tolist() stop_generation_status = False running_model_name = "other model" if infer_model: if infer_model.model_path.lower().find("mistral") >= 0 and infer_model.model_path.lower().find( "instruct") >= 0: running_model_name = "mistral" prompt = get_chat_history_prompt(chatbot_history_list, running_model_name) elif infer_model.model_path.lower().find("llama") >= 0 and infer_model.model_path.lower().find("chat") >= 0: running_model_name = "llama2" prompt = get_chat_history_prompt(chatbot_history_list, running_model_name) elif infer_model.model_path.lower().find("zephyr") >= 0: running_model_name = "zephyr" prompt = get_chat_history_prompt(chatbot_history_list, running_model_name) else: prompt = ','.join(chatbot_history_list[:-2]) prompt = prompt + chatbot_history_list[-2] print(f"{running_model_name} input prompt:", prompt) answer = infer_model(prompt) else: raise gr.Error("Model is not loaded!") return chatbot_history,gr.update(value="") print(f"{running_model_name} output:", answer) for char in answer: if stop_generation_status: break try: chatbot_history[-1][-1] += char except: break time.sleep(0.05) # print("d2:",chatbot_history) yield chatbot_history,gr.update(value="") yield chatbot_history,gr.update(value="") def generate_btn_click_clear_text1(): return gr.update(value="") def generate_btn_click_clear_text2(): return gr.update(value="") input_txtbox.submit(show_chatbot_question1, inputs=[input_txtbox], outputs=[chatbot], queue=False). \ success(generate_btn_click1, inputs=[input_txtbox], outputs=[chatbot,input_txtbox]) generate_btn.click(show_chatbot_question2, inputs=[input_txtbox], outputs=[chatbot], queue=False). \ success(generate_btn_click2, inputs=[input_txtbox], outputs=[chatbot,input_txtbox]) # clear_btn.click(clear_chat_history, [], chatbot) stop_btn.click(click_stop_btn) ########################## ###################### def click_delete_text_btn(training_runs_dropdown): delete_run_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs', training_runs_dropdown) if os.path.exists(delete_run_dir): shutil.rmtree(delete_run_dir) training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs') run_names = os.listdir(training_runs_dir) run_names = [run_name for run_name in run_names if os.path.isdir(os.path.join(training_runs_dir, run_name))] run_names.sort(key=lambda f: os.path.getmtime(os.path.join(training_runs_dir, f))) sss = np.random.randint(0, 100) + 1000 iframe = f'<iframe src={TENSORBOARD_URL} style="border:none;height:{sss}px;width:100%">' return gr.update(choices=run_names, value=run_names[0] if run_names else ""), gr.update(value=iframe) def click_stop_training_btn(): global stop_training
# os.environ['HTTP_PROXY'] = 'http://127.0.0.1:8889' # os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:8889' LOCAL_HOST_IP = "0.0.0.0" TENSORBOARD_URL = "http://" + LOCAL_HOST_IP + ":6006/" INIT_DATASET_NAME = "test_python_code_instructions_5000_rows" RAG_DATA_LIST_DROPDOWN = "" TEXT_SPLITTER_DROPDOWN = "" CHUNK_SIZE_SLIDER = 0 CHUNK_OVERLAP_SLIDER = -1 SEPARATORS_TEXTBOX = "" EMBEDDING_MODEL_SOURCE_RADIO = "" HUB_EMBEDDING_MODEL_NAMES_DROPDOWN = "" LOCAL_EMBEDDING_MODEL_NAMES_DROPDOWN = "" CHAT_MODEL_SOURCE_RADIO = "" HUB_CHAT_MODEL_NAMES_DROPDOWN = "" LOCAL_CHAT_MODEL_NAMES_DROPDOWN = "" SEARCH_TOP_K_SLIDER = "" SEARCH_SCORE_THRESHOLD_SLIDER = "" training_ret_val = -1 error_msg = "" current_running_model_name = "" infer_model = None stop_generation_status = False chatbot_history=[] chatbot_height = 500 rag_chatbot_history=[] rag_stop_generation_status = False qa_with_rag = QAWithRAG() train_param_config = {} train_param_config["dataset"]={} train_param_config["model"]={} train_param_config["training"]={} model_zoo_config = {} transformer_optimizer_list = [] model_context_window = 0 init_train_file_path = None init_val_file_path = None INIT_PREFIX1 = "" INIT_PREFIX2 = "" INIT_PREFIX3 = "" INIT_PREFIX4 = "" INIT_COL1_TEXT = "" INIT_COL2_TEXT = "" INIT_COL3_TEXT = "" INIT_COL4_TEXT = "" col_names = [] DATASET_FIRST_ROW = None local_model_list = "" local_model_root_dir = "" base_model_names = [] training_base_model_names = [] embedding_model_names = [] base_model_context_window = [] local_dataset_list = [] local_dataset_root_dir = "" def get_local_embedding_model_list(): local_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rag", "embedding_models") local_model_root_files = os.listdir(local_model_root_dir) local_model_list = [] for model_dir in local_model_root_files: if os.path.isdir(os.path.join(local_model_root_dir, model_dir)): local_model_list.append(model_dir) return local_model_list,local_model_root_dir def get_local_model_list(): local_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models") local_model_root_files = os.listdir(local_model_root_dir) local_model_list = [] for model_dir in local_model_root_files: if os.path.isdir(os.path.join(local_model_root_dir, model_dir)): local_model_list.append(model_dir) return local_model_list,local_model_root_dir def get_local_dataset_list(): local_dataset_list = [] local_dataset_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "datasets") matched_dataset_file_path_list = glob.glob(os.path.join(local_dataset_root_dir,"**","dataset_infos.json"),recursive=False) for matched_file_path in matched_dataset_file_path_list: matched_pos1 = matched_file_path.rfind("datasets") matched_pos2 = matched_file_path.rfind("dataset_infos.json") local_dataset_list.append(matched_file_path[matched_pos1 + 9:matched_pos2-1]) matched_dataset_file_path_list = glob.glob(os.path.join(local_dataset_root_dir,"**","dataset_dict.json"),recursive=False) for matched_file_path in matched_dataset_file_path_list: matched_pos1 = matched_file_path.rfind("datasets") matched_pos2 = matched_file_path.rfind("dataset_dict.json") local_dataset_list.append(matched_file_path[matched_pos1 + 9:matched_pos2-1]) return local_dataset_list,local_dataset_root_dir def start_tensorboard_server(): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((LOCAL_HOST_IP, 6006)) s.close() except Exception as e: tensorboard_cmd = f"tensorboard --logdir {os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs')} --reload_multifile True" tensorboard_proc = subprocess.Popen(tensorboard_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, close_fds=True) # bufsize=0, close_fds=True def init(): global config_dict,transformer_optimizer_list,model_context_window,init_train_file_path,init_val_file_path global INIT_PREFIX1,INIT_COL1_TEXT,INIT_PREFIX2,INIT_COL2_TEXT,INIT_PREFIX3,INIT_COL3_TEXT,INIT_PREFIX4,INIT_COL4_TEXT,col_names,DATASET_FIRST_ROW global local_model_list,local_model_root_dir global base_model_names,base_model_context_window,embedding_model_names,training_base_model_names global local_dataset_list, local_dataset_root_dir start_tensorboard_server() model_zoo_config = read_yaml(os.path.join(os.path.dirname(os.path.abspath(__file__)),"config","model_zoo.yaml")) transformer_optimizer_list = list(vars(OptimizerNames)["_value2member_map_"].keys()) #get dynamic context window from selected model model_context_window = [2048,1024,512] init_train_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "datasets", INIT_DATASET_NAME) DATASET_FIRST_ROW,split_list = get_first_row_from_dataset(init_train_file_path) col_names = list(DATASET_FIRST_ROW) col_names.insert(0,"") INIT_PREFIX1 = "<s>[INST] " INIT_PREFIX2 = "here are the inputs " INIT_PREFIX3 = " [/INST]" INIT_PREFIX4 = "</s>" INIT_COL1_TEXT = str(DATASET_FIRST_ROW[col_names[1]]) INIT_COL2_TEXT = str(DATASET_FIRST_ROW[col_names[2]]) INIT_COL3_TEXT = str(DATASET_FIRST_ROW[col_names[3]]) INIT_COL4_TEXT = "" local_model_list,local_model_root_dir = get_local_model_list() base_model_names = [model_name for model_name in model_zoo_config["model_list"]] training_base_model_names = [model_name for model_name in base_model_names if not model_name.endswith(".gguf")] # base_model_context_window = [model_name[1] for model_name in model_zoo_config["model_list"]] embedding_model_names = [model_name for model_name in model_zoo_config["embedding_model_list"]] local_dataset_list, local_dataset_root_dir = get_local_dataset_list() with gr.Blocks(title="FINETUNE",css="#vertical_center_align_markdown { position:absolute; top:30%;background-color:white;} .white_background {background-color: #ffffff} .none_border {border: none;border-collapse:collapse;}") as demo: init() local_model_root_dir_textbox = gr.Textbox(label="", value=local_model_root_dir, visible=False) local_dataset_root_dir_textbox = gr.Textbox(label="",value=local_dataset_root_dir, visible=False) local_embedding_model_root_dir_textbox = gr.Textbox(label="", value=os.path.join(os.path.dirname(os.path.abspath(__file__)), "rag", "embedding_models"), visible=False) local_chat_model_root_dir_textbox = gr.Textbox(label="", value=local_model_root_dir, visible=False) local_home_chat_model_root_dir_textbox = gr.Textbox(label="", value=local_model_root_dir, visible=False) session_state = gr.State(value={}) # html = gr.HTML("<p align='center';>llm-web-ui</p>",elem_id="header") with gr.Tab("Home"): with gr.Row(): # with gr.Column(scale=4, min_width=1): with gr.Group(): gr.Markdown("## &nbsp;ChatBot", elem_classes="white_background") with gr.Group(): gr.Markdown("### &nbsp;&nbsp;&nbsp;&nbsp;Chat Model", elem_classes="white_background") local_home_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models") runs_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runs") local_home_chat_model_names = get_hg_model_names_and_gguf_from_dir(local_home_chat_model_dir, runs_model_root_dir) home_chat_model_source_radio_choices = ["Download From Huggingface Hub", f"From Local Dir(hg format:{local_home_chat_model_dir})"] home_chat_model_source_radio = gr.Radio(home_chat_model_source_radio_choices, label="Chat Model source", show_label=False, value=home_chat_model_source_radio_choices[0], interactive=True) with gr.Row(): hub_home_chat_model_names_dropdown = gr.Dropdown(base_model_names, label=f"Chat Model", show_label=False, allow_custom_value=True, value=base_model_names[ 0] if base_model_names else None, interactive=True, scale=4, min_width=1) local_home_chat_model_names_dropdown = gr.Dropdown(local_home_chat_model_names, label=f"Chat Model", show_label=False, value=local_home_chat_model_names[ 0] if local_home_chat_model_names else None, interactive=True, scale=4, min_width=1, visible=False) download_hub_home_chat_model_names_btn = gr.Button("Download", scale=1) stop_download_hub_home_chat_model_names_btn = gr.Button("Stop", scale=1, visible=False) refresh_local_home_chat_model_names_btn = gr.Button("Refresh", scale=1, visible=False) load_home_chat_model_btn = gr.Button("Load Model", scale=1, visible=True) using_4bit_quantization_checkbox = gr.Checkbox(True, label="Using 4-bit quantization", interactive=True, visible=True, info="Less memory but slower", scale=1 ) if validate_model_path(base_model_names[0])[0]: download_hub_home_chat_model_status_markdown = gr.Markdown( '<span style="color:green">&nbsp;&nbsp;&nbsp;&nbsp;This model has already been downloaded to local,click load model to run.</span>') else: download_hub_home_chat_model_status_markdown = gr.Markdown( '<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;This model has not been downloaded.</span>') # home_chat_model_running_status_markdown = gr.Markdown( # '<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;This model has not been downloaded.</span>') with gr.Row(): chatbot = gr.Chatbot(value=[],bubble_full_width=False,rtl=False,layout="panel",height=chatbot_height, avatar_images=((os.path.join(os.path.abspath(''),"pics", "user1.png")), (os.path.join(os.path.abspath(''),"pics", "bot4.png"))), ) with gr.Row(): input_txtbox = gr.Textbox( show_label=False,autofocus=True, placeholder="Enter text and press enter",scale=3 ) generate_btn = gr.Button("Generate", scale=1) stop_btn = gr.Button("Stop", scale=1) # clear_btn = gr.Button("Clear",scale=1) with gr.Tab("Fine-Tuning"): with gr.Tabs() as tensorboard_tab: with gr.TabItem("Training", id=0): with gr.Row(): with gr.Column(scale=1, min_width=1): with gr.Group(): gr.Markdown("## &nbsp;1.Training", elem_classes="white_background") with gr.Group(): gr.Markdown("### &nbsp;1).Model", elem_classes="white_background") with gr.Group(): # gr.Markdown("<br> &nbsp;&nbsp;&nbsp; Base Model") base_model_source_radio_choices = ["Download From Huggingface Hub", f"From Local Dir(hg format:{local_model_root_dir})"] base_model_source_radio = gr.Radio(base_model_source_radio_choices, label="Base Model", value=base_model_source_radio_choices[0], interactive=True) with gr.Row(elem_classes="white_background"): base_model_name_dropdown = gr.Dropdown(training_base_model_names, label="Model Name", value=training_base_model_names[0] if training_base_model_names else None, interactive=True, visible=True, scale=5, allow_custom_value=True) download_local_model_btn = gr.Button("Download", scale=1, visible=True) stop_download_local_model_btn = gr.Button("Stop", scale=1, visible=False) # model_download_status = gr.Markdown("<div id='vertical_center_align_markdown'><p style='text-align: center;'>Not downloaded</p></div>", elem_classes="white_background",scale=1,full_width=True,visible=False) if validate_model_path(training_base_model_names[0])[0]: download_model_status_markdown = gr.Markdown('<span style="color:green">&nbsp;&nbsp;&nbsp;&nbsp;This model has already been downloaded to local.</span>') else: download_model_status_markdown = gr.Markdown('<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;This model has not been downloaded.</span>') with gr.Row(): # local_home_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models") # runs_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runs") # local_model_list = get_hg_model_names_and_gguf_from_dir(local_home_chat_model_dir,runs_model_root_dir) local_model_list = get_hg_model_names_from_dir(os.path.dirname(os.path.abspath(__file__)), "models") local_model_dropdown = gr.Dropdown(local_model_list, label="Local Model", info="", value=local_model_list[0] if len(local_model_list) > 0 else None, interactive=True, elem_classes="white_background", scale=5, visible=False) refresh_local_model_list_btn = gr.Button("Refresh", scale=1, visible=False) fine_tuning_type_dropdown = gr.Dropdown(["QLoRA", "LoRA"], label="Fine-Tuning Type", info="", value="QLoRA", interactive=True) with gr.Group(): with gr.Row(elem_classes="white_background"): # gr.Markdown("### &nbsp;&nbsp;&nbsp; LoRA Config", elem_classes="white_background") lora_r_list = [str(ri) for ri in range(8, 65, 8)] lora_r_slider = gr.Slider(8, 64, value=8, step=8, label="lora_r", interactive=True) # lora_r_dropdown = gr.Dropdown(lora_r_list,label="lora_r", value=lora_r_list[0],interactive=True,allow_custom_value=True) lora_alpha_slider = gr.Slider(8, 96, value=32, step=8, label="lora_alpha", interactive=True) # lora_alpha_list = [str(ri) for ri in range(8, 97, 8)] # lora_alpha_dropdown = gr.Dropdown(lora_alpha_list,label="lora_alpha", value=lora_alpha_list[3],interactive=True,allow_custom_value=True) with gr.Row(elem_classes="white_background"): lora_dropout_slider = gr.Slider(0, 1, value=0.05, step=0.01, label="lora_dropout", interactive=True) lora_bias_dropdown = gr.Dropdown(["none", "all", "lora_only"], label="lora_bias", info="", value="none", interactive=True) with gr.Group(): gr.Markdown("### &nbsp;2).Dataset",elem_classes="white_background") dataset_source_radio_choices = ["Download From Huggingface Hub", f"From Local HG Dataset In {local_dataset_root_dir})"] dataset_source_radio = gr.Radio(dataset_source_radio_choices, label="Dataset Source", value=dataset_source_radio_choices[1], interactive=True) with gr.Row(equal_height=True): hg_dataset_path_textbox = gr.Textbox(label="Dataset Name:",elem_classes="none_border",visible=False, interactive=True, scale=4, value="iamtarun/python_code_instructions_18k_alpaca") download_local_dataset_btn = gr.Button("Download", scale=1, visible=False) stop_download_local_dataset_btn = gr.Button("Stop", scale=1, visible=False) download_dataset_status_markdown = gr.Markdown('') with gr.Row(): hg_train_dataset_dropdown = gr.Dropdown(["train"], label="Train set", info="", interactive=False,visible=False, elem_classes="white_background", scale=1,value="train") hg_val_dataset_dropdown = gr.Dropdown([], label="Val set", info="", interactive=False,visible=False, elem_classes="white_background", scale=1) with gr.Row(): local_dataset_list.pop( local_dataset_list.index(INIT_DATASET_NAME)) local_dataset_list.insert(0, INIT_DATASET_NAME) local_train_path_dataset_dropdown = gr.Dropdown(local_dataset_list, label="Train Dataset", info="", value=local_dataset_list[0] if len(local_dataset_list)>0 else None, interactive=True, elem_classes="white_background", scale=5, visible=True) refresh_local_train_path_dataset_list_btn = gr.Button("Refresh", scale=1, visible=True) with gr.Row(): local_train_dataset_dropdown = gr.Dropdown(["train"], label="Train set", info="", interactive=True, elem_classes="white_background", scale=1,value="train",visible=True) local_val_dataset_dropdown = gr.Dropdown([], label="Val set", info="", interactive=True, elem_classes="white_background", scale=1,visible=True) with gr.Group(elem_classes="white_background"): # gr.Markdown("<h4><br> &nbsp;&nbsp;Prompt Template: (Prefix1 + ColumnName1 + Prefix2 + ColumnName2)</h4>",elem_classes="white_background") gr.Markdown("<br> &nbsp;&nbsp;&nbsp;&nbsp;**Prompt Template: (Prefix1+ColumnName1+Prefix2+ColumnName2+Prefix3+ColumnName3+Prefix4+ColumnName4)**",elem_classes="white_background") gr.Markdown( "<span> &nbsp;&nbsp;&nbsp;&nbsp;**Note**:&nbsp;&nbsp;Llama2/Mistral Chat Template:<s\>[INST] instruction+input [/INST] output</s\> </span>",elem_classes="white_background") # using_llama2_chat_template_checkbox = gr.Checkbox(True, label="Using Llama2/Mistral chat template",interactive=True,visible=False) with gr.Row(elem_classes="white_background"): # prompt_template prefix1_textbox = gr.Textbox(label="Prefix1:",value=INIT_PREFIX1,lines=2,interactive=True,elem_classes="white_background") datatset_col1_dropdown = gr.Dropdown(col_names, label="ColumnName1:", info="",value=col_names[1],interactive=True,elem_classes="white_background") prefix2_textbox = gr.Textbox(label="Prefix2:",value=INIT_PREFIX2,lines=2,interactive=True,elem_classes="white_background") datatset_col2_dropdown = gr.Dropdown(col_names, label="ColumnName2:", info="",value=col_names[2],interactive=True,elem_classes="white_background") with gr.Row(elem_classes="white_background"): prefix3_textbox = gr.Textbox(label="Prefix3:",value=INIT_PREFIX3,lines=2,interactive=True,elem_classes="white_background") datatset_col3_dropdown = gr.Dropdown(col_names, label="ColumnName3:", info="",value=col_names[3],interactive=True,elem_classes="white_background") prefix4_textbox = gr.Textbox(label="Prefix4:",value=INIT_PREFIX4,lines=2,interactive=True,elem_classes="white_background") datatset_col4_dropdown = gr.Dropdown(col_names, label="ColumnName4:", info="",value=col_names[0],interactive=True,elem_classes="white_background") # print("") prompt_sample = INIT_PREFIX1 + INIT_COL1_TEXT + INIT_PREFIX2 + INIT_COL2_TEXT + INIT_PREFIX3 + INIT_COL3_TEXT + INIT_PREFIX4 + INIT_COL4_TEXT prompt_sample_textbox = gr.Textbox(label="Prompt Sample:",interactive=False,value=prompt_sample,lines=4) max_length_dropdown = gr.Dropdown(["Model Max Length"]+model_context_window, label="Max Length",value="Model Max Length", interactive=True,allow_custom_value=True) with gr.Group(): gr.Markdown("### &nbsp;3).Training Arguments",elem_classes="white_background") with gr.Row(elem_classes="white_background"): epochs_slider = gr.Slider(1, 100, value=10, step=1, label="Epochs", interactive=True) # epochs_dropdown = gr.Dropdown([1]+[bi for bi in range(10,101,10)], label="Epochs",value=1, interactive=True,allow_custom_value=True) batch_size_list = [1,2,3]+[bi for bi in range(4,32+1,4)] batch_size_slider = gr.Slider(1, 100, value=1, step=1, label="Batch Size", interactive=True) # batch_size_dropdown = gr.Dropdown(batch_size_list,label="Batch Size", info="",value=batch_size_list[0],interactive=True,allow_custom_value=True) # learning_rate_textbox = gr.Textbox(label="Learning Rate", value=2e-4,interactive=True) with gr.Row(elem_classes="white_background"): learning_rate_slider = gr.Slider(0, 0.01, value=2e-4, step=0.0001, label="Learning Rate", interactive=True) warmup_steps_slider = gr.Slider(0, 400, value=100, step=10, label="Warmup Steps", interactive=True) with gr.Row(elem_classes="white_background"): optimizer_dropdown = gr.Dropdown(transformer_optimizer_list, label="Optimizer", info="", value=transformer_optimizer_list[1], interactive=True) lr_scheduler_list = ["linear","cosine","cosine_with_hard_restarts","polynomial_decay","constant","constant_with_warmup","inverse_sqrt","reduce_on_plateau"] lr_scheduler_type_dropdown = gr.Dropdown(lr_scheduler_list, label="LR Scheduler Type", info="", value=lr_scheduler_list[0], interactive=True) with gr.Row(elem_classes="white_background"): early_stopping_patience_slider = gr.Slider(0, 50+1, value=0, step=5, label="Early Stopping Patience", interactive=True) gradient_accumulation_steps_slider = gr.Slider(1, 50, value=1, step=1, label="Gradient Accumulation Steps") with gr.Row(elem_classes="white_background"): eval_steps_slider = gr.Slider(0, 1000, value=100, step=100, label="eval_steps", interactive=True) gradient_checkpointing_checkbox = gr.Checkbox(True,label="Gradient Checkpointing",interactive=True) train_btn = gr.Button("Start Training") with gr.Column(scale=1, min_width=1): with gr.Group(): gr.Markdown("## &nbsp;2.Test",elem_classes="white_background") training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs') run_names = os.listdir(training_runs_dir) run_names.sort(key=lambda file:os.path.getmtime(os.path.join(training_runs_dir,file))) runs_output_model = [] for run_name in run_names: run_name_dir = os.path.join(training_runs_dir,run_name) run_output_model = os.path.join(run_name_dir,"output_model") if os.path.exists(run_output_model): run_output_model_names = os.listdir(run_output_model) for run_output_model_name in run_output_model_names: if run_output_model_name.find("merged_")>=0: runs_output_model.append(os.path.join(run_name,"output_model",run_output_model_name, "ori")) runs_output_model = runs_output_model[::-1] runs_output_model_dropdown = gr.Dropdown(runs_output_model, label="runs_output_model", value=runs_output_model[0] if runs_output_model else None, interactive=True) gr.Markdown("") gr.Markdown( "<span> &nbsp;&nbsp;&nbsp;&nbsp;**Note**:&nbsp;&nbsp;Llama2/Mistral Chat Template:<s\>[INST] instruction+input [/INST] output</s\> </span>", elem_classes="white_background") with gr.Row(): test_input_textbox = gr.Textbox(label="Input:", interactive=True, value="", lines=4, scale=4) generate_text_btn = gr.Button("Generate",scale=1) finetune_test_using_4bit_quantization_checkbox = gr.Checkbox(True, label="Using 4-bit quantization", interactive=True, visible=True, info="Less memory but slower", scale=1 ) # test_prompt = gr.Textbox(label="Prompt:", interactive=False, lines=2, scale=1) test_output = gr.Textbox(label="Output:", interactive=False,lines=4, scale=1) # def change_test_input_textbox(test_prefix1_textbox,test_input_textbox,test_prefix2_textbox): # return gr.update(value=test_prefix1_textbox+test_input_textbox+test_prefix2_textbox) # test_input_textbox.change(change_test_input_textbox,[test_prefix1_textbox,test_input_textbox,test_prefix2_textbox],test_prompt) with gr.Group(): gr.Markdown("## &nbsp;3.Quantization",elem_classes="white_background") with gr.Row(): quantization_type_list = ["gguf"] quantization_type_dropdown = gr.Dropdown(quantization_type_list, label="Quantization Type",value=quantization_type_list[0], interactive=True,scale=3) local_quantization_dataset_dropdown = gr.Dropdown(local_dataset_list, label="Dataset for quantization", value=local_dataset_list[0] if len( local_dataset_list) > 0 else None, interactive=True, elem_classes="white_background", scale=7, visible=False) refresh_local_quantization_dataset_btn = gr.Button("Refresh", scale=2, visible=False) def click_refresh_local_quantization_dataset_btn(): local_dataset_list, _ = get_local_dataset_list() return gr.update(choices=local_dataset_list, value=local_dataset_list[0] if len(local_dataset_list) > 0 else "") refresh_local_quantization_dataset_btn.click(click_refresh_local_quantization_dataset_btn,[],local_quantization_dataset_dropdown) with gr.Row(): training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs') run_names = os.listdir(training_runs_dir) run_names.sort(key=lambda file: os.path.getmtime(os.path.join(training_runs_dir, file))) runs_output_model = [] for run_name in run_names: run_name_dir = os.path.join(training_runs_dir, run_name) run_output_model = os.path.join(run_name_dir, "output_model") if os.path.exists(run_output_model): run_output_model_names = os.listdir(run_output_model) for run_output_model_name in run_output_model_names: if run_output_model_name.find("merged_") >= 0: runs_output_model.append( os.path.join(run_name, "output_model", run_output_model_name, "ori")) runs_output_model = runs_output_model[::-1] quantization_runs_output_model_dropdown = gr.Dropdown(runs_output_model, label="runs_output_model", value=runs_output_model[ 0] if runs_output_model else None, interactive=True, scale=6) quantize_btn = gr.Button("Quantize", scale=1,visible=False) if runs_output_model: model_name = runs_output_model[0].split(os.sep)[-2].split('_')[-1] quantized_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs', os.sep.join(runs_output_model[0].split(os.sep)[0:-1]), "quantized_" + quantization_type_list[0] + "_" + model_name) if not os.path.exists(quantized_model_dir): os.makedirs(quantized_model_dir) quantization_logging_markdown = gr.Markdown("") gguf_quantization_markdown0 = gr.Markdown("### &nbsp;&nbsp;&nbsp;&nbsp;GGUF Quantization Instruction:", elem_classes="white_background", visible=True) gguf_quantization_markdown1 = gr.Markdown('''&nbsp;&nbsp;&nbsp;&nbsp;1.Follow the instructions in the llama.cpp to generate a GGUF:[https://github.com/ggerganov/llama.cpp#prepare-data--run](https://github.com/ggerganov/llama.cpp#prepare-data--run),<span style="color:red">&nbsp;&nbsp;Q4_K_M is recommend</span>''',visible=True) if runs_output_model: gguf_quantization_markdown2 = gr.Markdown(f"&nbsp;&nbsp;&nbsp;&nbsp;2.Convert {runs_output_model[0]} to gguf model",visible=True) else: gguf_quantization_markdown2 = gr.Markdown( f"", visible=True) gguf_quantization_markdown3 = gr.Markdown(f"&nbsp;&nbsp;&nbsp;&nbsp;3.Deploy gguf model", visible=False) else: quantization_logging_markdown = gr.Markdown("") gguf_quantization_markdown0 = gr.Markdown("### &nbsp;&nbsp;&nbsp;&nbsp;GGUF Quantization Instruction:", elem_classes="white_background", visible=True) gguf_quantization_markdown1 = gr.Markdown('''''',visible=True) gguf_quantization_markdown2 = gr.Markdown(f"",visible=True) gguf_quantization_markdown3 = gr.Markdown(f"", visible=True) with gr.Group(visible=False): gr.Markdown("## &nbsp;4.Deploy",elem_classes="white_background") with gr.Row(): deployment_framework_dropdown = gr.Dropdown(["TGI","llama-cpp-python"], label="Deployment Framework",value="TGI", interactive=True) with gr.Row(): training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs') run_names = os.listdir(training_runs_dir) run_names.sort(key=lambda file: os.path.getmtime(os.path.join(training_runs_dir, file))) # ori_model_runs_output_model = [] tgi_model_format_runs_output_model = [] gguf_model_format_runs_output_model = [] for run_name in run_names: run_name_dir = os.path.join(training_runs_dir, run_name) run_output_model = os.path.join(run_name_dir, "output_model") if os.path.exists(run_output_model): run_output_model_names = os.listdir(run_output_model) for run_output_model_name in run_output_model_names: model_bin_path = os.path.exists( os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs', run_name, "output_model", run_output_model_name, "ori", "pytorch_model.bin")) if run_output_model_name.find("merged_") >= 0 and model_bin_path: tgi_model_format_runs_output_model.append( os.path.join(run_name, "output_model", run_output_model_name, "ori")) gptq_model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs',run_name, "output_model", run_output_model_name, "quantized_gptq_"+run_output_model_name.split('_')[-1], "pytorch_model.bin") if os.path.exists(gptq_model_path): tgi_model_format_runs_output_model.append(os.path.join(run_name, "output_model", run_output_model_name, "quantized_gptq_"+run_output_model_name.split('_')[-1])) gguf_model_dir = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'runs', run_name, "output_model", run_output_model_name, "quantized_gguf_" + run_output_model_name.split('_')[-1]) if os.path.exists(gguf_model_dir): gguf_model_names = os.listdir(gguf_model_dir) for gguf_model_name in gguf_model_names: if gguf_model_name.split('.')[-1] == "gguf": gguf_model_format_runs_output_model.append( os.path.join(run_name, "output_model", run_output_model_name, "quantized_gguf_" + run_output_model_name.split('_')[-1], gguf_model_name)) tgi_model_format_runs_output_model = tgi_model_format_runs_output_model[::-1] gguf_model_format_runs_output_model = gguf_model_format_runs_output_model[::-1] deployment_runs_output_model_dropdown = gr.Dropdown(tgi_model_format_runs_output_model, label="runs_output_model", value=tgi_model_format_runs_output_model[ 0] if tgi_model_format_runs_output_model else None, interactive=True,scale=6) refresh_deployment_runs_output_model_btn = gr.Button("Refresh", scale=1, visible=True) if tgi_model_format_runs_output_model: model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs', os.path.dirname(tgi_model_format_runs_output_model[0])) model_name = os.path.basename(tgi_model_format_runs_output_model[0]) if model_name.rfind("quantized_gptq_") >= 0: run_server_value = f'''docker run --gpus all --shm-size 1g -p 8080:80 -v {model_dir}:/data ghcr.io/huggingface/text-generation-inference:latest --model-id /data/{model_name} --quantize gptq''' else: run_server_value = f'''docker run --gpus all --shm-size 1g -p 8080:80 -v {model_dir}:/data ghcr.io/huggingface/text-generation-inference:latest --model-id /data/{model_name}''' run_server_script_textbox = gr.Textbox(label="Run Server:", interactive=False,lines=2, scale=1,value=run_server_value) run_client_value = '''Command-Line Interface(CLI):\ncurl 127.0.0.1:8080/generate -X POST -d '{"inputs":"What is Deep Learning?","parameters":{"max_new_tokens":20}}' -H 'Content-Type: application/json'\n\nPython:\nfrom huggingface_hub import InferenceClient \nclient = InferenceClient(model="http://127.0.0.1:8080")\noutput = client.text_generation(prompt="What is Deep Learning?",max_new_tokens=512) ''' run_client_script_textbox = gr.Textbox(label="Run Client:", interactive=False, lines=6,scale=1,value=run_client_value) else: run_server_script_textbox = gr.Textbox(label="Run Server:", interactive=False,lines=2, scale=1,value="") run_client_script_textbox = gr.Textbox(label="Run Client:", interactive=False, lines=6, scale=1, value="") # deploy_llm_code = gr.Code(code_str, language="shell", lines=5, label="Install Requirements:") install_requirements_value = ''' ### &nbsp;&nbsp; 1.install docker ### &nbsp;&nbsp; 2.Install NVIDIA Container Toolkit <h4> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.1 Configure the repository: </h4> <p> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \ && curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \ sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \ sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list \ && \ sudo apt-get update </p> <h4> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.2 Install the NVIDIA Container Toolkit packages: </h4> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sudo apt-get install -y nvidia-container-toolkit </p> ''' with gr.Accordion("Install Requirements",open=False) as install_requirements_accordion: install_requirements_markdown = gr.Markdown(install_requirements_value) run_llama_cpp_python_code = gr.Code("", language="python", lines=10, label="run_model_using_llama_cpp_python.py",visible=False) # run_script_textbox = gr.Textbox(label="Install Requirements:", interactive=False, scale=1,value=install_requirements_value) #dependencies with gr.TabItem("Tensorboard", id=1) as fdddd: # training_log_markdown = gr.Markdown('',every=mytestfun) with gr.Row(): # training_log_textbox = gr.Textbox(label="logging:",value="", interactive=True, lines=2, scale=1) with gr.Group(): training_log_markdown = gr.Markdown('') stop_training_btn = gr.Button("Stop Training") training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs') run_names = os.listdir(training_runs_dir) run_names = [run_name for run_name in run_names if os.path.isdir(os.path.join(training_runs_dir,run_name))] run_names.sort(key=lambda f: os.path.getmtime(os.path.join(training_runs_dir, f))) # print("dddddddd:",run_names) with gr.Group(): # with gr.Row(): training_runs_dropdown = gr.Dropdown(run_names, label="Training Runs",value=run_names[0] if run_names else None, interactive=True, scale=1) delete_text_btn = gr.Button("Delete Run", scale=1) iframe = f'<iframe src={TENSORBOARD_URL} style="border:none;height:1024px;width:100%">' tensorboard_html = gr.HTML(iframe) with gr.Tab("RAG"): with gr.Row(): with gr.Column(scale=4, min_width=1): with gr.Group(): gr.Markdown("## &nbsp;ChatBot", elem_classes="white_background") rag_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'rag', 'data') matched_file_list = [] supported_doc_type = ["*.pdf","*.txt","*.docx"] for doc_type in supported_doc_type: matched_file_list += glob.glob(os.path.join(rag_data_dir, doc_type), recursive=False) matched_file_list.sort(key=lambda file: os.path.getmtime(file),reverse=True) matched_file_name_list = [] for matched_file in matched_file_list: matched_file_name_list.append(os.path.basename(matched_file)) # chat_data_source_radio_choices = ["Chat With Document", # f"Chat With Image"] gr.Markdown("### &nbsp;Chat With Document", elem_classes="white_background") # chat_data_source_radio = gr.Radio(chat_data_source_radio_choices, # label="", # value=chat_data_source_radio_choices[0], # interactive=True) with gr.Row(): rag_data_list_dropdown = gr.Dropdown(matched_file_name_list, label=f"Local Documents In {rag_data_dir}", value=matched_file_name_list[0] if matched_file_name_list else None, interactive=True,scale=4, min_width=1) refresh_rag_data_list_btn = gr.Button("Refresh", scale=1, min_width=1) # if not current_running_model_name: # model_running_status_markdown = gr.Markdown(f"<span style='color:red'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;No modelis running!</span>") # else: # model_running_status_markdown = gr.Markdown(f"<span style='color:green'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Model is runing:{current_running_model_name}.</span>") def click_refresh_rag_data_list_btn(): rag_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'rag', 'data') matched_file_list = [] supported_doc_type = ["*.pdf", "*.txt", "*.docx"] for doc_type in supported_doc_type: matched_file_list += glob.glob(os.path.join(rag_data_dir, doc_type), recursive=False) matched_file_list.sort(key=lambda file: os.path.getmtime(file), reverse=True) matched_file_name_list = [] for matched_file in matched_file_list: matched_file_name_list.append(os.path.basename(matched_file)) return gr.update(choices=matched_file_name_list,value=matched_file_name_list[0] if matched_file_name_list else None) refresh_rag_data_list_btn.click(click_refresh_rag_data_list_btn,[],rag_data_list_dropdown) # def update_model_running_status(): # return gr.update(value=f"<span style='color:red'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{current_running_model_name} is runing!.</span>") # # load_model_btn.click(click_load_model_btn,model_list_dropdown,[model_list_dropdown]).success(update_model_running_status,[],model_running_status_markdown) with gr.Row(): rag_chatbot = gr.Chatbot(value=[],bubble_full_width=False,rtl=False,layout="panel",height=chatbot_height, avatar_images=((os.path.join(os.path.abspath(''),"pics", "user1.png")), (os.path.join(os.path.abspath(''),"pics", "bot4.png"))), ) with gr.Row(): rag_input_txtbox = gr.Textbox( show_label=False,autofocus=True, placeholder="Enter text and press enter",scale=6) rag_generate_btn = gr.Button("Generate", scale=1) rag_stop_btn = gr.Button("Stop", scale=1) # rag_clear_btn = gr.Button("Clear", scale=1) rag_model_running_status_markdown = gr.Markdown( f"### &nbsp;&nbsp;Retrieved Document Chunks",visible=True) # retrieved_document_chunks_markdown = gr.Markdown( # f"### &nbsp;&nbsp;Retrieved Document Chunks",visible=True) retrieved_document_chunks_dataframe = gr.Dataframe( headers=["ID", "Chunk"], datatype=["str", "str"], show_label=False, value=None ) with gr.Column(scale=4, min_width=1): with gr.Group(): gr.Markdown("## &nbsp;Setting", elem_classes="white_background") with gr.Group(): with gr.Group(): gr.Markdown("### &nbsp;&nbsp;1.Chunking", elem_classes="white_background") with gr.Row(): text_splitter_dropdown = gr.Dropdown(["RecursiveCharacterTextSplitter"], label=f"Text Splitter", value="RecursiveCharacterTextSplitter", interactive=True, scale=1, min_width=1) with gr.Row(): chunk_size_slider = gr.Slider(32, 1024, value=256, step=32, label="Chunk Size", interactive=True, scale=1) chunk_overlap_slider = gr.Slider(0, 500, value=20, step=10, label="Chunk Overlap", interactive=True) Separators_textbox = gr.Textbox(label="Separators", value='''["\n\n", "\n", ".", " ", ""]''', interactive=True,visible=False) with gr.Group(): gr.Markdown("### &nbsp;&nbsp;2.Vector Store Retriever", elem_classes="white_background") # local_embedding_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"rag","embedding_models") local_embedding_model_names = get_hg_model_names_from_dir(local_embedding_model_dir,"embedding_models") embedding_model_source_radio_choices = ["Download From Huggingface Hub", f"From Local Dir(hg format:{local_embedding_model_dir})"] embedding_model_source_radio = gr.Radio(embedding_model_source_radio_choices, label="Embedding Model Source", value=embedding_model_source_radio_choices[0], interactive=True) with gr.Row(): hub_embedding_model_names_dropdown = gr.Dropdown(embedding_model_names, label=f"",show_label=False, value=embedding_model_names[0] if embedding_model_names else None, interactive=True, scale=4, min_width=1) download_hub_embedding_model_names_btn = gr.Button("Download", scale=1) stop_download_hub_embedding_model_names_btn = gr.Button("Stop", scale=1, visible=False) local_embedding_model_names_dropdown = gr.Dropdown(local_embedding_model_names, label=f"Embedding Model",show_label=False, value=local_embedding_model_names[0] if local_embedding_model_names else None, interactive=True, scale=4, min_width=1,visible=False) refresh_local_embedding_model_names_btn = gr.Button("Refresh", scale=1,visible=False) # model_config_path1 = os.path.join(local_embedding_model_dir, # embedding_model_names[0], "pytorch_model.bin") # model_config_path2 = os.path.join(local_embedding_model_dir, # embedding_model_names[0], "model.safetensors") model_config_path = os.path.join(local_embedding_model_dir, embedding_model_names[0], "config.json") if os.path.exists(model_config_path): download_hub_embedding_model_status_markdown = gr.Markdown( '<span style="color:green">&nbsp;&nbsp;&nbsp;&nbsp;This model has already been downloaded to local.</span>') else: download_hub_embedding_model_status_markdown = gr.Markdown( '<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;This model has not been downloaded.</span>') with gr.Row(): search_top_k_slider = gr.Slider(1, 10, value=3, step=1, label="Search Top K", interactive=True) search_score_threshold_slider = gr.Slider(0, 1, value=0.5, step=0.1, label="Search Score Threshold",interactive=True) with gr.Group(): gr.Markdown("### &nbsp;&nbsp;3.Chat Model", elem_classes="white_background") local_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),"models") runs_model_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "runs") # local_chat_model_names = get_hg_model_names_from_dir(local_chat_model_dir) local_chat_model_names = get_hg_model_names_and_gguf_from_dir(local_chat_model_dir,runs_model_root_dir) chat_model_source_radio_choices = ["Download From Huggingface Hub", f"From Local Dir(hg format:{local_chat_model_dir})"] chat_model_source_radio = gr.Radio(chat_model_source_radio_choices, label="Chat Model source",show_label=False, value=chat_model_source_radio_choices[0], interactive=True) with gr.Row(): hub_chat_model_names_dropdown = gr.Dropdown(base_model_names, label=f"Chat Model",show_label=False,allow_custom_value=True, value=base_model_names[0] if base_model_names else None, interactive=True, scale=4, min_width=1) download_hub_chat_model_names_btn = gr.Button("Download", scale=1) stop_download_hub_chat_model_names_btn = gr.Button("Stop", scale=1, visible=False) local_chat_model_names_dropdown = gr.Dropdown(local_chat_model_names, label=f"Chat Model",show_label=False, value=local_chat_model_names[0] if local_chat_model_names else None, interactive=True, scale=4, min_width=1,visible=False) refresh_local_chat_model_names_btn = gr.Button("Refresh", scale=1,visible=False) rag_using_4bit_quantization_checkbox = gr.Checkbox(True, label="Using 4-bit quantization", interactive=True, visible=True, info="Less memory but slower", scale=1 ) if validate_model_path(base_model_names[0])[0]: download_hub_chat_model_status_markdown = gr.Markdown( '<span style="color:green">&nbsp;&nbsp;&nbsp;&nbsp;This model has already been downloaded to local.</span>') else: download_hub_chat_model_status_markdown = gr.Markdown( '<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;This model has not been downloaded.</span>') with gr.Tab("Setting"): # with gr.Column(scale=4, min_width=1): with gr.Group(): gr.Markdown("## &nbsp;Setting", elem_classes="white_background") with gr.Group(): with gr.Row(): max_new_tokens_slider = gr.Slider(1, 4096, value=256, step=0.1, label="Max New Tokens", interactive=True) temperature_slider = gr.Slider(0, 5, value=1, step=0.1, label="Temperature", interactive=True) with gr.Row(): top_k_slider = gr.Slider(1, 100, value=50, step=1, label="Top_k", interactive=True) top_p_slider = gr.Slider(0, 1, value=1, step=0.1, label="Top_p", interactive=True) with gr.Row(): repeat_penalty_slider = gr.Slider(1, 5, value=1, step=0.1, label="Repeat Penalty", interactive=True) with gr.Row(): chat_history_window_slider = gr.Slider(1, 20, value=3, step=1, label="Chat History Window", interactive=True) low_cpu_mem_usage_checkbox = gr.Checkbox(False, label="Low Cpu Mem Usage",interactive=True,visible=False) Huggingface_hub_token = gr.Textbox(label="Huggingface Hub Token", value="") def check_local_model_or_dataset_is_empty1(base_model_name_dropdown,Huggingface_hub_token): if len(base_model_name_dropdown.strip()) == 0: raise gr.Error("Name is empty!") try: login_huggingface(Huggingface_hub_token,base_model_name_dropdown) except Exception as e: raise gr.Error(e) def check_local_model_or_dataset_is_empty2(base_model_name_dropdown,Huggingface_hub_token): if len(base_model_name_dropdown.strip()) == 0: raise gr.Error("Name is empty!") try: login_huggingface(Huggingface_hub_token,base_model_name_dropdown) except Exception as e: raise gr.Error(e) def check_local_model_or_dataset_is_empty3(base_model_name_dropdown,Huggingface_hub_token): if len(base_model_name_dropdown.strip()) == 0: raise gr.Error("Name is empty!") try: login_huggingface(Huggingface_hub_token,base_model_name_dropdown) except Exception as e: raise gr.Error(e) def check_local_model_or_dataset_is_empty4(base_model_name_dropdown,Huggingface_hub_token): if len(base_model_name_dropdown.strip()) == 0: raise gr.Error("Name is empty!") try: login_huggingface(Huggingface_hub_token,base_model_name_dropdown) except Exception as e: raise gr.Error(e) def check_local_model_or_dataset_is_empty5(base_model_name_dropdown,Huggingface_hub_token): if len(base_model_name_dropdown.strip()) == 0: raise gr.Error("Name is empty!") try: login_huggingface(Huggingface_hub_token,base_model_name_dropdown) except Exception as e: raise gr.Error(e) def download_hub_home_chat_model_postprocess(): return gr.update(visible=True), gr.update(visible=False) def click_download_hub_home_chat_model_btn(): return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True) def click_stop_download_hub_home_chat_model_names_btn(): return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) def click_stop_download_hub_home_chat_model_names_btn(): return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) def change_home_chat_model_source_radio(home_chat_model_source_radio, hub_home_chat_model_names_dropdown): local_home_chat_model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models") if home_chat_model_source_radio == "Download From Huggingface Hub": if not hub_home_chat_model_names_dropdown: model_download_status = '<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;No model is selected.</span>' else: if validate_model_path(hub_home_chat_model_names_dropdown)[0]: model_download_status = '<span style="color:green">&nbsp;&nbsp;&nbsp;&nbsp;This model has already been downloaded to local,click load model to run.</span>' else: model_download_status = '<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;This model has not been downloaded.</span>' return gr.update(visible=True), gr.update(visible=False), gr.update( visible=False), gr.update(visible=True, value=model_download_status), gr.update( visible=True), gr.update( visible=False) else: model_download_status = "" return gr.update(visible=False), gr.update(visible=True), gr.update( visible=True), gr.update(visible=False, value=model_download_status), gr.update( visible=False), gr.update( visible=False) click_download_hub_home_chat_model_names_btn_event = download_hub_home_chat_model_names_btn.click( check_local_model_or_dataset_is_empty1, [hub_home_chat_model_names_dropdown,Huggingface_hub_token]).success( click_download_hub_home_chat_model_btn, [], [download_hub_home_chat_model_names_btn, stop_download_hub_home_chat_model_names_btn, download_hub_home_chat_model_status_markdown]).then( download_model_wrapper, [hub_home_chat_model_names_dropdown, local_home_chat_model_root_dir_textbox], download_hub_home_chat_model_status_markdown). \ then(download_hub_home_chat_model_postprocess, [], [download_hub_home_chat_model_names_btn, stop_download_hub_home_chat_model_names_btn]) stop_download_hub_home_chat_model_names_btn.click(click_stop_download_hub_home_chat_model_names_btn, [], [download_hub_home_chat_model_names_btn, stop_download_hub_home_chat_model_names_btn, download_hub_home_chat_model_status_markdown], cancels=[ click_download_hub_home_chat_model_names_btn_event]) home_chat_model_source_radio.change(change_home_chat_model_source_radio, [home_chat_model_source_radio, hub_home_chat_model_names_dropdown], [hub_home_chat_model_names_dropdown, local_home_chat_model_names_dropdown, refresh_local_home_chat_model_names_btn, download_hub_home_chat_model_status_markdown, download_hub_home_chat_model_names_btn, stop_download_hub_home_chat_model_names_btn], cancels=[click_download_hub_home_chat_model_names_btn_event]) def change_refresh_local_home_chat_model_names_btn(): local_home_chat_model_names = get_hg_model_names_and_gguf_from_dir(local_home_chat_model_dir,runs_model_root_dir) return gr.update(choices=local_home_chat_model_names,value = local_home_chat_model_names[0] if local_home_chat_model_names else None) refresh_local_home_chat_model_names_btn.click(change_refresh_local_home_chat_model_names_btn,[],[local_home_chat_model_names_dropdown]) def change_hub_home_chat_model_names_dropdown(hub_home_chat_model_names_dropdown): if not hub_home_chat_model_names_dropdown: return gr.update(visible=True, value='<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;No model is selected.</span>'), \ gr.update(visible=True), gr.update(visible=False) if validate_model_path(hub_home_chat_model_names_dropdown)[0]: return gr.update( visible=True, value='<span style="color:green">&nbsp;&nbsp;&nbsp;&nbsp;This model has already been downloaded to local,click load model to run.</span>'), \ gr.update(visible=True), gr.update(visible=False) else: return gr.update(visible=True, value='<span style="color:red">&nbsp;&nbsp;&nbsp;&nbsp;This model has not been downloaded.</span>'), \ gr.update(visible=True), gr.update(visible=False) hub_home_chat_model_names_dropdown.change(change_hub_home_chat_model_names_dropdown, hub_home_chat_model_names_dropdown, [download_hub_home_chat_model_status_markdown, download_hub_home_chat_model_names_btn, stop_download_hub_home_chat_model_names_btn], cancels=[click_download_hub_home_chat_model_names_btn_event]) def click_load_home_chat_model_btn(home_chat_model_source_radio, hub_home_chat_model_names_dropdown, local_home_chat_model_names_dropdown, max_new_tokens_slider, temperature_slider, top_k_slider, top_p_slider, repeat_penalty_slider, chat_history_window_slider,using_4bit_quantization_checkbox,low_cpu_mem_usage_checkbox, progress=gr.Progress()): if home_chat_model_source_radio == "Download From Huggingface Hub": cur_model_name = hub_home_chat_model_names_dropdown else: cur_model_name = local_home_chat_model_names_dropdown if not validate_model_path(cur_model_name)[0]: raise gr.Error(f"Model does not exist!") global infer_model global stop_generation_status stop_generation_status = True progress(0.6) if infer_model: infer_model.free_memory() infer_model = None torch.cuda.empty_cache() yield "Loading model ..." load_model_status = 0 model_path = validate_model_path(cur_model_name)[1] if model_path.split('.')[-1] == "gguf": infer_model = LlamaCppInference(model_path=model_path, max_new_tokens=max_new_tokens_slider, temperature=temperature_slider, top_k=top_k_slider, top_p=top_p_slider, repetition_penalty=repeat_penalty_slider) load_model_status, msg = infer_model.load_model() else: infer_model = HuggingfaceInference(model_path=model_path, max_new_tokens=max_new_tokens_slider, temperature=temperature_slider, top_k=top_k_slider, top_p=top_p_slider, repetition_penalty=repeat_penalty_slider, using_4bit_quantization=using_4bit_quantization_checkbox, low_cpu_mem_usage=low_cpu_mem_usage_checkbox) load_model_status, msg = infer_model.load_model() if load_model_status == -1: raise gr.Error(f"Loading model error:{msg}") if infer_model: infer_model.free_memory() infer_model = None torch.cuda.empty_cache() return progress(1.0) return gr.update() def update_model_running_status(): global chatbot_history return gr.update(visible=True, value=f"<span style='color:green'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Model is runing ...</span>"),chatbot_history,gr.update() def show_model_running_status(): return gr.update(visible=True) load_home_chat_model_btn.click(show_model_running_status, [], download_hub_home_chat_model_status_markdown).then( click_load_home_chat_model_btn, [home_chat_model_source_radio, hub_home_chat_model_names_dropdown, local_home_chat_model_names_dropdown, max_new_tokens_slider, temperature_slider, top_k_slider, top_p_slider, repeat_penalty_slider, chat_history_window_slider,using_4bit_quantization_checkbox,low_cpu_mem_usage_checkbox], [download_hub_home_chat_model_status_markdown]). \ success(update_model_running_status, [], [download_hub_home_chat_model_status_markdown,chatbot,input_txtbox]) def click_stop_btn(): global stop_generation_status stop_generation_status = True def clear_chat_history(): global chatbot_history, stop_generation_status stop_generation_status = True chatbot_history = [] return gr.update(value=None) def show_chatbot_question1(text): global chatbot_history if not text: raise gr.Error('Enter text') chatbot_history = chatbot_history + [[text, '']] chatbot_history = chatbot_history[-5:] return chatbot_history def show_chatbot_question2(text): global chatbot_history if not text: raise gr.Error('Enter text') chatbot_history = chatbot_history + [[text, '']] chatbot_history = chatbot_history[-5:] return chatbot_history # input_txtbox.submit(add_text) def generate_btn_click1(input_txtbox): global chatbot_history, infer_model, stop_generation_status chatbot_history_np = np.asarray(chatbot_history) chatbot_history_np = chatbot_history_np.flatten() chatbot_history_list = chatbot_history_np.tolist() stop_generation_status = False model_type = "other model" if infer_model: model_type = get_model_type(infer_model.model_path) prompt = get_chat_history_prompt(chatbot_history_list, model_type) print(f"{model_type} input prompt:", prompt) answer = infer_model(prompt) else: raise gr.Error("Model is not loaded!") return chatbot_history,gr.update(value="") print(f"{model_type} output:", answer) for char in answer: if stop_generation_status: break try: chatbot_history[-1][-1] += char except: break time.sleep(0.05) # print("d2:",chatbot_history) yield chatbot_history,gr.update(value="") yield chatbot_history,gr.update(value="") def generate_btn_click2(input_txtbox): global chatbot_history, infer_model, stop_generation_status chatbot_history_np = np.asarray(chatbot_history) chatbot_history_np = chatbot_history_np.flatten() chatbot_history_list = chatbot_history_np.tolist() stop_generation_status = False running_model_name = "other model" if infer_model: if infer_model.model_path.lower().find("mistral") >= 0 and infer_model.model_path.lower().find( "instruct") >= 0: running_model_name = "mistral" prompt = get_chat_history_prompt(chatbot_history_list, running_model_name) elif infer_model.model_path.lower().find("llama") >= 0 and infer_model.model_path.lower().find("chat") >= 0: running_model_name = "llama2" prompt = get_chat_history_prompt(chatbot_history_list, running_model_name) elif infer_model.model_path.lower().find("zephyr") >= 0: running_model_name = "zephyr" prompt = get_chat_history_prompt(chatbot_history_list, running_model_name) else: prompt = ','.join(chatbot_history_list[:-2]) prompt = prompt + chatbot_history_list[-2] print(f"{running_model_name} input prompt:", prompt) answer = infer_model(prompt) else: raise gr.Error("Model is not loaded!") return chatbot_history,gr.update(value="") print(f"{running_model_name} output:", answer) for char in answer: if stop_generation_status: break try: chatbot_history[-1][-1] += char except: break time.sleep(0.05) # print("d2:",chatbot_history) yield chatbot_history,gr.update(value="") yield chatbot_history,gr.update(value="") def generate_btn_click_clear_text1(): return gr.update(value="") def generate_btn_click_clear_text2(): return gr.update(value="") input_txtbox.submit(show_chatbot_question1, inputs=[input_txtbox], outputs=[chatbot], queue=False). \ success(generate_btn_click1, inputs=[input_txtbox], outputs=[chatbot,input_txtbox]) generate_btn.click(show_chatbot_question2, inputs=[input_txtbox], outputs=[chatbot], queue=False). \ success(generate_btn_click2, inputs=[input_txtbox], outputs=[chatbot,input_txtbox]) # clear_btn.click(clear_chat_history, [], chatbot) stop_btn.click(click_stop_btn) ########################## ###################### def click_delete_text_btn(training_runs_dropdown): delete_run_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs', training_runs_dropdown) if os.path.exists(delete_run_dir): shutil.rmtree(delete_run_dir) training_runs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'runs') run_names = os.listdir(training_runs_dir) run_names = [run_name for run_name in run_names if os.path.isdir(os.path.join(training_runs_dir, run_name))] run_names.sort(key=lambda f: os.path.getmtime(os.path.join(training_runs_dir, f))) sss = np.random.randint(0, 100) + 1000 iframe = f'<iframe src={TENSORBOARD_URL} style="border:none;height:{sss}px;width:100%">' return gr.update(choices=run_names, value=run_names[0] if run_names else ""), gr.update(value=iframe) def click_stop_training_btn(): global stop_training
if TRAINING_STATUS.status == 0:
16
2023-11-25 12:37:21+00:00
16k
danilonumeroso/conar
models/vkc_reasoner.py
[ { "identifier": "AlgorithmReasoner", "path": "models/algorithm_reasoner.py", "snippet": "class AlgorithmReasoner(nn.Module):\n @staticmethod\n def prepare_batch(batch):\n batch = batch.clone()\n for name, tensor in batch.items():\n if not torch.is_tensor(tensor):\n ...
from collections import defaultdict from pprint import pprint from torch_geometric.loader import DataLoader from pytorch_lightning.trainer.supporters import CombinedLoader from models.algorithm_reasoner import AlgorithmReasoner, LitAlgorithmReasoner from utils_execution import get_number_of_nodes from hyperparameters import get_hyperparameters from datasets._configs import CONFIGS import torch import torch_geometric import torch_geometric.utils as tg_utils import torch_scatter import networkx as nx
13,314
class LitVKCReasoner(LitAlgorithmReasoner): def __init__(self, hidden_dim, algo_processor, dataset_class, dataset_root, dataset_kwargs, bias=True, transferring=False, learning_rate=get_hyperparameters()['lr'], double_process=False, **algo_reasoner_kwargs): super().__init__(hidden_dim, algo_processor, dataset_class, dataset_root, dataset_kwargs, bias=bias, transferring=transferring, learning_rate=learning_rate, **algo_reasoner_kwargs) self.algorithm_module = AlgorithmReasoner( self.dataset.spec, self.dataset[0], hidden_dim, algo_processor, bias=bias, transferring=transferring, timeit=self.timeit, double_process=double_process, **algo_reasoner_kwargs) self.double_process = double_process self.save_hyperparameters(ignore=['algo_processor']) def training_step(self, batch, batch_idx): ret = {'loss': 0, 'losses_dict': defaultdict(list), 'accuracies': defaultdict(list)} for bb in batch: ans = super().training_step(bb, batch_idx) ret['loss'] += ans['loss'] for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k].append(v) ret['loss'] /= len(batch) for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k] = torch.tensor(v).mean() return ret def get_VKC_metrics(self, batch, output_logits): selected_dense = torch_geometric.utils.to_dense_batch(output_logits['output']['selected'], batch=batch.batch)[0] selected_dense_topk = torch.sort(torch.topk(selected_dense.squeeze(-1), self.dataset.k, dim=-1).indices).values selected_topk = (selected_dense_topk+batch.ptr[:-1].unsqueeze(-1)).view(-1) selected_topk_gt = batch.selected.nonzero().squeeze(-1) selected_batch = batch.batch[selected_topk] acc_selected_topk = torch_scatter.scatter_mean((selected_topk == selected_topk_gt).float(), selected_batch).mean() G = tg_utils.to_networkx(batch, to_undirected=True, edge_attrs=['edge_attr']) mspl = nx.multi_source_dijkstra_path_length(G, sources=selected_topk.tolist(), weight='edge_attr') mspl = torch.tensor([mspl[i] for i in range(batch.num_nodes)]).to(selected_dense) farthest = torch_scatter.scatter_max(mspl, batch.batch)[0] assert (farthest + torch.finfo(torch.float32).eps >= batch.farthest).all() return { 'acc_topk': acc_selected_topk, 'farthest': farthest.mean(), 'farthest_gt': batch.farthest.mean(), 'farthest_relative_error': ((farthest-batch.farthest)/batch.farthest).mean(), } def get_metrics(self, batch, all_hint_logits, output_logits, all_masks_graph): accs_dict = super().get_metrics(batch, all_hint_logits, output_logits, all_masks_graph) accs_dict.update(**self.get_VKC_metrics(batch, output_logits)) return accs_dict def load_dataset(self, split, suffix=''): split = split+suffix
class LitVKCReasoner(LitAlgorithmReasoner): def __init__(self, hidden_dim, algo_processor, dataset_class, dataset_root, dataset_kwargs, bias=True, transferring=False, learning_rate=get_hyperparameters()['lr'], double_process=False, **algo_reasoner_kwargs): super().__init__(hidden_dim, algo_processor, dataset_class, dataset_root, dataset_kwargs, bias=bias, transferring=transferring, learning_rate=learning_rate, **algo_reasoner_kwargs) self.algorithm_module = AlgorithmReasoner( self.dataset.spec, self.dataset[0], hidden_dim, algo_processor, bias=bias, transferring=transferring, timeit=self.timeit, double_process=double_process, **algo_reasoner_kwargs) self.double_process = double_process self.save_hyperparameters(ignore=['algo_processor']) def training_step(self, batch, batch_idx): ret = {'loss': 0, 'losses_dict': defaultdict(list), 'accuracies': defaultdict(list)} for bb in batch: ans = super().training_step(bb, batch_idx) ret['loss'] += ans['loss'] for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k].append(v) ret['loss'] /= len(batch) for name in ['losses_dict', 'accuracies']: for k, v in ans[name].items(): ret[name][k] = torch.tensor(v).mean() return ret def get_VKC_metrics(self, batch, output_logits): selected_dense = torch_geometric.utils.to_dense_batch(output_logits['output']['selected'], batch=batch.batch)[0] selected_dense_topk = torch.sort(torch.topk(selected_dense.squeeze(-1), self.dataset.k, dim=-1).indices).values selected_topk = (selected_dense_topk+batch.ptr[:-1].unsqueeze(-1)).view(-1) selected_topk_gt = batch.selected.nonzero().squeeze(-1) selected_batch = batch.batch[selected_topk] acc_selected_topk = torch_scatter.scatter_mean((selected_topk == selected_topk_gt).float(), selected_batch).mean() G = tg_utils.to_networkx(batch, to_undirected=True, edge_attrs=['edge_attr']) mspl = nx.multi_source_dijkstra_path_length(G, sources=selected_topk.tolist(), weight='edge_attr') mspl = torch.tensor([mspl[i] for i in range(batch.num_nodes)]).to(selected_dense) farthest = torch_scatter.scatter_max(mspl, batch.batch)[0] assert (farthest + torch.finfo(torch.float32).eps >= batch.farthest).all() return { 'acc_topk': acc_selected_topk, 'farthest': farthest.mean(), 'farthest_gt': batch.farthest.mean(), 'farthest_relative_error': ((farthest-batch.farthest)/batch.farthest).mean(), } def get_metrics(self, batch, all_hint_logits, output_logits, all_masks_graph): accs_dict = super().get_metrics(batch, all_hint_logits, output_logits, all_masks_graph) accs_dict.update(**self.get_VKC_metrics(batch, output_logits)) return accs_dict def load_dataset(self, split, suffix=''): split = split+suffix
nns = get_number_of_nodes(self.algorithm, split)
2
2023-11-20 15:32:43+00:00
16k
harisankar95/pathfinding3D
test/test_path.py
[ { "identifier": "DiagonalMovement", "path": "pathfinding3d/core/diagonal_movement.py", "snippet": "class DiagonalMovement:\n always = 1\n never = 2\n if_at_most_one_obstacle = 3\n only_when_no_obstacle = 4" }, { "identifier": "Grid", "path": "pathfinding3d/core/grid.py", "sni...
import numpy as np import pytest from pathfinding3d.core.diagonal_movement import DiagonalMovement from pathfinding3d.core.grid import Grid from pathfinding3d.core.node import GridNode from pathfinding3d.finder.a_star import AStarFinder from pathfinding3d.finder.best_first import BestFirst from pathfinding3d.finder.bi_a_star import BiAStarFinder from pathfinding3d.finder.breadth_first import BreadthFirstFinder from pathfinding3d.finder.dijkstra import DijkstraFinder from pathfinding3d.finder.finder import ExecutionRunsException, ExecutionTimeException from pathfinding3d.finder.ida_star import IDAStarFinder from pathfinding3d.finder.msp import MinimumSpanningTree
11,366
weighted_finders = [ AStarFinder, BiAStarFinder, DijkstraFinder, MinimumSpanningTree, ] SIMPLE_MATRIX = np.zeros((5, 5, 5)) SIMPLE_MATRIX[0, 0, 0] = 1 SIMPLE_MATRIX[0, 0, 1] = 1 SIMPLE_MATRIX[0, 0, 2] = 1 SIMPLE_MATRIX[0, 0, 3] = 1 SIMPLE_MATRIX[0, 0, 4] = 1 SIMPLE_MATRIX[1, :, :] = 1 SIMPLE_MATRIX[2, :, :] = 1 SIMPLE_MATRIX[3, :, :] = 1 SIMPLE_MATRIX[4, 0, 0] = 1 SIMPLE_MATRIX[4, 1, 0] = 1 SIMPLE_MATRIX[4, 2, 0] = 1 SIMPLE_MATRIX[4, 3, 0] = 1 SIMPLE_MATRIX[4, 4, 0] = 1 WEIGHTED_SIMPLE_MATRIX = np.copy(SIMPLE_MATRIX) WEIGHTED_SIMPLE_MATRIX[4, 1, 1] = 1 WEIGHTED_SIMPLE_MATRIX[4, 2, 1] = 1 WEIGHTED_SIMPLE_MATRIX[4, 3, 1] = 1 WEIGHTED_SIMPLE_MATRIX[4, 2, 0] = 99 WEIGHTED_SIMPLE_MATRIX[1, :, :] = 99 WEIGHTED_SIMPLE_MATRIX[2, :, :] = 99 WEIGHTED_SIMPLE_MATRIX[3, :, :] = 99 def test_path(): """ test if we can find a path """ grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(time_limit=TIME_LIMIT) path_, runs = finder.find_path(start, end, grid) path = [] for node in path_: if isinstance(node, GridNode): path.append((node.x, node.y, node.z)) elif isinstance(node, tuple): path.append((node[0], node[1], node[2])) print(find.__name__) print(f"path: {path}") print(f"length: {len(path)}, runs: {runs}") assert len(path) == 9 def test_weighted_path(): grid = Grid(matrix=WEIGHTED_SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in weighted_finders: grid.cleanup() finder = find(time_limit=TIME_LIMIT) path_, runs = finder.find_path(start, end, grid) path = [] for node in path_: if isinstance(node, GridNode): path.append((node.x, node.y, node.z)) elif isinstance(node, tuple): path.append((node[0], node[1], node[2])) print(find.__name__) print(f"path: {path}") print(f"length: {len(path)}, runs: {runs}") assert len(path) == 11 def test_path_diagonal(): # test diagonal movement grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(diagonal_movement=DiagonalMovement.always, time_limit=TIME_LIMIT) path_, runs = finder.find_path(start, end, grid) path = [] for node in path_: if isinstance(node, GridNode): path.append((node.x, node.y, node.z)) elif isinstance(node, tuple): path.append((node[0], node[1], node[2])) print(find.__name__) print(f"path: {path}") print(f"length: {len(path)}, runs: {runs}") assert len(path) == 5 def test_max_runs(): grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(diagonal_movement=DiagonalMovement.always, time_limit=TIME_LIMIT, max_runs=3) with pytest.raises(ExecutionRunsException): path, runs = finder.find_path(start, end, grid) print(f"{find.__name__} finishes after {runs} runs without exception") print(f"path: {path}") msg = f"{finder.__class__.__name__} needed too many iterations" assert finder.runs <= 3, msg def test_time(): grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(diagonal_movement=DiagonalMovement.always, time_limit=-0.1)
finders = [ AStarFinder, BestFirst, BiAStarFinder, DijkstraFinder, IDAStarFinder, BreadthFirstFinder, MinimumSpanningTree, ] TIME_LIMIT = 10 # give it a 10 second limit. weighted_finders = [ AStarFinder, BiAStarFinder, DijkstraFinder, MinimumSpanningTree, ] SIMPLE_MATRIX = np.zeros((5, 5, 5)) SIMPLE_MATRIX[0, 0, 0] = 1 SIMPLE_MATRIX[0, 0, 1] = 1 SIMPLE_MATRIX[0, 0, 2] = 1 SIMPLE_MATRIX[0, 0, 3] = 1 SIMPLE_MATRIX[0, 0, 4] = 1 SIMPLE_MATRIX[1, :, :] = 1 SIMPLE_MATRIX[2, :, :] = 1 SIMPLE_MATRIX[3, :, :] = 1 SIMPLE_MATRIX[4, 0, 0] = 1 SIMPLE_MATRIX[4, 1, 0] = 1 SIMPLE_MATRIX[4, 2, 0] = 1 SIMPLE_MATRIX[4, 3, 0] = 1 SIMPLE_MATRIX[4, 4, 0] = 1 WEIGHTED_SIMPLE_MATRIX = np.copy(SIMPLE_MATRIX) WEIGHTED_SIMPLE_MATRIX[4, 1, 1] = 1 WEIGHTED_SIMPLE_MATRIX[4, 2, 1] = 1 WEIGHTED_SIMPLE_MATRIX[4, 3, 1] = 1 WEIGHTED_SIMPLE_MATRIX[4, 2, 0] = 99 WEIGHTED_SIMPLE_MATRIX[1, :, :] = 99 WEIGHTED_SIMPLE_MATRIX[2, :, :] = 99 WEIGHTED_SIMPLE_MATRIX[3, :, :] = 99 def test_path(): """ test if we can find a path """ grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(time_limit=TIME_LIMIT) path_, runs = finder.find_path(start, end, grid) path = [] for node in path_: if isinstance(node, GridNode): path.append((node.x, node.y, node.z)) elif isinstance(node, tuple): path.append((node[0], node[1], node[2])) print(find.__name__) print(f"path: {path}") print(f"length: {len(path)}, runs: {runs}") assert len(path) == 9 def test_weighted_path(): grid = Grid(matrix=WEIGHTED_SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in weighted_finders: grid.cleanup() finder = find(time_limit=TIME_LIMIT) path_, runs = finder.find_path(start, end, grid) path = [] for node in path_: if isinstance(node, GridNode): path.append((node.x, node.y, node.z)) elif isinstance(node, tuple): path.append((node[0], node[1], node[2])) print(find.__name__) print(f"path: {path}") print(f"length: {len(path)}, runs: {runs}") assert len(path) == 11 def test_path_diagonal(): # test diagonal movement grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(diagonal_movement=DiagonalMovement.always, time_limit=TIME_LIMIT) path_, runs = finder.find_path(start, end, grid) path = [] for node in path_: if isinstance(node, GridNode): path.append((node.x, node.y, node.z)) elif isinstance(node, tuple): path.append((node[0], node[1], node[2])) print(find.__name__) print(f"path: {path}") print(f"length: {len(path)}, runs: {runs}") assert len(path) == 5 def test_max_runs(): grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(diagonal_movement=DiagonalMovement.always, time_limit=TIME_LIMIT, max_runs=3) with pytest.raises(ExecutionRunsException): path, runs = finder.find_path(start, end, grid) print(f"{find.__name__} finishes after {runs} runs without exception") print(f"path: {path}") msg = f"{finder.__class__.__name__} needed too many iterations" assert finder.runs <= 3, msg def test_time(): grid = Grid(matrix=SIMPLE_MATRIX) start = grid.node(0, 0, 0) end = grid.node(4, 4, 0) for find in finders: grid.cleanup() finder = find(diagonal_movement=DiagonalMovement.always, time_limit=-0.1)
with pytest.raises(ExecutionTimeException):
9
2023-11-21 10:14:12+00:00
16k
yuukawahiroshi/ddb-tools
extract_wav.py
[ { "identifier": "DDIModel", "path": "utils/ddi_utils.py", "snippet": "class DDIModel:\n def __init__(self, ddi_bytes: bytes) -> None:\n self.ddi_bytes = ddi_bytes\n self.ddi_data = None\n self.phdc_data = {}\n self.tdb_data = {}\n self.sta_data = {}\n self.ar...
import argparse import math import os import re import time import wave from typing import Sequence, TypedDict from utils.ddi_utils import DDIModel, bytes_to_str, stream_reverse_search
11,581
start_time = offset_time + \ frm2sec(frame_align[i]["start"], sample_rate) end_time = offset_time + frm2sec(frame_align[i]["end"], sample_rate) if i == 0: boundaries.append(start_time) boundaries.append(end_time) seg_list.append([phoneme, start_time, end_time]) art_seg_info: ArticulationSegmentInfo = { "boundaries": boundaries, "phonemes": [] } if len(phonemes) == 4: # VCV art_seg_info["phonemes"] = [phonemes[0], phonemes[1], phonemes[3]] else: art_seg_info["phonemes"] = phonemes trans_content = generate_transcription(seg_list) seg_content = generate_seg(seg_list, duration_time) art_seg_content = generate_articulation_seg( art_seg_info, total_bytes, unvoiced_consonant_list) return trans_content, seg_content, art_seg_content def generate_transcription(seg_info: list[list]) -> str: content = [] phoneme_list = [] for i in range(0, len(seg_info)): phoneme_list.append(seg_info[i][0]) content.append(" ".join(phoneme_list)) trans_group = [item[0] for item in seg_info] content.append("[" + " ".join(trans_group) + "]") return "\n".join(content) def generate_seg( phoneme_list: list[list], wav_length: float ) -> str: content = [ "nPhonemes %d" % (len(phoneme_list) + 2,), # Add 2 Sil "articulationsAreStationaries = 0", "phoneme BeginTime EndTime", "===================================================", ] content.append("%s\t\t%.6f\t\t%.6f" % ("Sil", 0, phoneme_list[0][1])) begin_time: float = 0 end_time: float = 0 for i in range(0, len(phoneme_list)): phoneme_info = phoneme_list[i] phoneme_name = phoneme_info[0] begin_time = phoneme_info[1] end_time = phoneme_info[2] content.append("%s\t\t%.6f\t\t%.6f" % (phoneme_name, begin_time, end_time)) content.append("%s\t\t%.6f\t\t%.6f" % ("Sil", end_time, wav_length)) return "\n".join(content) + "\n" def generate_articulation_seg( art_seg_info: ArticulationSegmentInfo, wav_samples: int, unvoiced_consonant_list: list[str] ) -> str: content = [ "nphone art segmentation", "{", '\tphns: ["' + ('", "'.join(art_seg_info["phonemes"])) + '"];', "\tcut offset: 0;", "\tcut length: %d;" % int(math.floor(wav_samples / 2)), ] boundaries_str = [ ("%.9f" % item) for item in art_seg_info["boundaries"] ] content.append("\tboundaries: [" + ", ".join(boundaries_str) + "];") content.append("\trevised: false;") voiced_str = [] is_triphoneme = len(art_seg_info["phonemes"]) == 3 for i in range(0, len(art_seg_info["phonemes"])): phoneme = art_seg_info["phonemes"][i] is_unvoiced = phoneme in unvoiced_consonant_list or phoneme in [ "Sil", "Asp", "?", ] voiced_str.append(str(not is_unvoiced).lower()) if is_triphoneme and i == 1: # Triphoneme needs 2 flags for center phoneme voiced_str.append(str(not is_unvoiced).lower()) content.append("\tvoiced: [" + ", ".join(voiced_str) + "];") content.append("};") content.append("") return "\n".join(content) def main(): ddi_path, ddb_path, dst_path, filename_style, gen_lab, gen_seg = parse_args() snd_pos_list: list[int] = [] # Read DDI file print("Reading DDI...") with open(ddi_path, "rb") as f: ddi_bytes = f.read()
#!/usr/bin/env python3 from __future__ import annotations start_encode = 'SND '.encode() wav_params = (1, 2, 44100, 0, 'NONE', 'NONE') window_size = 512 class ArticulationSegmentInfo(TypedDict): phonemes: list[str, str] boundaries: list[list[str, float, float]] def escape_xsampa(xsampa: str) -> str: """Escapes xsampa to file name.""" xsampa = xsampa.replace("Sil", "sil") # Sil is a special case xsampa = ( xsampa.replace("\\", "-") .replace("/", "~") .replace("?", "!") .replace(":", ";") .replace("<", "(") .replace(">", ")") ) return xsampa def unescape_xsampa(xsampa: str) -> str: """Unescapes xsampa from file name.""" xsampa = ( xsampa.replace("-", "\\") .replace("~", "/") .replace("!", "?") .replace(";", ":") .replace("(", "<") .replace(")", ">") ) return xsampa def parse_args(args: Sequence[str] = None): # : list[str] # initialize parser parser = argparse.ArgumentParser() parser.add_argument('--src_path', required=True, help='source ddi file path') parser.add_argument('--dst_path', help='destination extract path, ' 'default to be "./[name]/snd"') parser.add_argument('--gen_lab', action='store_true', help='generate lab file') parser.add_argument('--gen_seg', action='store_true', help='generate trans, seg, as files') parser.add_argument('--filename_style', type=str, choices=['flat', 'devkit'], default=None, help="output filename style, default to be 'devkit', or default to be 'flat' if gen_lab is true.") # parse args args_result = parser.parse_args(args) ddi_path: str = os.path.normpath(args_result.src_path) ddb_path: str = re.sub(r'\.ddi$', '.ddb', ddi_path) dst_path: str = args_result.dst_path if dst_path is None: dst_path = os.path.dirname(ddi_path) + '/snd' dst_path: str = os.path.normpath(dst_path) # make dirs if not os.path.exists(dst_path): os.makedirs(dst_path) gen_lab: bool = args_result.gen_lab gen_seg: bool = args_result.gen_seg filename_style: str = args_result.filename_style if filename_style is None: if gen_lab or gen_seg: filename_style = "flat" else: filename_style = "devkit" return ddi_path, ddb_path, dst_path, filename_style, gen_lab, gen_seg def create_file_name(phonemes: list[str], name_style: str, offset: int, pitch: float, dst_path: str, file_type: str): offset_hex = f'{offset:0>8x}' escaped_phonemes = [escape_xsampa(p) for p in phonemes] phonemes_len = len(phonemes) if pitch >= 0: pit_str = f"pit+{pitch:.2f}" else: pit_str = f"pit{pitch:.2f}" filename = "" if name_style == "flat": phonemes_str = "-".join(escaped_phonemes) prefix = "" if phonemes_len == 0: filename = f"unknown_{offset_hex}.{file_type}" else: if phonemes_len == 1: if phonemes[0] == "growl": prefix = "growl" else: prefix = "sta" elif phonemes_len == 2: prefix = "art" elif phonemes_len == 3: prefix = "tri" file_type_prefix = "lab" if file_type == "lab" else "wav" filename = f"{file_type_prefix}/{prefix}_[{phonemes_str}]_{pit_str}_{offset_hex}.{file_type}" elif name_style == "devkit": phonemes_path = "/".join([item + "#" + bytes_to_str(item.encode('utf-8')) for item in escaped_phonemes]) root_path = "" if phonemes_len == 0: filename = f"unknown/{offset_hex}.{file_type}" else: if phonemes_len == 1: if phonemes[0] == "growl": root_path = "vqm/growl" else: root_path = "stationary" elif phonemes_len == 2: root_path = "articulation" elif phonemes_len == 3: root_path = "triphoneme" filename = f"{root_path}/{phonemes_path}/{pit_str}_{offset_hex}.{file_type}" folder = os.path.dirname(filename) if folder != "": os.makedirs(os.path.join(dst_path, folder), exist_ok=True) return filename def nsample2sec(nsample: int, sample_rate: int) -> float: return nsample / sample_rate / 2 def frm2sec(frm: int, sample_rate: int) -> float: return frm * window_size / sample_rate / 2 def generate_lab(phonemes: list[str], frame_align: list[dict], sample_rate: int, offset_bytes: int, total_bytes: int): offset_time = nsample2sec(offset_bytes, sample_rate) * 1e7 duration_time = nsample2sec(total_bytes, sample_rate) * 1e7 lab_lines = [] if len(phonemes) == 3: # VCV center_phoneme = re.sub("^\^", "", phonemes[1]) phonemes = [phonemes[0], center_phoneme, center_phoneme, phonemes[2]] lab_lines.append(f"0 {offset_time:.0f} sil") last_time = 0 for i, phoneme in enumerate(phonemes): frame = frame_align[i] start_time = offset_time + frm2sec(frame["start"], sample_rate) * 1e7 end_time = offset_time + frm2sec(frame["end"], sample_rate) * 1e7 lab_lines.append(f'{start_time:.0f} {end_time:.0f} {phoneme}') last_time = end_time lab_lines.append(f'{last_time:.0f} {duration_time:.0f} sil') return "\n".join(lab_lines) def generate_seg_files( phonemes: list[str], frame_align: list[dict], sample_rate: int, offset_bytes: int, total_bytes: int, unvoiced_consonant_list: list[str]): offset_time = nsample2sec(offset_bytes, sample_rate) duration_time = nsample2sec(total_bytes, sample_rate) if len(phonemes) == 3: # VCV center_phoneme = re.sub("^\^", "", phonemes[1]) phonemes = [phonemes[0], center_phoneme, center_phoneme, phonemes[2]] seg_list: list[list] = [] boundaries: list[float] = [] for i, phoneme in enumerate(phonemes): start_time = offset_time + \ frm2sec(frame_align[i]["start"], sample_rate) end_time = offset_time + frm2sec(frame_align[i]["end"], sample_rate) if i == 0: boundaries.append(start_time) boundaries.append(end_time) seg_list.append([phoneme, start_time, end_time]) art_seg_info: ArticulationSegmentInfo = { "boundaries": boundaries, "phonemes": [] } if len(phonemes) == 4: # VCV art_seg_info["phonemes"] = [phonemes[0], phonemes[1], phonemes[3]] else: art_seg_info["phonemes"] = phonemes trans_content = generate_transcription(seg_list) seg_content = generate_seg(seg_list, duration_time) art_seg_content = generate_articulation_seg( art_seg_info, total_bytes, unvoiced_consonant_list) return trans_content, seg_content, art_seg_content def generate_transcription(seg_info: list[list]) -> str: content = [] phoneme_list = [] for i in range(0, len(seg_info)): phoneme_list.append(seg_info[i][0]) content.append(" ".join(phoneme_list)) trans_group = [item[0] for item in seg_info] content.append("[" + " ".join(trans_group) + "]") return "\n".join(content) def generate_seg( phoneme_list: list[list], wav_length: float ) -> str: content = [ "nPhonemes %d" % (len(phoneme_list) + 2,), # Add 2 Sil "articulationsAreStationaries = 0", "phoneme BeginTime EndTime", "===================================================", ] content.append("%s\t\t%.6f\t\t%.6f" % ("Sil", 0, phoneme_list[0][1])) begin_time: float = 0 end_time: float = 0 for i in range(0, len(phoneme_list)): phoneme_info = phoneme_list[i] phoneme_name = phoneme_info[0] begin_time = phoneme_info[1] end_time = phoneme_info[2] content.append("%s\t\t%.6f\t\t%.6f" % (phoneme_name, begin_time, end_time)) content.append("%s\t\t%.6f\t\t%.6f" % ("Sil", end_time, wav_length)) return "\n".join(content) + "\n" def generate_articulation_seg( art_seg_info: ArticulationSegmentInfo, wav_samples: int, unvoiced_consonant_list: list[str] ) -> str: content = [ "nphone art segmentation", "{", '\tphns: ["' + ('", "'.join(art_seg_info["phonemes"])) + '"];', "\tcut offset: 0;", "\tcut length: %d;" % int(math.floor(wav_samples / 2)), ] boundaries_str = [ ("%.9f" % item) for item in art_seg_info["boundaries"] ] content.append("\tboundaries: [" + ", ".join(boundaries_str) + "];") content.append("\trevised: false;") voiced_str = [] is_triphoneme = len(art_seg_info["phonemes"]) == 3 for i in range(0, len(art_seg_info["phonemes"])): phoneme = art_seg_info["phonemes"][i] is_unvoiced = phoneme in unvoiced_consonant_list or phoneme in [ "Sil", "Asp", "?", ] voiced_str.append(str(not is_unvoiced).lower()) if is_triphoneme and i == 1: # Triphoneme needs 2 flags for center phoneme voiced_str.append(str(not is_unvoiced).lower()) content.append("\tvoiced: [" + ", ".join(voiced_str) + "];") content.append("};") content.append("") return "\n".join(content) def main(): ddi_path, ddb_path, dst_path, filename_style, gen_lab, gen_seg = parse_args() snd_pos_list: list[int] = [] # Read DDI file print("Reading DDI...") with open(ddi_path, "rb") as f: ddi_bytes = f.read()
ddi_model = DDIModel(ddi_bytes)
0
2023-11-20 11:37:46+00:00
16k
shercoo/RGDiffSR
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n ...
import datetime import math import cv2 import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import pygame from collections import OrderedDict from matplotlib import pyplot as plt from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from torchvision import transforms from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler from text_super_resolution.model.VisionLAN.utils import Attention_AR_counter from text_super_resolution.model.tps_spatial_transformer import TPSSpatialTransformer from text_super_resolution.model.stn_head import STNHead from text_super_resolution.model.VisionLAN.VisionLAN import VisionLAN from utils.render_standard_text import * from text_super_resolution.loss.semantic_loss import SemanticLoss from text_super_resolution.utils import ssim_psnr from pygame import freetype from utils.metrics import *
14,310
x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, text_prior_enable=False, image_height=32, image_width=128, STN_enable=False, standard_text=False, VL_pretrained_path=None, fid_eval=False, visualize=False, down_sample_rate=2, recog_loss_enable=False, font_path=None, *args, **kwargs): self.fid_eval = fid_eval self.visualize = visualize self.text_prior_enable = text_prior_enable self.recog_loss_enable = recog_loss_enable self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__': conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True self.image_height = image_height self.image_width = image_width self.stn = STN_enable if self.stn: self.tps_inputsize = [image_height // down_sample_rate, image_width // down_sample_rate] tps_outputsize = [image_height // down_sample_rate, image_width // down_sample_rate] num_control_points = 20 tps_margins = [0.05, 0.05] self.tps = TPSSpatialTransformer( output_image_size=tuple(tps_outputsize), num_control_points=num_control_points, margins=tuple(tps_margins))
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} sem_loss = SemanticLoss() def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) else: raise NotImplementedError("mu not supported") # TODO how to choose this term lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") print(sd.keys()) print(sd['epoch']) print(sd['global_step']) print(sd['callbacks']) # print(sd['optimizer_states']) # print(sd['lr_schedulers']) # print(sd['state_dict'].keys()) # exit(0) if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys: {missing}") if len(unexpected) > 0: print(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start else: raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): # print('************************fuck',k) x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): # print('******************************in validation') _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, text_prior_enable=False, image_height=32, image_width=128, STN_enable=False, standard_text=False, VL_pretrained_path=None, fid_eval=False, visualize=False, down_sample_rate=2, recog_loss_enable=False, font_path=None, *args, **kwargs): self.fid_eval = fid_eval self.visualize = visualize self.text_prior_enable = text_prior_enable self.recog_loss_enable = recog_loss_enable self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__': conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True self.image_height = image_height self.image_width = image_width self.stn = STN_enable if self.stn: self.tps_inputsize = [image_height // down_sample_rate, image_width // down_sample_rate] tps_outputsize = [image_height // down_sample_rate, image_width // down_sample_rate] num_control_points = 20 tps_margins = [0.05, 0.05] self.tps = TPSSpatialTransformer( output_image_size=tuple(tps_outputsize), num_control_points=num_control_points, margins=tuple(tps_margins))
self.stn_head = STNHead(
20
2023-11-20 06:34:21+00:00
16k
mjavadpur/mj_ONNX_SadTalker
inference_onnx.py
[ { "identifier": "AnimateFromCoeff", "path": "src/facerender/animate_onnx.py", "snippet": "class AnimateFromCoeff():\n\n def __init__(self, sadtalker_path, device):\n\n with open(sadtalker_path['facerender_yaml']) as f:\n config = yaml.safe_load(f)\n\n generator = OcclusionAwa...
from glob import glob from time import strftime from argparse import ArgumentParser from src.facerender.animate_onnx import AnimateFromCoeff from src.generate_batch import get_data from src.generate_facerender_batch import get_facerender_data from src.utils.init_path import init_path from src.utils.preprocess import CropAndExtract from src.test_audio2coeff import Audio2Coeff from src.generate_batch import get_data from src.generate_facerender_batch import get_facerender_data from src.utils.init_path import init_path from src.face3d.visualize import gen_composed_video import shutil import torch import os, sys, time import base64
13,229
# from src.facerender.animate import AnimateFromCoeff def main(args): #torch.backends.cudnn.enabled = False # tts_service = os.getenv("TTS_SERVER") facerender_batch_size = 10 startInference = time.time() pic_path = args.source_image audio_path = args.driven_audio save_dir = os.path.join(args.result_dir, strftime("%Y_%m_%d_%H.%M.%S")) os.makedirs(save_dir, exist_ok=True) pose_style = args.pose_style device = args.device batch_size = args.batch_size input_yaw_list = args.input_yaw input_pitch_list = args.input_pitch input_roll_list = args.input_roll ref_eyeblink = args.ref_eyeblink ref_pose = args.ref_pose current_root_path = os.path.split(sys.argv[0])[0] sadtalker_paths = init_path(args.checkpoint_dir, os.path.join(current_root_path, 'src/config'), args.size, args.old_version, args.preprocess) #init model preprocess_model = CropAndExtract(sadtalker_paths, device) audio_to_coeff = Audio2Coeff(sadtalker_paths, device) animate_from_coeff = AnimateFromCoeff(sadtalker_paths, device) #crop image and extract 3dmm from image first_frame_dir = os.path.join(save_dir, 'first_frame_dir') os.makedirs(first_frame_dir, exist_ok=True) print('3DMM Extraction for source image') first_coeff_path, crop_pic_path, crop_info = preprocess_model.generate(pic_path, first_frame_dir, args.preprocess,\ source_image_flag=True, pic_size=args.size) if first_coeff_path is None: print("Can't get the coeffs of the input") return if ref_eyeblink is not None: ref_eyeblink_videoname = os.path.splitext(os.path.split(ref_eyeblink)[-1])[0] ref_eyeblink_frame_dir = os.path.join(save_dir, ref_eyeblink_videoname) os.makedirs(ref_eyeblink_frame_dir, exist_ok=True) print('3DMM Extraction for the reference video providing eye blinking') ref_eyeblink_coeff_path, _, _ = preprocess_model.generate(ref_eyeblink, ref_eyeblink_frame_dir, args.preprocess, source_image_flag=False) else: ref_eyeblink_coeff_path=None if ref_pose is not None: if ref_pose == ref_eyeblink: ref_pose_coeff_path = ref_eyeblink_coeff_path else: ref_pose_videoname = os.path.splitext(os.path.split(ref_pose)[-1])[0] ref_pose_frame_dir = os.path.join(save_dir, ref_pose_videoname) os.makedirs(ref_pose_frame_dir, exist_ok=True) print('3DMM Extraction for the reference video providing pose') ref_pose_coeff_path, _, _ = preprocess_model.generate(ref_pose, ref_pose_frame_dir, args.preprocess, source_image_flag=False) else: ref_pose_coeff_path=None #audio2ceoff batch = get_data(first_coeff_path, audio_path, device, ref_eyeblink_coeff_path, still=args.still) coeff_path = audio_to_coeff.generate(batch, save_dir, pose_style, ref_pose_coeff_path) # 3dface render if args.face3dvis: gen_composed_video(args, device, first_coeff_path, coeff_path, audio_path, os.path.join(save_dir, '3dface.mp4')) #coeff2video
# from src.facerender.animate import AnimateFromCoeff def main(args): #torch.backends.cudnn.enabled = False # tts_service = os.getenv("TTS_SERVER") facerender_batch_size = 10 startInference = time.time() pic_path = args.source_image audio_path = args.driven_audio save_dir = os.path.join(args.result_dir, strftime("%Y_%m_%d_%H.%M.%S")) os.makedirs(save_dir, exist_ok=True) pose_style = args.pose_style device = args.device batch_size = args.batch_size input_yaw_list = args.input_yaw input_pitch_list = args.input_pitch input_roll_list = args.input_roll ref_eyeblink = args.ref_eyeblink ref_pose = args.ref_pose current_root_path = os.path.split(sys.argv[0])[0] sadtalker_paths = init_path(args.checkpoint_dir, os.path.join(current_root_path, 'src/config'), args.size, args.old_version, args.preprocess) #init model preprocess_model = CropAndExtract(sadtalker_paths, device) audio_to_coeff = Audio2Coeff(sadtalker_paths, device) animate_from_coeff = AnimateFromCoeff(sadtalker_paths, device) #crop image and extract 3dmm from image first_frame_dir = os.path.join(save_dir, 'first_frame_dir') os.makedirs(first_frame_dir, exist_ok=True) print('3DMM Extraction for source image') first_coeff_path, crop_pic_path, crop_info = preprocess_model.generate(pic_path, first_frame_dir, args.preprocess,\ source_image_flag=True, pic_size=args.size) if first_coeff_path is None: print("Can't get the coeffs of the input") return if ref_eyeblink is not None: ref_eyeblink_videoname = os.path.splitext(os.path.split(ref_eyeblink)[-1])[0] ref_eyeblink_frame_dir = os.path.join(save_dir, ref_eyeblink_videoname) os.makedirs(ref_eyeblink_frame_dir, exist_ok=True) print('3DMM Extraction for the reference video providing eye blinking') ref_eyeblink_coeff_path, _, _ = preprocess_model.generate(ref_eyeblink, ref_eyeblink_frame_dir, args.preprocess, source_image_flag=False) else: ref_eyeblink_coeff_path=None if ref_pose is not None: if ref_pose == ref_eyeblink: ref_pose_coeff_path = ref_eyeblink_coeff_path else: ref_pose_videoname = os.path.splitext(os.path.split(ref_pose)[-1])[0] ref_pose_frame_dir = os.path.join(save_dir, ref_pose_videoname) os.makedirs(ref_pose_frame_dir, exist_ok=True) print('3DMM Extraction for the reference video providing pose') ref_pose_coeff_path, _, _ = preprocess_model.generate(ref_pose, ref_pose_frame_dir, args.preprocess, source_image_flag=False) else: ref_pose_coeff_path=None #audio2ceoff batch = get_data(first_coeff_path, audio_path, device, ref_eyeblink_coeff_path, still=args.still) coeff_path = audio_to_coeff.generate(batch, save_dir, pose_style, ref_pose_coeff_path) # 3dface render if args.face3dvis: gen_composed_video(args, device, first_coeff_path, coeff_path, audio_path, os.path.join(save_dir, '3dface.mp4')) #coeff2video
data = get_facerender_data(coeff_path, crop_pic_path, first_coeff_path, audio_path,
7
2023-11-25 06:53:12+00:00
16k
microsoft/Project-BayesDAG
src/causica/models/bayesdag/bayesdag_linear.py
[ { "identifier": "Variables", "path": "src/causica/datasets/variables.py", "snippet": "class Variables:\n \"\"\"\n This class represents any variables present in a model.\n \"\"\"\n\n def __init__(\n self,\n variables: List[Variable],\n auxiliary_variables: Optional[List[...
import torch from ...datasets.variables import Variables from .bayesdag_nonlinear import BayesDAGNonLinear
13,360
from __future__ import annotations class BayesDAGLinear(BayesDAGNonLinear): """ Approximate Bayesian inference over the graph in a Gaussian linear ANM based on the BayesDAG result. Any DAG G is represented as G = W * Step(grad (p)) where W is a discrete matrix W in {0, 1} ^ {d, d} and p in R^d. Inference over DAGs G then corresponds to inference over W and p as the transformation is determinstic. This can be converted to inference over W and p by using the Gumbel-Sinkhorn trick. """ def __init__( self, model_id: str,
from __future__ import annotations class BayesDAGLinear(BayesDAGNonLinear): """ Approximate Bayesian inference over the graph in a Gaussian linear ANM based on the BayesDAG result. Any DAG G is represented as G = W * Step(grad (p)) where W is a discrete matrix W in {0, 1} ^ {d, d} and p in R^d. Inference over DAGs G then corresponds to inference over W and p as the transformation is determinstic. This can be converted to inference over W and p by using the Gumbel-Sinkhorn trick. """ def __init__( self, model_id: str,
variables: Variables,
0
2023-11-21 12:55:08+00:00
16k
ChenyangGao/python-epub3
epub3/epub.py
[ { "identifier": "File", "path": "epub3/util/file.py", "snippet": "class File:\n __slots__ = (\"path\", \"fs\", \"open\", \"open_modes\", \"_getattr\")\n ALL_MODES = frozenset(\"rwxab+\")\n\n def __init__(\n self, \n /, \n path=None, \n fs=None, \n open_modes=N...
import errno import io import os import os.path as ospath import posixpath from copy import deepcopy from datetime import datetime from fnmatch import translate as wildcard_translate from functools import cached_property, partial from inspect import getfullargspec, isclass from io import IOBase, TextIOWrapper from operator import methodcaller from os import fsdecode, remove, stat, stat_result, PathLike from pathlib import PurePosixPath from posixpath import join as joinpath, normpath from pprint import pformat from re import compile as re_compile, escape as re_escape, Pattern from shutil import copy, copyfileobj from typing import cast, Any, Callable, Container, Mapping, MutableMapping, Optional from types import MappingProxyType from uuid import uuid4 from warnings import warn from weakref import WeakKeyDictionary, WeakValueDictionary from urllib.parse import quote, unquote from zipfile import ZipFile, ZIP_STORED from .util.file import File, RootFS, TemporaryFS, OPEN_MODES from .util.helper import guess_media_type, values, items, sup from .util.proxy import proxy_property, ElementAttribProxy, ElementProxy, NAMESPACES from .util.remap import remap_links from .util.stream import PyLinq from .util.xml import el_add, el_del, el_iterfind, el_set from .util.undefined import undefined, UndefinedType from lxml.etree import fromstring, tostring, _Element as Element, _ElementTree as ElementTree # type: ignore from xml.etree.ElementTree import fromstring, tostring, Element, ElementTree # type: ignore
13,902
elif isinstance(id_or_attrib, str): id = id_or_attrib itemref = super().get(id) if itemref is None: self.add(id, attrs) else: itemref.merge(attrs) else: self._proxy.merge(id_or_attrib, **attrs) elif isinstance(id_or_attrib, Mapping): self._proxy.merge(id_or_attrib) return self def update(self, id_or_attrib=None, /, **attrs): if isinstance(id_or_attrib, Item): id_or_attrib = id_or_attrib._attrib["id"] if attrs: if isinstance(id_or_attrib, Itemref): itemref = id_or_attrib if itemref not in self: raise LookupError(f"no such itemref: {itemref!r}") itemref.update(attrs) elif isinstance(id_or_attrib, str): id = id_or_attrib itemref = super().get(id) if itemref is None: self.add(id, attrs) else: itemref.update(attrs) else: self._proxy.update(id_or_attrib, **attrs) elif isinstance(id_or_attrib, Mapping): self._proxy.update(id_or_attrib) return self class ePub(ElementProxy): __protected_keys__ = ("unique-identifier", "version") __optional_keys__ = ("dir", "id", "prefix", "xml:lang") __cache_get_key__ = False def __init__( self, /, path=None, workroot=None, maketemp=True, generate_id=None, init_opf=None, ): if path and ospath.lexists(path): self._zfile = zfile = ZipFile(path) contenter_xml = zfile.read("META-INF/container.xml") match = fromstring(contenter_xml).find( '{*}rootfiles/{*}rootfile[@media-type="application/oebps-package+xml"][@full-path]', ) if match is None: raise FileNotFoundError(errno.ENOENT, "no opf file specified in container.xml") self._opf_path = opf_path = unquote(match.attrib["full-path"]) self._opf_dir, self._opf_name = opf_dir, _ = posixpath.split(opf_path) root = fromstring(zfile.read(opf_path)) else: self._opf_path = "OEBPS/content.opf" self._opf_dir = "OEBPS" self._opf_name = "content.opf" if init_opf is None: content_opf = b'''\ <?xml version="1.0" encoding="utf-8"?> <package version="3.0" unique-identifier="BookId" xmlns="http://www.idpf.org/2007/opf"> <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"> <dc:identifier id="BookId" opf:scheme="UUID">urn:uuid:%(uuid)s</dc:identifier> <dc:language>en</dc:language> <dc:title></dc:title> <meta property="dcterms:modified">%(mtime)s</meta> </metadata> <manifest /> <spine /> </package>''' % { b"uuid": bytes(str(uuid4()), "utf-8"), b"mtime": bytes(datetime.now().strftime("%FT%XZ"), "utf-8") } elif callable(init_opf): content_opf = init_opf() elif isinstance(init_opf, str): content_opf = bytes(init_opf, "utf-8") else: content_opf = init_opf root = fromstring(content_opf) super().__init__(root) self._path = path self._workroot = workroot self._maketemp = maketemp if generate_id is None: self._generate_id = None else: try: argcount = generate_id.__code__.co_argcount except AttributeError: argcount = len(getfullargspec(generate_id).args) if argcount == 0: self._generate_id = lambda href, seen_ids: generate_id() elif argcount == 1: self._generate_id = lambda href, seen_ids: generate_id(href) else: self._generate_id = generate_id self.metadata self.manifest self.spine def __del__(self): try: self._zfile.close() except: pass def __getattr__(self, attr, /): return getattr(self.manifest, attr) @cached_property def metadata(self, /):
#!/usr/bin/env python # coding: utf-8 __author__ = "ChenyangGao <https://chenyanggao.github.io>" __version__ = (0, 0, 1) __all__ = ["ePub", "Metadata", "DCTerm", "Meta", "Link", "Manifest", "Item", "Spine", "Itemref"] try: except ModuleNotFoundError: class DCTerm(ElementProxy): pass class Meta(ElementProxy): __protected_keys__ = ("property",) __optional_keys__ = ("dir", "id", "refines", "scheme", "xml:lang") class Link(ElementAttribProxy): __protected_keys__ = ("href", "rel") __optional_keys__ = ("hreflang", "id", "media-type", "properties", "refines") class Item(ElementAttribProxy): __const_keys__ = ("id",) __protected_keys__ = ("href", "media-type") __optional_keys__ = ("fallback", "media-overlay", "properties") __cache_get_state__ = lambda _, manifest: manifest def __init__(self, root: Element, manifest, /): super().__init__(root) self._manifest = manifest def __eq__(self, other, /): if type(self) is not type(other): return NotImplemented return self._manifest is other._manifest and self._attrib["href"] == other._attrib["href"] def __fspath__(self, /): return unquote(self._attrib["href"]) def __hash__(self, /): return hash((self._root, id(self._manifest))) def __setitem__(self, key, value, /): if key == "href": if value is None: raise ValueError("can't set href to None") self.rename(val) else: super().__setitem__(key, value) return self @property def filename(self, /): return PurePosixPath(joinpath(self.home, self)) @property def home(self, /): return PurePosixPath(self._manifest._epub._opf_dir) @property def name(self, /): return self.path.name @property def path(self, /): return PurePosixPath(self) @property def _parent(self, /): return posixpath.dirname(unquote(self._attrib["href"])) @property def parent(self, /): return self.path.parent @property def parents(self, /): return self.path.parents @property def parts(self, /): return self.path.parts @property def stem(self, /): return self.path.stem @property def suffix(self, /): return self.path.suffix @property def suffixes(self, /): return self.path.suffixes def update(self, attrib=None, /, **attrs): if attrib: attrib = dict(attrib) if attrs: attrib.update(attrs) else: attrib = attrs href = attrib.pop("href", None) if href: self.rename(href) if attrib: super().update(attrib) return self def is_relative_to(self, /, *other): return self.path.is_relative_to(*other) def joinpath(self, /, *others): return PurePosixPath(normpath(joinpath(self._parent, *others))) __truediv__ = joinpath def relpath(self, other, /): return PurePosixPath(posixpath.relpath(other, self._parent)) def relative_to(self, /, *other): return self.path.relative_to(*other) def with_name(self, /, name): return self.path.with_name(str(name)) def with_stem(self, /, stem): return self.path.with_stem(str(stem)) def with_suffix(self, /, suffix): return self.path.with_suffix(str(suffix)) def exists(self, /): return self._manifest.exists(self) def is_file(self, /): return self.exists() def is_dir(self, /): return False def is_symlink(self, /): return False def glob(self, /, pattern="*", ignore_case=False): return self._manifest.glob(pattern, self, ignore_case=ignore_case) def rglob(self, /, pattern="", ignore_case=False): return self._manifest.rglob(pattern, self, ignore_case=ignore_case) def iterdir(self, /): return self._manifest.iterdir(self) def match(self, /, path_pattern, ignore_case=False): path_pattern = path_pattern.strip("/") if not path_pattern: return False pattern = joinpath(*posix_glob_translate_iter(path_pattern)) if ignore_case: pattern = "(?i:%s)" % pattern return re_compile(pattern).fullmatch(self._attrib["href"]) is not None def open( self, /, mode="r", buffering=-1, encoding=None, errors=None, newline=None, ): return self._manifest.open( self, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) def read(self, /, buffering=0): return self._manifest.read(self, buffering=buffering) read_bytes = read def read_text(self, /, encoding=None): return self._manifest.read_text(self, encoding=encoding) def remove(self, /): self._manifest.remove(self) return self def rename(self, dest_href, /, repair=False): return self._manifest.rename(self, dest_href, repair=repair) def batch_rename(self, mapper, /, predicate=None, repair=False): return self._manifest.batch_rename(self, mapper, predicate=predicate, repair=repair) def replace(self, href, /): self._manifest.replace(self, href) return self def stat(self, /) -> Optional[stat_result]: return self._manifest.stat(self) def touch(self, /): self._manifest.touch(self) return self unlink = remove def write(self, /, data): return self._manifest.write(self, data) write_bytes = write def write_text(self, /, text, encoding=None, errors=None, newline=None): return self._manifest.write_text(self, text, encoding=encoding, errors=errors, newline=newline) class Itemref(ElementAttribProxy): __const_keys__ = ("idref",) __optional_keys__ = ("id", "linear", "properties") @property def linear(self, /): return "no" if self._attrib.get("linear") == "no" else "yes" @linear.setter def linear(self, value, /): self._attrib["linear"] = "no" if value == "no" else "yes" class Metadata(ElementProxy): __wrap_class_map__ = {"{*}meta": Meta, "{*}": Link, "dc:*": DCTerm} def __repr__(self, /): return f"{super().__repr__()}\n{pformat(self.iter().list())}" @property def info(self, /): return tuple(meta.info for meta in self.iter()) def add( self, name: str = "meta", /, attrib: Optional[Mapping] = None, text: Optional[str] = None, tail: Any = undefined, **_disregards, ): return super().add(name, attrib=attrib, text=text) def dc( self, name: str, text_value: UndefinedType | Optional[str] = undefined, /, find_attrib: Optional[Mapping] = None, attrib: Optional[Mapping] = None, text: Optional[str] = None, merge: bool = False, delete: bool = False, auto_add: bool = False, ): if text_value is not undefined: if find_attrib: find_attrib = {**find_attrib, "": text_value} else: find_attrib = {"": text_value} return self.setfind( "dc:%s" % name, find_attrib=find_attrib, attrib=attrib, text=text, merge=merge, delete=delete, auto_add=auto_add, ) def meta( self, preds: str = "", /, find_attrib: Optional[Mapping] = None, attrib: Optional[Mapping] = None, text: Optional[str] = None, merge: bool = False, delete: bool = False, auto_add: bool = False, ): return self.setfind( "{*}meta%s" % preds, find_attrib=find_attrib, attrib=attrib, text=text, merge=merge, delete=delete, auto_add=auto_add, ) def name_meta( self, name, content: Optional[str] = None, /, find_attrib: Optional[Mapping] = None, attrib: Optional[Mapping] = None, text: Optional[str] = None, merge: bool = False, delete: bool = False, auto_add: bool = False, ): if find_attrib: find_attrib = {**find_attrib, "name": name} else: find_attrib = {"name": name} if content is not None: find_attrib["content"] = content return self.meta( find_attrib=find_attrib, attrib=attrib, text=text, merge=merge, delete=delete, auto_add=auto_add, ) def property_meta( self, property, text_value: UndefinedType | Optional[str] = undefined, /, find_attrib: Optional[Mapping] = None, attrib: Optional[Mapping] = None, text: Optional[str] = None, merge: bool = False, delete: bool = False, auto_add: bool = False, ): if find_attrib: find_attrib = {**find_attrib, "property": property} else: find_attrib = {"property": property} if text_value is not undefined: find_attrib[""] = text_value return self.meta( find_attrib=find_attrib, attrib=attrib, text=text, merge=merge, delete=delete, auto_add=auto_add, ) class ManifestProxy(ElementAttribProxy): __optional_keys__ = ("id",) class Manifest(dict[str, Item]): def __init__(self, /, root: Element, epub): self._root = root self._attrib = root.attrib self._epub = epub self._proxy = ManifestProxy(root) self._href_to_id: dict[str, str] = {} self._href_to_file: dict[str, File] = {} if len(root): href_to_id = self._href_to_id dangling_items = [] for item in root.iterfind("{*}item"): id = item.attrib.get("id") href = item.attrib.get("href") if id is None or not href: dangling_items.append(item) continue id = cast(str, id) href = cast(str, unquote(href)) super().__setitem__(id, Item(item, self)) href_to_id[href] = id if dangling_items: for item in reversed(dangling_items): root.remove(item) warn(f"removed a dangling item element: {item!r}") zfile = epub.__dict__.get("_zfile") opf_dir = epub._opf_dir if zfile: href_to_file = self._href_to_file for href in href_to_id: zpath = joinpath(opf_dir, href) zinfo = zfile.NameToInfo.get(zpath) if not zinfo or zinfo.is_dir(): warn(f"missing file in original epub: {href!r}") href_to_file[href] = File(str(uuid4()), self._workfs) else: href_to_file[href] = File(zpath, zfile, open_modes="r") def __init_subclass__(self, /, **kwargs): raise TypeError("subclassing is not allowed") def __call__(self, href, /): if isinstance(href, Item): if href not in self: raise LookupError(f"no such item: {href!r}") return href if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" try: id = self._href_to_id[href] except LookupError as e: raise FileNotFoundError(errno.ENOENT, f"no such file: {href!r}") from e return super().__getitem__(id) def __contains__(self, other, /): if isinstance(other, Item): return other._manifest is self and super().__contains__(other["id"]) return super().__contains__(other) def __delitem__(self, key, /): pop = self.pop if isinstance(key, int): el = self._root[key] try: id = el.attrib["id"] except AttributeError: try: self._root.remove(el) except: pass else: pop(id) elif isinstance(key, slice): root = self._root for el in root[key]: try: id = el.attrib["id"] except AttributeError: try: root.remove(el) except: pass else: pop(id, None) elif isinstance(key, Item): if key not in self: raise LookupError(f"no such item: {key!r}") pop(key["id"]) elif isinstance(key, str): pop(key) else: raise TypeError("`key` only accepts: `str`, `int`, `slice`, `Item`") return self def __getitem__(self, key, /): def wrap(el): try: if el.tag == "item" or el.tag.endswith("}item"): return Item(el, self) return ElementProxy(el) except AttributeError: return el if isinstance(key, int): return wrap(self._root[key]) elif isinstance(key, slice): return list(map(wrap, self._root[key])) elif isinstance(key, Item): if key not in self: raise LookupError(f"no such item: {key!r}") return key elif isinstance(key, str): return super().__getitem__(key) else: raise TypeError("`key` only accepts: `str`, `int`, `slice`, `Item`") def __setitem__(self, id, value, /): if id not in self: raise LookupError(f"no such item: {id!r}") if isinstance(id, Item): item = id else: item = super().__getitem__(id) href = unquote(item._attrib["href"]) if isinstance(value, str): self.rename(href, value) elif isinstance(value, bytes): self.write(href, value) elif isinstance(value, Mapping): if "open" in value and callable(value["open"]): self._href_to_file[href] = File(value, open_modes="rb") else: item.update(value) else: self._href_to_file[href] = File(value, open_modes="rb") return self @cached_property def _workfs(self, /): if self._epub._maketemp: return TemporaryFS(self._epub._workroot) else: return RootFS(self._epub._workroot) @cached_property def href_to_id(self, /): return MappingProxyType(self._href_to_id) @cached_property def href_to_file(self, /): return MappingProxyType(self._href_to_file) @property def home(self, /): return self._epub._opf_dir @property def attrib(self, /): return self._attrib @property def proxy(self, /): return self._proxy @property def info(self, /): return tuple(item.info for item in self.values()) delete = __delitem__ def clear(self, /): self._root.clear() self._href_to_file.clear() self._href_to_id.clear() super().clear() return self def pop(self, id, /, default=undefined): if id not in self: if default is undefined: raise LookupError(f"no such item: {id!r}") return default if isinstance(id, Item): id = id["id"] item = super().pop(id) try: self._root.remove(item._root) except: pass href = unquote(item._attrib["href"]) self._href_to_id.pop(href, None) file = self._href_to_file.pop(href, None) if file is not None and file.check_open_mode("w"): try: file.remove() except: pass return item def popitem(self, /): id, item = super().popitem() try: self._root.remove(item._root) except: pass href = unquote(item._attrib["href"]) self._href_to_id.pop(href, None) file = self._href_to_file.pop(href, None) if file is not None and file.check_open_mode("w"): try: file.remove() except: pass return id, item def set(self, id, value, /): if isinstance(id, Item): if id not in self: raise LookupError(f"no such item: {id!r}") item = id else: item = super().get(id) if item is None: if isinstance(value, str): item = self.add(href, id=id) elif isinstance(value, Mapping) and "href" in value: if "open" in value and callable(value["open"]): item = self.add(value["href"], value, id=id) else: item = self.add(value["href"], id=id, attrib=value) else: raise LookupError(f"no such item: {id!r}") else: href = unquote(item._attrib["href"]) if isinstance(value, str): self.rename(href, value) elif isinstance(value, bytes): self.write(href, value) elif isinstance(value, Mapping): if "open" in value and callable(value["open"]): self._href_to_file[href] = File(value, open_modes="rb") else: item.update(value) else: self._href_to_file[href] = File(value, open_modes="rb") return item def setdefault(self, id, value, /): if isinstance(id, Item): if id not in self: raise LookupError(f"no such item: {id!r}") item = id else: item = super().get(id) if item is None: if isinstance(value, str): item = self.add(value, id=id) elif isinstance(value, Mapping) and "href" in value: if "open" in value and callable(value["open"]): item = self.add(value["href"], value, id=id) else: item = self.add(value["href"], id=id, attrib=value) else: raise LookupError(f"no such item: {id!r}") else: if isinstance(value, Mapping) and not ("open" in value and callable(value["open"])): item.merge(value) return item def merge(self, id_or_attrib=None, /, **attrs): if attrs: if isinstance(id_or_attrib, Item): item = id_or_attrib if item not in self: raise LookupError(f"no such item: {item!r}") item.merge(attrib=attrs) elif isinstance(id_or_attrib, str): id = id_or_attrib item = super().get(id) if item is None: if "href" in attrs: href = attrs.pop("href") self.add(href, id=id, attrib=attrs) else: raise LookupError(f"no such item: {id!r}") else: item.merge(attrs) else: self._proxy.merge(id_or_attrib, **attrs) elif isinstance(id_or_attrib, Mapping): self._proxy.merge(id_or_attrib) return self def update(self, id_or_attrib=None, /, **attrs): if attrs: if isinstance(id_or_attrib, Item): item = id_or_attrib if item not in self: raise LookupError(f"no such item: {item!r}") item.update(attrib=attrs) elif isinstance(id_or_attrib, str): id = id_or_attrib item = super().get(id) if item is None: if "href" in attrs: href = attrs.pop("href") self.add(href, id=id, attrib=attrs) else: raise LookupError(f"no such item: {id!r}") else: item.update(attrs) else: self._proxy.update(id_or_attrib, **attrs) elif isinstance(id_or_attrib, Mapping): self._proxy.update(id_or_attrib) return self #################### SubElement Methods #################### @PyLinq.streamify def filter(self, /, predicate=None): if not callable(predicate): return iter(self.values()) return filter(predicate, self.values()) @PyLinq.streamify def filter_by_attr(self, predicate=None, attr="media-type", /): def activate_predicate(predicate): if predicate is None: return None if callable(predicate): return predicate elif isinstance(predicate, Pattern): return predicate.search elif isinstance(predicate, str): use_false = False if predicate.startswith(r"!"): use_false = True predicate = predicate[1:] predicate_startswith = predicate.startswith if predicate_startswith(r"="): predicate = predicate[1:].__eq__ elif predicate_startswith(r"~"): predicate = methodcaller("__contains__", predicate[1:]) elif predicate_startswith(r"^"): predicate = methodcaller("startswith", predicate[1:]) elif predicate_startswith(r"$"): predicate = methodcaller("endswith", predicate[1:]) elif predicate_startswith(r";"): predicate = lambda s, needle=predicate[1:]: needle in s.split() elif predicate_startswith(r","): predicate = lambda s, needle=predicate[1:]: needle in s.split(",") elif predicate_startswith(r"<"): predicate = re_compile(r"\b"+re_escape(predicate[1:])).search elif predicate_startswith(r">"): predicate = re_compile(re_escape(predicate[1:])+r"\b").search elif predicate_startswith(r"|"): predicate = re_compile(r"\b"+re_escape(predicate[1:])+r"\b").search elif predicate_startswith(r"*"): predicate = re_compile(wildcard_translate(predicate[1:])).fullmatch elif predicate_startswith(r"/"): predicate = re_compile(predicate[1:]).search elif predicate_startswith(r"%"): predicate = re_compile(predicate[1:]).fullmatch else: predicate = predicate.__eq__ if use_false: predicate = lambda s, _pred=predicate: not _pred(s) return predicate elif type(predicate) in (tuple, list): preds = tuple(pred for p in predicate if (pred:=activate_predicate(p)) is not None) if not preds: return None if type(predicate) is tuple: return lambda s, _preds=preds: any(p(s) for p in preds) else: return lambda s, _preds=preds: all(p(s) for p in preds) elif isinstance(predicate, Container): return predicate.__contains__ predicate = activate_predicate(predicate) if predicate is None: return filter(lambda item: attr in item, self.values()) return filter(lambda item: attr in item and predicate(item[attr]), self.values()) @PyLinq.streamify def iter(self, /): root = self._root for el in root.iterfind("*"): if not (el.tag == "item" or el.tag.endswith("}item")): yield ElementProxy(el) continue id = el.attrib.get("id") href = el.attrib.get("href") if not href: if id is None or not super().__contains__(id): try: root.remove(el) warn(f"removed a dangling item element: {el!r}") except: pass else: item = super().__getitem__(id) if item._root is not el: raise RuntimeError(f"different item elements {el!r} and {item._root!r} share the same id {id!r}") else: self.pop(id, None) warn(f"removed an item because of missing href attribute: {item!r}") continue href = unquote(href) if not el.attrib.get("media-type"): el.attrib["media-type"] = guess_media_type(href) if id is None: yield self.add(href) elif super().__contains__(id): item = super().__getitem__(id) if item._root is not el: raise RuntimeError(f"different item elements {el!r} and {item._root!r} share the same id {id!r}") yield item else: try: self._root.remove(el) warn(f"removed a dangling item element: {el!r}") except: pass def list(self, /, mapfn=None): if mapfn is None: return list(self.iter()) return list(map(mapfn, self.iter())) def audio_iter(self, /): return self.filter_by_attr("^audio/") def css_iter(self, /): return self.filter_by_attr("text/css") def font_iter(self, /): return self.filter_by_attr(("^font/", "^application/font-")) def image_iter(self, /): return self.filter_by_attr("^image/") def javascript_iter(self, /): return self.filter_by_attr(("text/javascript", "application/javascript", "application/ecmascript")) def media_iter(self, /): return self.filter_by_attr(("^audio/", "^image/", "^video/")) def text_iter(self, /): return self.filter_by_attr(("^text/", "$+xml")) def video_iter(self, /): return self.filter_by_attr("^video/") @PyLinq.streamify def html_item_ref_pair_iter(self, /): spine = self._epub.spine for id, itemref in spine.items(): yield self[id], itemref for item in self.filter_by_attr(("text/html", "application/xhtml+xml")): if item["id"] in spine: continue yield item, None #################### File System Methods #################### def add( self, href, /, file=None, fs=None, open_modes="r", id=None, media_type=None, attrib=None, ): if isinstance(href, Item): raise TypeError("can't directly add `Item` object") if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" if href in self._href_to_id: raise FileExistsError(errno.EEXIST, f"file exists: {href!r}") uid = str(uuid4()) if id is None: generate_id = self._epub._generate_id if generate_id is None: id = uid else: keys = self.keys() id = generate_id(href, keys) while id in keys: nid = generate_id(href, keys) if nid == id: i = sup(lambda i: f"{i}_{nid}" in keys) id = f"{i}_{nid}" break id = nid if id in self: raise LookupError(f"id already exists: {id!r}") attrib = dict(attrib) if attrib else {} attrib["id"] = id attrib["href"] = quote(href, safe=":/?&=#") if media_type: attrib["media-type"] = media_type if fs is not None: file = File(file, fs=fs, open_modes=open_modes) elif file is None: file = File(uid, self._workfs) elif isinstance(file, IOBase) or hasattr(file, "read") and not hasattr(file, "open"): file0 = file file = File(uid, self._workfs) test_data = file0.read(0) if test_data == b"": copyfileobj(file0, self._workfs.open(uid, "wb")) elif test_data == "": attrib.setdefault("media-type", "text/plain") copyfileobj(file0, self._workfs.open(uid, "w")) else: raise TypeError(f"incorrect read behavior: {file0!r}") else: file = File(file, open_modes=open_modes) if not attrib.get("media-type"): attrib["media-type"] = guess_media_type(href) item = Item(el_add(self._root, "item", attrib=attrib, namespaces=NAMESPACES), self) super().__setitem__(id, item) self._href_to_id[href] = id self._href_to_file[href] = file return item def change( self, href, /, file=None, fs=None, open_modes="r", id=None, media_type=None, attrib=None, ): if fs is self._workfs: raise OSError(errno.EINVAL, f"Remapping the file that in the working fs is not supported, use `rename` instead: {fs!r}") if href in self.href_to_id: item = self[self.href_to_id[href]] if attrib: item.update(attrib) if media_type: item.media_type = media_type try: self.href_to_file[href].remove() except: pass self._href_to_file[href] = File(file, fs, open_modes) return item else: return self.add( href, file=file, fs=fs, open_modes=open_modes, id=id, media_type=media_type, attrib=attrib, ) def exists(self, href, /): if isinstance(href, Item): return href in self if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" return href in self._href_to_id @PyLinq.streamify def glob(self, pattern="*", dirname="", ignore_case=False): pattern = pattern.strip("/") if not pattern: return if isinstance(dirname, Item): dirname = posixpath.dirname(unquote(href._attrib["href"])) else: dirname = dirname.strip("/") if dirname: dirname = re_escape(dirname) pattern = joinpath(dirname, *posix_glob_translate_iter(pattern)) if ignore_case: pattern = "(?i:%s)" % pattern matches = re_compile(pattern).fullmatch for href, id in self._href_to_id.items(): if not matches(href): continue try: yield super().__getitem__(id) except KeyError: pass @PyLinq.streamify def iterdir(self, /, dirname=""): if isinstance(dirname, Item): dirname = posixpath.dirname(unquote(href._attrib["href"])) else: dirname = dirname.strip("/") for href, id in self._href_to_id.items(): if posixpath.dirname(href) != dirname: continue try: yield super().__getitem__(id) except KeyError: pass def open( self, href, /, mode="r", buffering=-1, encoding=None, errors=None, newline=None, ): if mode not in OPEN_MODES: raise ValueError(f"invalid open mode: {mode!r}") if isinstance(href, Item): if href not in self: raise LookupError(f"no such item: {href!r}") href = unquote(href["href"]) else: if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" href_to_file = self._href_to_file if href in self._href_to_id: if "x" in mode: raise FileExistsError(errno.EEXIST, f"file exists: {href!r}") file = href_to_file.get(href) uid = str(uuid4()) if file is None: href_to_file[href] = file = File(uid, self._workfs) elif not file.check_open_mode(mode): if "w" not in mode: try: fsrc = file.open("rb", buffering=0) except FileNotFoundError: if "r" in mode: raise else: with fsrc: copyfileobj(fsrc, self._workfs.open(uid, "wb")) href_to_file[href] = file = File(uid, self._workfs) elif "r" in mode: raise FileNotFoundError(errno.ENOENT, f"no such file: {href!r}") else: item = self.add(href) file = href_to_file[href] if "b" not in mode and encoding is None: encoding = "utf-8" return file.open( mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, ) def read(self, href, /, buffering=0): with self.open(href, "rb", buffering=buffering) as f: return f.read() read_bytes = read def read_text(self, href, /, encoding=None): with self.open(href, "r", encoding=encoding) as f: return f.read() def remove(self, href, /): if isinstance(href, Item): if href not in self: raise LookupError(f"no such item: {href!r}") href = unquote(href["href"]) else: if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" try: id = self._href_to_id.pop(href) except LookupError: raise FileNotFoundError(errno.ENOENT, f"no such file: {href!r}") item = super().pop(id, None) if item is not None: try: self._root.remove(item._root) except: pass file = self._href_to_file.pop(href, None) if file is not None and file.check_open_mode("w"): try: file.remove() except: pass def _rename(self, item, href, dest_href, /): try: id = self._href_to_id[dest_href] = self._href_to_id.pop(href) except LookupError: raise FileNotFoundError(errno.ENOENT, f"no such file: {href!r}") if item is None: item = super().__getitem__(id) item._attrib["href"] = quote(dest_href, safe=":/?&=#") self._href_to_file[dest_href] = self._href_to_file.pop(href, None) def rename(self, href, dest_href, /, repair=False): result = {} if isinstance(href, Item): item = href if item not in self: raise LookupError(f"no such item: {item!r}") href = unquote(item._attrib["href"]) else: if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" item = None if isinstance(dest_href, (bytes, PathLike)): dest_href = fsdecode(dest_href) else: dest_href = str(dest_href) assert (dest_href := dest_href.strip("/")), "empty href" result["pathpair"] = (href, dest_href) if href != dest_href: if dest_href in self._href_to_id: raise FileExistsError(errno.EEXIST, f"target file exists: {dest_href!r}") self._rename(item, href, dest_href) if repair: result["repairs"] = remap_links(self, (href, dest_href)) return result def batch_rename(self, mapper, /, predicate=None, repair=False): result = {} result["pathmap"] = pathmap = {} result["fails"] = fails = {} if not callable(mapper) and isinstance(mapper, Mapping): def mapper(item, m=mapper): href = unquote(item["href"]) try: return m[href] except LookupError: return href if predicate is None: predicate = mapper if not callable(predicate) and isinstance(predicate, Mapping): predicate = lambda item, m=predicate: unquote(item["href"]) in m for item in self.filter(predicate): try: href, dest_href = self.rename(item, mapper(item))["pathpair"] if href != dest_href: pathmap[href] = dest_href except Exception as e: fails[unquote(item._attrib["href"])] = e if pathmap and repair: result["repairs"] = remap_links(self, pathmap) return result def replace(self, href, dest_href, /): if isinstance(href, Item): item = href if item not in self: raise LookupError(f"no such item: {item!r}") href = unquote(item._attrib["href"]) else: if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" if href not in self._href_to_id: raise FileNotFoundError(errno.ENOENT, f"no such file: {href!r}") item = None if isinstance(dest_href, Item): dest_item = dest_href if dest_item not in self: raise LookupError(f"no such item: {dest_item!r}") dest_href = unquote(dest_item["href"]) else: if isinstance(dest_href, (bytes, PathLike)): dest_href = fsdecode(dest_href) else: dest_href = str(dest_href) assert (dest_href := dest_href.strip("/")), "empty href" dest_item = None if href == dest_href: return if dest_item is not None: del self[dest_item] elif dest_href in self._href_to_id: del self[self._href_to_id[dest_href]] self._rename(item, href, dest_href) def rglob(self, pattern="", dirname="", ignore_case=False): if pattern: pattern = joinpath("**", pattern.lstrip("/")) else: pattern = "**" return self.glob(pattern, dirname, ignore_case) def stat(self, href, /) -> Optional[stat_result]: if isinstance(href, Item): if href not in self: raise LookupError(f"no such item: {href!r}") href = unquote(href["href"]) else: if isinstance(href, (bytes, PathLike)): href = fsdecode(href) else: href = str(href) assert (href := href.strip("/")), "empty href" if href not in self._href_to_id: raise FileNotFoundError(errno.ENOENT, f"no such file: {href!r}") try: stat = self._href_to_file[href].stat except (AttributeError, LookupError): return None if callable(stat): return stat() return None def touch(self, href, /): try: self.open(href, "rb", buffering=0).close() except: self.open(href, "wb", buffering=0).close() unlink = remove def write(self, href, /, data): need_close = True if isinstance(data, File): fsrc = data.open("rb", buffering=0) elif callable(getattr(data, "read", None)): fsrc = data need_close = False elif isinstance(data, (str, PathLike)): fsrc = open(data, "rb", buffering=0) else: content = memoryview(data) with self.open(href, "wb") as f: return f.write(content) try: fsrc_read = fsrc.read test_data = fsrc_read(0) if test_data == "": fsrc_read = lambda n, read=fsrc_read: bytes(read(n), "utf-8") elif test_data: raise TypeError(f"incorrect read behavior: {fsrc!r}") with self.open(href, "wb") as fdst: fdst_write = fdst.write n = 0 while (buf := fsrc_read(1 << 16)): n += fdst_write(buf) return n finally: if need_close: fsrc.close() write_bytes = write def write_text(self, href, /, text, encoding=None, errors=None, newline=None): with self.open(href, "w", encoding=encoding, errors=errors, newline=newline) as f: return f.write(text) class SpineProxy(ElementAttribProxy): __optional_keys__ = ("id", "page-progression-direction") class Spine(dict[str, Itemref]): def __init__(self, root: Element, /, manifest: Manifest): self._root = root self._attrib = root.attrib self._proxy = SpineProxy(root) self._manifest = manifest if len(root): dangling_itemrefs = [] for itemref in root.iterfind("{*}itemref"): idref = itemref.attrib.get("idref") if idref is None or idref not in manifest: dangling_itemrefs.append(itemref) continue super().__setitem__(cast(str, idref), Itemref(itemref)) if dangling_itemrefs: for itemref in reversed(dangling_itemrefs): warn(f"removed a dangling item element: {itemref!r}") root.remove(itemref) def __init_subclass__(self, /, **kwargs): raise TypeError("subclassing is not allowed") def __call__(self, id, /, attrib=None): if isinstance(id, Item): id = id._attrib["id"] if isinstance(id, Itemref): if id not in self: raise LookupError(f"no such itemref: {id!r}") itemref = id else: itemref = super().get(id) if not attrib: return itemref if itemref is None: if id not in self._manifest: raise LookupError(f"no such item: {id!r}") itemref = self._add(id, attrib) else: itemref.update(attrib) return itemref def __contains__(self, id, /): if isinstance(id, Itemref): return super().get(id._attrib["idref"]) is id return super().__contains__(id) def __delitem__(self, key, /): pop = self.pop if isinstance(key, Itemref): if key not in self: raise LookupError(f"no such itemref: {key!r}") key = key._attrib["idref"] elif isinstance(key, Item): key = key._attrib["id"] if isinstance(key, str): pop(key, None) elif isinstance(key, int): el = self._root[key] try: id = el.attrib["idref"] except AttributeError: try: self._root.remove(el) except: pass else: pop(id) elif isinstance(key, slice): root = self._root for el in root[key]: try: id = el.attrib["idref"] except AttributeError: try: root.remove(el) except: pass else: pop(id, None) else: raise TypeError("`key` only accepts: `str`, `int`, `slice`, `Item`, `Itemref`") return self def __getitem__(self, key, /): def wrap(el): try: if el.tag == "itemref" or el.tag.endswith("}itemref"): return Itemref(el) return ElementProxy(el) except AttributeError: return el if isinstance(key, Itemref): if key not in self: raise LookupError(f"no such itemref: {key!r}") return key if isinstance(key, Item): key = key._attrib["id"] if isinstance(key, str): return super().__getitem__(key) elif isinstance(key, int): return wrap(self._root[key]) elif isinstance(key, slice): return list(map(wrap, self._root[key])) else: raise TypeError("`key` only accepts: `str`, `int`, `slice`, `Item`, `Itemref`") def __setitem__(self, id, attrib, /): if isinstance(key, Item): key = key._attrib["id"] if isinstance(key, Itemref): if key not in self: raise LookupError(f"no such itemref: {key!r}") itemref = key else: itemref = super().get(id) if itemref is None: self.add(key, attrib=attrib) else: itemref.update(attrib) return self @property def attrib(self, /): return self._attrib @property def manifest(self, /): return self._manifest @property def proxy(self, /): return self._proxy @property def info(self, /): return tuple(itemref.info for itemref in self.values()) delete = __delitem__ def _add(self, id, /, attrib=None): if attrib: attrib = dict(attrib, idref=id) else: attrib = {"idref": id} itemref = Itemref(el_add(self._root, "itemref", attrib=attrib, namespaces=NAMESPACES)) super().__setitem__(id, itemref) return itemref def add(self, id, /, attrib=None): if isinstance(id, Itemref): raise TypeError("can't directly add `Itemref` object") if isinstance(id, Item): id = id._attrib["id"] elif id not in self._manifest: raise LookupError(f"no such id in manifest: {id!r}") if super().__contains__(id): raise LookupError(f"id already exists: {id!r}") return self._add(id, attrib) def clear(self, /): self._root.clear() super().clear() return self @PyLinq.streamify def iter(self, /): root = self._root for el in root.iterfind("*"): if not (el.tag == "itemref" or el.tag.endswith("}itemref")): yield ElementProxy(el) continue idref = el.attrib.get("idref") if idref is None or idref not in self._manifest: try: root.remove(el) warn(f"removed a dangling itemref element: {el!r}") except: pass elif idref not in self: itemref = self._add(idref) yield itemref else: itemref = self[idref] if itemref._root is not el: raise RuntimeError(f"different itemref elements {el!r} and {itemref._root!r} share the same id {idref!r}") yield itemref def list(self, /, mapfn=None): if mapfn is None: return list(self.iter()) return list(map(mapfn, self.iter())) def pop(self, id, /, default=undefined): if isinstance(id, Item): id = id._attrib["id"] if isinstance(id, Itemref): if id not in self: if default is undefined: raise LookupError(f"no such itemref: {id!r}") return default itemref = id super().__delitem__(itemref._attrib["idref"]) else: if id not in self: if default is undefined: raise LookupError(f"no such itemref: {id!r}") return default itemref = super().pop(id) try: self._root.remove(itemref._root) except: pass return itemref def popitem(self, /): id, itemref = super().popitem() try: self._root.remove(itemref._root) except: pass return id, itemref def set(self, id, /, attrib=None): if isinstance(id, Item): id = id._attrib["id"] if isinstance(id, Itemref): if id not in self: raise LookupError(f"no such itemref: {id!r}") itemref = id else: itemref = super().get(id) if itemref is None: return self.add(id, attrib) itemref.update(attrib) return itemref def setdefault(self, id, /, attrib=None): if isinstance(id, Item): id = id._attrib["id"] if isinstance(id, Itemref): if id not in self: raise LookupError(f"no such itemref: {id!r}") itemref = id else: itemref = super().get(id) if itemref is None: return self.add(id, attrib) itemref.merge(attrib) return itemref def merge(self, id_or_attrib=None, /, **attrs): if isinstance(id_or_attrib, Item): id_or_attrib = id_or_attrib._attrib["id"] if attrs: if isinstance(id_or_attrib, Itemref): itemref = id_or_attrib if itemref not in self: raise LookupError(f"no such itemref: {itemref!r}") itemref.merge(attrs) elif isinstance(id_or_attrib, str): id = id_or_attrib itemref = super().get(id) if itemref is None: self.add(id, attrs) else: itemref.merge(attrs) else: self._proxy.merge(id_or_attrib, **attrs) elif isinstance(id_or_attrib, Mapping): self._proxy.merge(id_or_attrib) return self def update(self, id_or_attrib=None, /, **attrs): if isinstance(id_or_attrib, Item): id_or_attrib = id_or_attrib._attrib["id"] if attrs: if isinstance(id_or_attrib, Itemref): itemref = id_or_attrib if itemref not in self: raise LookupError(f"no such itemref: {itemref!r}") itemref.update(attrs) elif isinstance(id_or_attrib, str): id = id_or_attrib itemref = super().get(id) if itemref is None: self.add(id, attrs) else: itemref.update(attrs) else: self._proxy.update(id_or_attrib, **attrs) elif isinstance(id_or_attrib, Mapping): self._proxy.update(id_or_attrib) return self class ePub(ElementProxy): __protected_keys__ = ("unique-identifier", "version") __optional_keys__ = ("dir", "id", "prefix", "xml:lang") __cache_get_key__ = False def __init__( self, /, path=None, workroot=None, maketemp=True, generate_id=None, init_opf=None, ): if path and ospath.lexists(path): self._zfile = zfile = ZipFile(path) contenter_xml = zfile.read("META-INF/container.xml") match = fromstring(contenter_xml).find( '{*}rootfiles/{*}rootfile[@media-type="application/oebps-package+xml"][@full-path]', ) if match is None: raise FileNotFoundError(errno.ENOENT, "no opf file specified in container.xml") self._opf_path = opf_path = unquote(match.attrib["full-path"]) self._opf_dir, self._opf_name = opf_dir, _ = posixpath.split(opf_path) root = fromstring(zfile.read(opf_path)) else: self._opf_path = "OEBPS/content.opf" self._opf_dir = "OEBPS" self._opf_name = "content.opf" if init_opf is None: content_opf = b'''\ <?xml version="1.0" encoding="utf-8"?> <package version="3.0" unique-identifier="BookId" xmlns="http://www.idpf.org/2007/opf"> <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf"> <dc:identifier id="BookId" opf:scheme="UUID">urn:uuid:%(uuid)s</dc:identifier> <dc:language>en</dc:language> <dc:title></dc:title> <meta property="dcterms:modified">%(mtime)s</meta> </metadata> <manifest /> <spine /> </package>''' % { b"uuid": bytes(str(uuid4()), "utf-8"), b"mtime": bytes(datetime.now().strftime("%FT%XZ"), "utf-8") } elif callable(init_opf): content_opf = init_opf() elif isinstance(init_opf, str): content_opf = bytes(init_opf, "utf-8") else: content_opf = init_opf root = fromstring(content_opf) super().__init__(root) self._path = path self._workroot = workroot self._maketemp = maketemp if generate_id is None: self._generate_id = None else: try: argcount = generate_id.__code__.co_argcount except AttributeError: argcount = len(getfullargspec(generate_id).args) if argcount == 0: self._generate_id = lambda href, seen_ids: generate_id() elif argcount == 1: self._generate_id = lambda href, seen_ids: generate_id(href) else: self._generate_id = generate_id self.metadata self.manifest self.spine def __del__(self): try: self._zfile.close() except: pass def __getattr__(self, attr, /): return getattr(self.manifest, attr) @cached_property def metadata(self, /):
return Metadata(el_set(self._root, "{*}metadata", "metadata", attrib={
17
2023-11-20 14:46:41+00:00
16k
ymp5078/AI-SAM
segment_anything/automatic_mask_generator.py
[ { "identifier": "Sam", "path": "segment_anything/modeling/sam.py", "snippet": "class Sam(nn.Module):\n mask_threshold: float = 0.0\n image_format: str = \"RGB\"\n\n def __init__(\n self,\n image_encoder: ImageEncoderViT,\n prompt_encoder: PromptEncoder,\n mask_decode...
import numpy as np import torch import cv2 # type: ignore # noqa: F401 from torchvision.ops.boxes import batched_nms, box_area # type: ignore from typing import Any, Dict, List, Optional, Tuple from .modeling import Sam from .predictor import SamPredictor from .utils.amg import ( MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh, build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes, is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy, uncrop_masks, uncrop_points, ) from pycocotools import mask as mask_utils # type: ignore # noqa: F401
11,119
# Crop the image and calculate embeddings x0, y0, x1, y1 = crop_box cropped_im = image[y0:y1, x0:x1, :] cropped_im_size = cropped_im.shape[:2] self.predictor.set_image(cropped_im) # Get points for this crop points_scale = np.array(cropped_im_size)[None, ::-1] points_for_image = self.point_grids[crop_layer_idx] * points_scale # Generate masks for this crop in batches data = MaskData() for (points,) in batch_iterator(self.points_per_batch, points_for_image): batch_data = self._process_batch( points, cropped_im_size, crop_box, orig_size ) data.cat(batch_data) del batch_data self.predictor.reset_image() # Remove duplicates within this crop. keep_by_nms = batched_nms( data["boxes"].float(), data["iou_preds"], torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Return to the original image frame data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) data["points"] = uncrop_points(data["points"], crop_box) data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) return data def _process_batch( self, points: np.ndarray, im_size: Tuple[int, ...], crop_box: List[int], orig_size: Tuple[int, ...], ) -> MaskData: orig_h, orig_w = orig_size # Run model on this batch transformed_points = self.predictor.transform.apply_coords(points, im_size) in_points = torch.as_tensor(transformed_points, device=self.predictor.device) in_labels = torch.ones( in_points.shape[0], dtype=torch.int, device=in_points.device ) masks, iou_preds, _ = self.predictor.predict_torch( in_points[:, None, :], in_labels[:, None], multimask_output=True, return_logits=True, ) # Serialize predictions and store in MaskData data = MaskData( masks=masks.flatten(0, 1), iou_preds=iou_preds.flatten(0, 1), points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), ) del masks # Filter by predicted IoU if self.pred_iou_thresh > 0.0: keep_mask = data["iou_preds"] > self.pred_iou_thresh data.filter(keep_mask) # Calculate stability score data["stability_score"] = calculate_stability_score( data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset, ) if self.stability_score_thresh > 0.0: keep_mask = data["stability_score"] >= self.stability_score_thresh data.filter(keep_mask) # Threshold masks and calculate boxes data["masks"] = data["masks"] > self.predictor.model.mask_threshold data["boxes"] = batched_mask_to_box(data["masks"]) # Filter boxes that touch crop boundaries keep_mask = ~is_box_near_crop_edge( data["boxes"], crop_box, [0, 0, orig_w, orig_h] ) if not torch.all(keep_mask): data.filter(keep_mask) # Compress to RLE data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) data["rles"] = mask_to_rle_pytorch(data["masks"]) del data["masks"] return data @staticmethod def postprocess_small_regions( mask_data: MaskData, min_area: int, nms_thresh: float ) -> MaskData: """ Removes small disconnected regions and holes in masks, then reruns box NMS to remove any new duplicates. Edits mask_data in place. Requires open-cv as a dependency. """ if len(mask_data["rles"]) == 0: return mask_data # Filter small disconnected regions and holes new_masks = [] scores = [] for rle in mask_data["rles"]: mask = rle_to_mask(rle)
# -*- coding: utf-8 -*- # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class SamAutomaticMaskGenerator: def __init__( self, model: Sam, points_per_side: Optional[int] = 32, points_per_batch: int = 64, pred_iou_thresh: float = 0.88, stability_score_thresh: float = 0.95, stability_score_offset: float = 1.0, box_nms_thresh: float = 0.7, crop_n_layers: int = 0, crop_nms_thresh: float = 0.7, crop_overlap_ratio: float = 512 / 1500, crop_n_points_downscale_factor: int = 1, point_grids: Optional[List[np.ndarray]] = None, min_mask_region_area: int = 0, output_mode: str = "binary_mask", ) -> None: """ Using a SAM model, generates masks for the entire image. Generates a grid of point prompts over the image, then filters low quality and duplicate masks. The default settings are chosen for SAM with a ViT-H backbone. Arguments: model (Sam): The SAM model to use for mask prediction. points_per_side (int or None): The number of points to be sampled along one side of the image. The total number of points is points_per_side**2. If None, 'point_grids' must provide explicit point sampling. points_per_batch (int): Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. pred_iou_thresh (float): A filtering threshold in [0,1], using the model's predicted mask quality. stability_score_thresh (float): A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (float): The amount to shift the cutoff when calculated the stability score. box_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks. crop_n_layers (int): If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crop_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. crop_overlap_ratio (float): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (int): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. point_grids (list(np.ndarray) or None): A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. min_mask_region_area (int): If >0, postprocessing will be applied to remove disconnected regions and holes in masks with area smaller than min_mask_region_area. Requires opencv. output_mode (str): The form masks are returned in. Can be 'binary_mask', 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. For large resolutions, 'binary_mask' may consume large amounts of memory. """ assert (points_per_side is None) != ( point_grids is None ), "Exactly one of points_per_side or point_grid must be provided." if points_per_side is not None: self.point_grids = build_all_layer_point_grids( points_per_side, crop_n_layers, crop_n_points_downscale_factor, ) elif point_grids is not None: self.point_grids = point_grids else: raise ValueError("Can't have both points_per_side and point_grid be None.") assert output_mode in [ "binary_mask", "uncompressed_rle", "coco_rle", ], f"Unknown output_mode {output_mode}." if output_mode == "coco_rle": if min_mask_region_area > 0: self.predictor = SamPredictor(model) self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.stability_score_thresh = stability_score_thresh self.stability_score_offset = stability_score_offset self.box_nms_thresh = box_nms_thresh self.crop_n_layers = crop_n_layers self.crop_nms_thresh = crop_nms_thresh self.crop_overlap_ratio = crop_overlap_ratio self.crop_n_points_downscale_factor = crop_n_points_downscale_factor self.min_mask_region_area = min_mask_region_area self.output_mode = output_mode @torch.no_grad() def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: """ Generates masks for the given image. Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any) or np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": mask_data["segmentations"] = [ coco_encode_rle(rle) for rle in mask_data["rles"] ] elif self.output_mode == "binary_mask": mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] else: mask_data["segmentations"] = mask_data["rles"] # Write mask records curr_anns = [] for idx in range(len(mask_data["segmentations"])): ann = { "segmentation": mask_data["segmentations"][idx], "area": area_from_rle(mask_data["rles"][idx]), "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), "predicted_iou": mask_data["iou_preds"][idx].item(), "point_coords": [mask_data["points"][idx].tolist()], "stability_score": mask_data["stability_score"][idx].item(), "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), } curr_anns.append(ann) return curr_anns def _generate_masks(self, image: np.ndarray) -> MaskData: orig_size = image.shape[:2] crop_boxes, layer_idxs = generate_crop_boxes( orig_size, self.crop_n_layers, self.crop_overlap_ratio ) # Iterate over image crops data = MaskData() for crop_box, layer_idx in zip(crop_boxes, layer_idxs): crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) data.cat(crop_data) # Remove duplicate masks between crops if len(crop_boxes) > 1: # Prefer masks from smaller crops scores = 1 / box_area(data["crop_boxes"]) scores = scores.to(data["boxes"].device) keep_by_nms = batched_nms( data["boxes"].float(), scores, torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.crop_nms_thresh, ) data.filter(keep_by_nms) data.to_numpy() return data def _process_crop( self, image: np.ndarray, crop_box: List[int], crop_layer_idx: int, orig_size: Tuple[int, ...], ) -> MaskData: # Crop the image and calculate embeddings x0, y0, x1, y1 = crop_box cropped_im = image[y0:y1, x0:x1, :] cropped_im_size = cropped_im.shape[:2] self.predictor.set_image(cropped_im) # Get points for this crop points_scale = np.array(cropped_im_size)[None, ::-1] points_for_image = self.point_grids[crop_layer_idx] * points_scale # Generate masks for this crop in batches data = MaskData() for (points,) in batch_iterator(self.points_per_batch, points_for_image): batch_data = self._process_batch( points, cropped_im_size, crop_box, orig_size ) data.cat(batch_data) del batch_data self.predictor.reset_image() # Remove duplicates within this crop. keep_by_nms = batched_nms( data["boxes"].float(), data["iou_preds"], torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Return to the original image frame data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) data["points"] = uncrop_points(data["points"], crop_box) data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))]) return data def _process_batch( self, points: np.ndarray, im_size: Tuple[int, ...], crop_box: List[int], orig_size: Tuple[int, ...], ) -> MaskData: orig_h, orig_w = orig_size # Run model on this batch transformed_points = self.predictor.transform.apply_coords(points, im_size) in_points = torch.as_tensor(transformed_points, device=self.predictor.device) in_labels = torch.ones( in_points.shape[0], dtype=torch.int, device=in_points.device ) masks, iou_preds, _ = self.predictor.predict_torch( in_points[:, None, :], in_labels[:, None], multimask_output=True, return_logits=True, ) # Serialize predictions and store in MaskData data = MaskData( masks=masks.flatten(0, 1), iou_preds=iou_preds.flatten(0, 1), points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)), ) del masks # Filter by predicted IoU if self.pred_iou_thresh > 0.0: keep_mask = data["iou_preds"] > self.pred_iou_thresh data.filter(keep_mask) # Calculate stability score data["stability_score"] = calculate_stability_score( data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset, ) if self.stability_score_thresh > 0.0: keep_mask = data["stability_score"] >= self.stability_score_thresh data.filter(keep_mask) # Threshold masks and calculate boxes data["masks"] = data["masks"] > self.predictor.model.mask_threshold data["boxes"] = batched_mask_to_box(data["masks"]) # Filter boxes that touch crop boundaries keep_mask = ~is_box_near_crop_edge( data["boxes"], crop_box, [0, 0, orig_w, orig_h] ) if not torch.all(keep_mask): data.filter(keep_mask) # Compress to RLE data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) data["rles"] = mask_to_rle_pytorch(data["masks"]) del data["masks"] return data @staticmethod def postprocess_small_regions( mask_data: MaskData, min_area: int, nms_thresh: float ) -> MaskData: """ Removes small disconnected regions and holes in masks, then reruns box NMS to remove any new duplicates. Edits mask_data in place. Requires open-cv as a dependency. """ if len(mask_data["rles"]) == 0: return mask_data # Filter small disconnected regions and holes new_masks = [] scores = [] for rle in mask_data["rles"]: mask = rle_to_mask(rle)
mask, changed = remove_small_regions(mask, min_area, mode="holes")
13
2023-11-26 23:42:53+00:00
16k
sophiaalthammer/alforrankers
matchmaker/utils/input_pipeline.py
[ { "identifier": "ConditionalQueryGenerationInferenceReader", "path": "matchmaker/dataloaders/query_generation_inference_loader.py", "snippet": "class ConditionalQueryGenerationInferenceReader(DatasetReader):\n \"\"\"\n Read a tsv file containing a passage collection.\n \n Expected format for...
import torch import numpy import random import torch.multiprocessing as mp from allennlp.data.samplers import BucketBatchSampler, MaxTokensBatchSampler from allennlp.data.vocabulary import Vocabulary from allennlp.data.data_loaders import MultiProcessDataLoader from transformers import T5Tokenizer from allennlp.data.token_indexers import PretrainedTransformerIndexer from allennlp.data.tokenizers import PretrainedTransformerTokenizer from matchmaker.dataloaders.concatenated_reranking_loader import * from matchmaker.dataloaders.concatenated_training_loader import * from matchmaker.dataloaders.independent_reranking_loader import * from matchmaker.dataloaders.independent_training_loader import * from matchmaker.dataloaders.id_sequence_loader import * from matchmaker.dataloaders.mlm_masked_sequence_loader import * from matchmaker.dataloaders.query_generation_inference_loader import ConditionalQueryGenerationInferenceReader from matchmaker.dataloaders.tas_balanced_training_loader import * from matchmaker.dataloaders.pseudo_label_training_loader import PseudoLabelDatasetLoader, PseudoLabelTextDatasetLoader from matchmaker.dataloaders.triple_id_training_loader import TripleIdDatasetLoader from transformers import AutoTokenizer from matchmaker.dataloaders.bling_fire_tokenizer import BlingFireTokenizer from matchmaker.dataloaders.transformer_tokenizer import FastTransformerTokenizer from matchmaker.modules.bert_embedding_token_embedder import PretrainedBertIndexerNoSpecialTokens from typing import Dict, Tuple, List
12,241
max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], random_seed =run_config["random_seed"],concatenate_sequences = model_config.get("model_input_type", "") == "concatenated") elif run_config["dynamic_sampler_type"] == "mlm_pretrain": loader = MLMDatasetLoader(collection_file=run_config["train_tsv"], batch_size=int(run_config["batch_size_train"]), tokenizer=_tokenizer, max_doc_length=run_config["max_doc_length"], random_seed=run_config["random_seed"], min_doc_length=-1, mlm_mask_whole_words=True, mask_probability=run_config["mask_probability"], mlm_mask_replace_probability=run_config["mlm_mask_replace_probability"], mlm_mask_random_probability=run_config["mlm_mask_random_probability"], whole_word_masking=run_config["whole_word_masking"], random_spans=run_config["random_spans"], tasb=run_config["tasb"], tasb_cluster_file=run_config["tasb_cluster_file"], tasb_weight=run_config["tasb_weight"], grad_acc=run_config["gradient_accumulation_steps"], cached_chunk_size=int(run_config["batch_size_train"])/int(run_config["cache_chunk_size"])) else: raise ConfigurationError("dynamic sampler type not supported") return loader def allennlp_reranking_inference_loader(model_config, run_config, _input_file): ''' Load examples from a .tsv file in the reranking candidate file format: q_id<tab>d_id<tab>q_text<tab>d_text (Using allennlp's v2 multiprocess loader) ''' _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, max(run_config["max_doc_length"], run_config["max_query_length"])) if model_config.get("model_input_type", "") == "concatenated" or model_config["token_embedder_type"] == "bert_cat": reader = ConcatenatedReRankingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config["min_doc_length"], min_query_length=run_config["min_query_length"], train_qa_spans=run_config["train_qa_spans"]) else: reader = IndependentReRankingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config.get("min_doc_length",-1), min_query_length=run_config.get("min_query_length",-1), query_augment_mask_number=run_config.get("query_augment_mask_number",-1), train_qa_spans=run_config.get("train_qa_spans",False)) loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(run_config["batch_size_eval"])*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_sampler=MaxTokensBatchSampler(max_tokens=int(run_config["batch_size_eval"])*run_config["max_doc_length"], sorting_keys=["doc_tokens"], padding_noise=0)) loader.index_with(_vocab) return loader def allennlp_query_gen_train_loader(model_config, run_config, _input_file): ''' Load examples from a .tsv file in the reranking candidate file format: q_id<tab>d_id<tab>q_text<tab>d_text (Using allennlp's v2 multiprocess loader) ''' _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, max(run_config["max_doc_length"], run_config["max_query_length"])) reader = IndependentReRankingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config.get("min_doc_length",-1), min_query_length=run_config.get("min_query_length",-1), query_augment_mask_number=run_config.get("query_augment_mask_number",-1), train_qa_spans=run_config.get("train_qa_spans",False)) loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(run_config["batch_size_train"])*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_size=run_config["batch_size_train"]) loader.index_with(_vocab) return loader def allennlp_query_gen_inference_loader(model_config, run_config, _input_file,): ''' Load examples from a .tsv file in the single sequence format: id<tab>text and augment it with conditional query codes (Using allennlp's v2 multiprocess loader) ''' _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, run_config["max_doc_length"]) max_length = model_config["max_doc_length"] batch_size = run_config["collection_batch_size"] reader = ConditionalQueryGenerationInferenceReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=max_length, target_distribution_file=run_config["target_distribution_file"], target_number_of_queries_total=run_config["target_number_of_queries_total"]) loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(batch_size)*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_sampler=MaxTokensBatchSampler(max_tokens=int(batch_size)*max_length, sorting_keys=["doc_tokens"], padding_noise=0)) loader.index_with(_vocab) return loader def _get_indexer(model_config, max_length): # default values _tokenizer = BlingFireTokenizer() _vocab = Vocabulary() if model_config["token_embedder_type"] == "embedding": _token_indexers = {"tokens": SingleIdTokenIndexer(lowercase_tokens=True)} _vocab = Vocabulary.from_files(model_config["vocab_directory"]) elif model_config["token_embedder_type"] == "bert_embedding" or model_config["token_embedder_type"] == "bert_vectors": _tokenizer = PretrainedTransformerTokenizer(model_config["bert_pretrained_model"], do_lowercase=True, start_tokens=[], end_tokens=[]) _ind = PretrainedBertIndexerNoSpecialTokens(pretrained_model=model_config["bert_pretrained_model"], do_lowercase=True, max_pieces=max_length) _token_indexers = {"tokens": _ind} elif model_config["token_embedder_type"].startswith("bert"): model = model_config["bert_pretrained_model"] if "facebook/dpr" in model: model = "bert-base-uncased" # should be the right one (judging from paper + huggingface doc)
#from tokenizers import ByteLevelBPETokenizer,CharBPETokenizer #from matchmaker.dataloaders.transformer_tokenizer import CustomTransformerTokenizer,CustomTransformerIndexer mp.set_sharing_strategy("file_system") # VERY MUCH needed for linux !! makes everything faster, but tends to break stuff def allennlp_single_sequence_loader(model_config, run_config, _input_file, sequence_type, force_exact_batch_size=False): ''' Load examples from a .tsv file in the single sequence format: id<tab>text (Using allennlp's v2 multiprocess loader) ''' if model_config.get("model_input_type", "") == "mlm": sequence_type == "single_mlm" if sequence_type == "query": max_length = run_config.get("overwrite_max_query_length", model_config["max_query_length"]) min_length = model_config.get("min_query_length",-1) batch_size = run_config["query_batch_size"] split_document=False split_document_window_size=-1 if sequence_type == "single_mlm": max_length = run_config.get("overwrite_max_doc_length", model_config["max_doc_length"]) min_length = model_config.get("min_doc_length", -1) batch_size = run_config.get("collection_batch_size", run_config["batch_size_train"]) make_multiple_of=run_config.get("make_multiple_of",8) mask_probability=run_config.get("mask_probability",0.1) mlm_mask_replace_probability=run_config.get("mlm_mask_replace_probability",0.5) mlm_mask_random_probability=run_config.get("mlm_mask_random_probability",0.5) else: # doc max_length = run_config.get("overwrite_max_doc_length", model_config["max_doc_length"]) min_length = model_config.get("min_doc_length",-1) batch_size = run_config["collection_batch_size"] split_document=run_config.get("split_document",False) split_document_window_size=run_config.get("split_document_window_size",-1) _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, max_length) #if model_config.get("model_input_type", "") == "mlm": # reader = MLMMaskedSequenceDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, # max_doc_length=max_length, min_doc_length=min_length, # mask_probability=mask_probability, # mlm_mask_replace_probability=mlm_mask_replace_probability, # mlm_mask_random_probability=mlm_mask_random_probability, # make_multiple_of=make_multiple_of) reader = IdSequenceDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, split_document=split_document,split_document_window_size=split_document_window_size, max_seq_length=max_length, min_seq_length=min_length, sequence_type=sequence_type) if force_exact_batch_size: loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(batch_size)*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_size=int(batch_size)) else: loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(batch_size)*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_sampler=MaxTokensBatchSampler(max_tokens=int(batch_size)*max_length, sorting_keys=["seq_tokens"], padding_noise=0)) loader.index_with(_vocab) return loader def allennlp_triple_training_loader(model_config, run_config, _input_file,add_text_to_batch=False): ''' Load training examples (either in the re-ranking text file format or a dynamic loader) (Using allennlp's v2 multiprocess loader) ''' _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, max(run_config["max_doc_length"], run_config["max_query_length"])) if run_config.get("dynamic_sampler", False) == False: if model_config.get("model_input_type", "") == "concatenated" or model_config["token_embedder_type"] == "bert_cat": reader = ConcatenatedTrainingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config["min_doc_length"], min_query_length=run_config["min_query_length"], data_augment=run_config["train_data_augment"], train_pairwise_distillation=run_config["train_pairwise_distillation"], train_qa_spans=run_config["train_qa_spans"],add_text_to_batch=add_text_to_batch) else: reader = IndependentTrainingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config["min_doc_length"], min_query_length=run_config["min_query_length"], data_augment=run_config["train_data_augment"], train_pairwise_distillation=run_config["train_pairwise_distillation"], query_augment_mask_number=run_config["query_augment_mask_number"], train_qa_spans=run_config["train_qa_spans"],add_text_to_batch=add_text_to_batch) loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(run_config["batch_size_train"])*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_size=run_config["batch_size_train"]) loader.index_with(_vocab) else: #if run_config["dynamic_sampler_type"] == "list": # loader = IrDynamicTripleDatasetLoader(query_file=run_config["dynamic_query_file"], collection_file=run_config["dynamic_collection_file"], # qrels_file=run_config["dynamic_qrels_file"], candidate_file=run_config["dynamic_candidate_file"], # batch_size=int(run_config["batch_size_train"]), queries_per_batch=run_config["dynamic_queries_per_batch"], tokenizer=_tokenizer, token_indexers=_token_indexers, # max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], # min_doc_length=run_config["min_doc_length"], min_query_length=run_config["min_query_length"], # data_augment=run_config["train_data_augment"], vocab=_vocab) if run_config["dynamic_sampler_type"] == "tas_balanced": loader = TASBalancedDatasetLoader(query_file=run_config["dynamic_query_file"], collection_file=run_config["dynamic_collection_file"], pairs_with_teacher_scores=run_config["dynamic_pairs_with_teacher_scores"], query_cluster_file=run_config["dynamic_query_cluster_file"], batch_size=int(run_config["batch_size_train"]), clusters_per_batch=run_config["dynamic_clusters_per_batch"], tokenizer=_tokenizer, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], pair_balancing_strategy=run_config["tas_balanced_pair_strategy"],random_seed =run_config["random_seed"]) elif run_config["dynamic_sampler_type"] == "pseudo_label": loader = PseudoLabelDatasetLoader(query_file=run_config["dynamic_query_file"], collection_file=run_config["dynamic_collection_file"], rankings_with_teacher_scores=run_config["dynamic_rankings_with_teacher_scores"], selection_type=run_config["pseudo_label_selection_type"],min_pos_score=run_config["pseudo_label_min_pos_score"], max_diff_to_be_pos=run_config["pseudo_label_max_diff_to_be_pos"],min_diff_to_neg=run_config["pseudo_label_min_diff_to_neg"], batch_size=int(run_config["batch_size_train"]), tokenizer=_tokenizer, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], random_seed =run_config["random_seed"],concatenate_sequences = model_config.get("model_input_type", "") == "concatenated") elif run_config["dynamic_sampler_type"] == "pseudo_labeltext": loader = PseudoLabelTextDatasetLoader(rankings_with_teacher_scores=run_config["dynamic_rankings_with_teacher_scores"], batch_size=int(run_config["batch_size_train"]), tokenizer=_tokenizer, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], random_seed =run_config["random_seed"],concatenate_sequences = model_config.get("model_input_type", "") == "concatenated") elif run_config["dynamic_sampler_type"] == "triple_ids": loader = TripleIdDatasetLoader(query_file=run_config["dynamic_query_file"], collection_file=run_config["dynamic_collection_file"], triples_with_teacher_scores=run_config["dynamic_triples_with_teacher_scores"], batch_size=int(run_config["batch_size_train"]), tokenizer=_tokenizer, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], random_seed =run_config["random_seed"],concatenate_sequences = model_config.get("model_input_type", "") == "concatenated") elif run_config["dynamic_sampler_type"] == "mlm_pretrain": loader = MLMDatasetLoader(collection_file=run_config["train_tsv"], batch_size=int(run_config["batch_size_train"]), tokenizer=_tokenizer, max_doc_length=run_config["max_doc_length"], random_seed=run_config["random_seed"], min_doc_length=-1, mlm_mask_whole_words=True, mask_probability=run_config["mask_probability"], mlm_mask_replace_probability=run_config["mlm_mask_replace_probability"], mlm_mask_random_probability=run_config["mlm_mask_random_probability"], whole_word_masking=run_config["whole_word_masking"], random_spans=run_config["random_spans"], tasb=run_config["tasb"], tasb_cluster_file=run_config["tasb_cluster_file"], tasb_weight=run_config["tasb_weight"], grad_acc=run_config["gradient_accumulation_steps"], cached_chunk_size=int(run_config["batch_size_train"])/int(run_config["cache_chunk_size"])) else: raise ConfigurationError("dynamic sampler type not supported") return loader def allennlp_reranking_inference_loader(model_config, run_config, _input_file): ''' Load examples from a .tsv file in the reranking candidate file format: q_id<tab>d_id<tab>q_text<tab>d_text (Using allennlp's v2 multiprocess loader) ''' _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, max(run_config["max_doc_length"], run_config["max_query_length"])) if model_config.get("model_input_type", "") == "concatenated" or model_config["token_embedder_type"] == "bert_cat": reader = ConcatenatedReRankingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config["min_doc_length"], min_query_length=run_config["min_query_length"], train_qa_spans=run_config["train_qa_spans"]) else: reader = IndependentReRankingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config.get("min_doc_length",-1), min_query_length=run_config.get("min_query_length",-1), query_augment_mask_number=run_config.get("query_augment_mask_number",-1), train_qa_spans=run_config.get("train_qa_spans",False)) loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(run_config["batch_size_eval"])*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_sampler=MaxTokensBatchSampler(max_tokens=int(run_config["batch_size_eval"])*run_config["max_doc_length"], sorting_keys=["doc_tokens"], padding_noise=0)) loader.index_with(_vocab) return loader def allennlp_query_gen_train_loader(model_config, run_config, _input_file): ''' Load examples from a .tsv file in the reranking candidate file format: q_id<tab>d_id<tab>q_text<tab>d_text (Using allennlp's v2 multiprocess loader) ''' _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, max(run_config["max_doc_length"], run_config["max_query_length"])) reader = IndependentReRankingDatasetReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=run_config["max_doc_length"], max_query_length=run_config["max_query_length"], min_doc_length=run_config.get("min_doc_length",-1), min_query_length=run_config.get("min_query_length",-1), query_augment_mask_number=run_config.get("query_augment_mask_number",-1), train_qa_spans=run_config.get("train_qa_spans",False)) loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(run_config["batch_size_train"])*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_size=run_config["batch_size_train"]) loader.index_with(_vocab) return loader def allennlp_query_gen_inference_loader(model_config, run_config, _input_file,): ''' Load examples from a .tsv file in the single sequence format: id<tab>text and augment it with conditional query codes (Using allennlp's v2 multiprocess loader) ''' _tokenizer, _token_indexers, _vocab = _get_indexer(model_config, run_config["max_doc_length"]) max_length = model_config["max_doc_length"] batch_size = run_config["collection_batch_size"] reader = ConditionalQueryGenerationInferenceReader(tokenizer=_tokenizer, token_indexers=_token_indexers, max_doc_length=max_length, target_distribution_file=run_config["target_distribution_file"], target_number_of_queries_total=run_config["target_number_of_queries_total"]) loader = MultiProcessDataLoader(reader, data_path=_input_file, num_workers=run_config["dataloader_num_workers"], max_instances_in_memory=int(batch_size)*25, quiet=True, start_method="fork" if "fork" in mp.get_all_start_methods() else "spawn", batch_sampler=MaxTokensBatchSampler(max_tokens=int(batch_size)*max_length, sorting_keys=["doc_tokens"], padding_noise=0)) loader.index_with(_vocab) return loader def _get_indexer(model_config, max_length): # default values _tokenizer = BlingFireTokenizer() _vocab = Vocabulary() if model_config["token_embedder_type"] == "embedding": _token_indexers = {"tokens": SingleIdTokenIndexer(lowercase_tokens=True)} _vocab = Vocabulary.from_files(model_config["vocab_directory"]) elif model_config["token_embedder_type"] == "bert_embedding" or model_config["token_embedder_type"] == "bert_vectors": _tokenizer = PretrainedTransformerTokenizer(model_config["bert_pretrained_model"], do_lowercase=True, start_tokens=[], end_tokens=[]) _ind = PretrainedBertIndexerNoSpecialTokens(pretrained_model=model_config["bert_pretrained_model"], do_lowercase=True, max_pieces=max_length) _token_indexers = {"tokens": _ind} elif model_config["token_embedder_type"].startswith("bert"): model = model_config["bert_pretrained_model"] if "facebook/dpr" in model: model = "bert-base-uncased" # should be the right one (judging from paper + huggingface doc)
_tokenizer = FastTransformerTokenizer(model,
5
2023-11-21 10:38:22+00:00
16k
MICLab-Unicamp/medpseg
medpseg/poly_pipeline.py
[ { "identifier": "PolySeg2DModule", "path": "medpseg/poly_seg_2d_module.py", "snippet": "class PolySeg2DModule(pl.LightningModule):\n '''\n Regarding of the name, also works with 3D networks\n '''\n def __init__(self, hparams):\n '''\n Check starter.py for description of all hpa...
import os import torch import numpy as np import cc3d import SimpleITK as sitk from medpseg.poly_seg_2d_module import PolySeg2DModule from medpseg.eval_2d_utils import E2DStackDataset, argon_cpu_count from torch.nn import functional as F from tqdm import tqdm from collections import defaultdict from operator import itemgetter from typing import Dict, Optional from multiprocessing import Queue
10,858
''' Copyright (c) Diedre Carmo, Medical Imaging Computing Lab (MICLab) https://miclab.fee.unicamp.br/ https://github.com/MICLab-Unicamp/medpseg All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. Independent script Updated pipeline using a single weight ''' def get_connected_components(volume, return_largest=2, verbose=False): ''' volume: input volume return_largest: how many of the largest labels to return. If 0, nothing is changed in input volume verbose: prints label_count returns: filtered_volume, label_count, labeled_volume ''' labels_out = cc3d.connected_components(volume.astype(np.int32)) label_count = np.unique(labels_out, return_counts=True)[1] # Indicate which was the original label and sort by count label_count = [(label, count) for label, count in enumerate(label_count)] label_count.sort(key=itemgetter(1), reverse=True) label_count.pop(0) # remove largest which should be background if verbose: print(f"Label count: {label_count}") filtered = None if return_largest > 0: for i in range(return_largest): try: id_max = label_count[i][0] if filtered is None: filtered = (labels_out == id_max) else: filtered += (labels_out == id_max) except IndexError: # We want more components that what is in the image, stop break volume = filtered * volume labels_out = filtered * labels_out return volume, label_count, labels_out class PrintInterface(): def __init__(self, tqdm_iter): self.tqdm_iter = tqdm_iter self.rot90 = False def write(self, x): self.tqdm_iter.put(("write", x)) def progress(self, x): self.tqdm_iter.put(("iterbar", x)) def image_to_front_end(self, x): if self.rot90: x = np.rot90(x, k=2, axes=(0, 1)) self.tqdm_iter.put(("slice", x)) def icon(self): self.tqdm_iter.put(("icon", '')) def poly_stack_predict(model: torch.nn.Module, volume: torch.Tensor, batch_size: int, device=torch.device("cuda:0"), info_q: Optional[Queue] = None, uncertainty: Optional[int] = None): ''' DEVING uncertainty: epistemic uncerainty, predict n times and return the mean and std prediction '''
''' Copyright (c) Diedre Carmo, Medical Imaging Computing Lab (MICLab) https://miclab.fee.unicamp.br/ https://github.com/MICLab-Unicamp/medpseg All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. Independent script Updated pipeline using a single weight ''' def get_connected_components(volume, return_largest=2, verbose=False): ''' volume: input volume return_largest: how many of the largest labels to return. If 0, nothing is changed in input volume verbose: prints label_count returns: filtered_volume, label_count, labeled_volume ''' labels_out = cc3d.connected_components(volume.astype(np.int32)) label_count = np.unique(labels_out, return_counts=True)[1] # Indicate which was the original label and sort by count label_count = [(label, count) for label, count in enumerate(label_count)] label_count.sort(key=itemgetter(1), reverse=True) label_count.pop(0) # remove largest which should be background if verbose: print(f"Label count: {label_count}") filtered = None if return_largest > 0: for i in range(return_largest): try: id_max = label_count[i][0] if filtered is None: filtered = (labels_out == id_max) else: filtered += (labels_out == id_max) except IndexError: # We want more components that what is in the image, stop break volume = filtered * volume labels_out = filtered * labels_out return volume, label_count, labels_out class PrintInterface(): def __init__(self, tqdm_iter): self.tqdm_iter = tqdm_iter self.rot90 = False def write(self, x): self.tqdm_iter.put(("write", x)) def progress(self, x): self.tqdm_iter.put(("iterbar", x)) def image_to_front_end(self, x): if self.rot90: x = np.rot90(x, k=2, axes=(0, 1)) self.tqdm_iter.put(("slice", x)) def icon(self): self.tqdm_iter.put(("icon", '')) def poly_stack_predict(model: torch.nn.Module, volume: torch.Tensor, batch_size: int, device=torch.device("cuda:0"), info_q: Optional[Queue] = None, uncertainty: Optional[int] = None): ''' DEVING uncertainty: epistemic uncerainty, predict n times and return the mean and std prediction '''
e2d_stack_dataloader = E2DStackDataset(volume, extended_2d=1).get_dataloader(batch_size=batch_size, pin_memory=False, num_workers=argon_cpu_count())
1
2023-11-21 20:03:33+00:00
16k
DLYuanGod/TinyGPT-V
minigpt4/datasets/builders/image_text_pair_builder.py
[ { "identifier": "registry", "path": "minigpt4/common/registry.py", "snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_task(cls, name):\n def wrap(task_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def ...
import os import logging import warnings from minigpt4.common.registry import registry from minigpt4.datasets.builders.base_dataset_builder import BaseDatasetBuilder from minigpt4.datasets.datasets.laion_dataset import LaionDataset from minigpt4.datasets.datasets.cc_sbu_dataset import CCSBUDataset, CCSBUAlignDataset from minigpt4.datasets.datasets.text_caps import TextCapDataset from minigpt4.datasets.datasets.llava_dataset import LlavaDetailDataset, LlavaReasonDataset, LlavaConversationDataset from minigpt4.datasets.datasets.unnatural_instruction import UnnaturalDataset from minigpt4.datasets.datasets.multitask_conversation import MultiTaskConversationDataset from minigpt4.datasets.datasets.flickr import GroundedDetailDataset,CaptionToObjectDataset,PhraseToObjectDataset from minigpt4.datasets.datasets.vg_dataset import ReferVisualGenomeDataset from minigpt4.datasets.datasets.coco_dataset import ReferCOCODataset, InvReferCOCODataset from minigpt4.datasets.datasets.gqa_datasets import GQADataset from minigpt4.datasets.datasets.aok_vqa_datasets import AOKVQADataset from minigpt4.datasets.datasets.coco_vqa_datasets import COCOVQADataset from minigpt4.datasets.datasets.ocrvqa_dataset import OCRVQADataset from minigpt4.datasets.datasets.coco_caption import COCOCapDataset
11,628
datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets class AllRefCOCOBuilder(BaseDatasetBuilder): def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info image_path = build_info.image_path ann_path = build_info.ann_path datasets = dict() if not os.path.exists(image_path): warnings.warn("image path {} does not exist.".format(image_path)) if not os.path.exists(ann_path): warnings.warn("ann path {} does not exist.".format(ann_path)) # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=ann_path, vis_root=image_path, dataset=build_info.dataset, splitBy=build_info.splitBy ) return datasets @registry.register_builder("refcoco") class RefCOCOBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcoco.yaml", } @registry.register_builder("refcocop") class RefCOCOPBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcocop.yaml", } @registry.register_builder("refcocog") class RefCOCOGBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcocog.yaml", } @registry.register_builder("invrefcoco") class RefCOCOBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcoco.yaml", } @registry.register_builder("invrefcocop") class RefCOCOPBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcocop.yaml", } @registry.register_builder("invrefcocog") class RefCOCOGBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcocog.yaml", } @registry.register_builder("refvg") class RefVisualGenomeBuilder(BaseDatasetBuilder): train_dataset_cls = ReferVisualGenomeDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/vg/ref.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info data_dir = build_info.data_dir datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], data_dir=data_dir, ) return datasets @registry.register_builder("textcaps_caption") class TextcapCaptionBuilder(BaseDatasetBuilder):
@registry.register_builder("multitask_conversation") class MultitaskConversationBuilder(BaseDatasetBuilder): train_dataset_cls = MultiTaskConversationDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/multitask_conversation/default.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("unnatural_instruction") class UnnaturalInstructionBuilder(BaseDatasetBuilder): train_dataset_cls = UnnaturalDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/nlp/unnatural_instruction.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( text_processor=self.text_processors["train"], ann_path=build_info.ann_path, ) return datasets @registry.register_builder("llava_detail") class LlavaDetailBuilder(BaseDatasetBuilder): train_dataset_cls = LlavaDetailDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/llava/detail.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("llava_reason") class LlavaReasonBuilder(BaseDatasetBuilder): train_dataset_cls = LlavaReasonDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/llava/reason.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets @registry.register_builder("llava_conversation") class LlavaReasonBuilder(BaseDatasetBuilder): train_dataset_cls = LlavaConversationDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/llava/conversation.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=build_info.ann_path, vis_root=build_info.image_path, ) return datasets class AllRefCOCOBuilder(BaseDatasetBuilder): def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info image_path = build_info.image_path ann_path = build_info.ann_path datasets = dict() if not os.path.exists(image_path): warnings.warn("image path {} does not exist.".format(image_path)) if not os.path.exists(ann_path): warnings.warn("ann path {} does not exist.".format(ann_path)) # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], ann_path=ann_path, vis_root=image_path, dataset=build_info.dataset, splitBy=build_info.splitBy ) return datasets @registry.register_builder("refcoco") class RefCOCOBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcoco.yaml", } @registry.register_builder("refcocop") class RefCOCOPBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcocop.yaml", } @registry.register_builder("refcocog") class RefCOCOGBuilder(AllRefCOCOBuilder): train_dataset_cls = ReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/refcocog.yaml", } @registry.register_builder("invrefcoco") class RefCOCOBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcoco.yaml", } @registry.register_builder("invrefcocop") class RefCOCOPBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcocop.yaml", } @registry.register_builder("invrefcocog") class RefCOCOGBuilder(AllRefCOCOBuilder): train_dataset_cls = InvReferCOCODataset DATASET_CONFIG_DICT = { "default": "configs/datasets/coco_bbox/invrefcocog.yaml", } @registry.register_builder("refvg") class RefVisualGenomeBuilder(BaseDatasetBuilder): train_dataset_cls = ReferVisualGenomeDataset DATASET_CONFIG_DICT = { "default": "configs/datasets/vg/ref.yaml", } def build_datasets(self): # at this point, all the annotations and image/videos should be all downloaded to the specified locations. logging.info("Building datasets...") self.build_processors() build_info = self.config.build_info data_dir = build_info.data_dir datasets = dict() # create datasets dataset_cls = self.train_dataset_cls datasets['train'] = dataset_cls( vis_processor=self.vis_processors["train"], text_processor=self.text_processors["train"], data_dir=data_dir, ) return datasets @registry.register_builder("textcaps_caption") class TextcapCaptionBuilder(BaseDatasetBuilder):
train_dataset_cls = TextCapDataset
5
2023-12-28 05:47:18+00:00
16k
jiawei-ren/dreamgaussian4d
gaussian_model_4d.py
[ { "identifier": "inverse_sigmoid", "path": "utils/general_utils.py", "snippet": "def inverse_sigmoid(x):\n return torch.log(x/(1-x))" }, { "identifier": "get_expon_lr_func", "path": "utils/general_utils.py", "snippet": "def get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, ...
import torch import numpy as np import os import mcubes import mcubes from utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation from torch import nn from utils.system_utils import mkdir_p from plyfile import PlyData, PlyElement from random import randint from utils.sh_utils import RGB2SH from simple_knn._C import distCUDA2 from mesh import Mesh from mesh_utils import decimate_mesh, clean_mesh from utils.graphics_utils import BasicPointCloud from utils.general_utils import strip_symmetric, build_scaling_rotation from scene.deformation import deform_network from scene.regulation import compute_plane_smoothness
11,983
self._opacity, self.max_radii2D, xyz_gradient_accum, denom, opt_dict, self.spatial_lr_scale) = model_args self.training_setup(training_args) self.xyz_gradient_accum = xyz_gradient_accum self.denom = denom self.optimizer.load_state_dict(opt_dict) @property def get_scaling(self): return self.scaling_activation(self._scaling) @property def get_rotation(self): return self.rotation_activation(self._rotation) @property def get_xyz(self): return self._xyz @property def get_features(self): features_dc = self._features_dc features_rest = self._features_rest return torch.cat((features_dc, features_rest), dim=1) @property def get_opacity(self): return self.opacity_activation(self._opacity) @torch.no_grad() def extract_fields(self, resolution=128, num_blocks=16, relax_ratio=1.5): # resolution: resolution of field block_size = 2 / num_blocks assert resolution % block_size == 0 split_size = resolution // num_blocks opacities = self.get_opacity # pre-filter low opacity gaussians to save computation mask = (opacities > 0.005).squeeze(1) opacities = opacities[mask] xyzs = self.get_xyz[mask] stds = self.get_scaling[mask] # normalize to ~ [-1, 1] mn, mx = xyzs.amin(0), xyzs.amax(0) self.center = (mn + mx) / 2 self.scale = 1.8 / (mx - mn).amax().item() xyzs = (xyzs - self.center) * self.scale stds = stds * self.scale covs = self.covariance_activation(stds, 1, self._rotation[mask]) # tile device = opacities.device occ = torch.zeros([resolution] * 3, dtype=torch.float32, device=device) X = torch.linspace(-1, 1, resolution).split(split_size) Y = torch.linspace(-1, 1, resolution).split(split_size) Z = torch.linspace(-1, 1, resolution).split(split_size) # loop blocks (assume max size of gaussian is small than relax_ratio * block_size !!!) for xi, xs in enumerate(X): for yi, ys in enumerate(Y): for zi, zs in enumerate(Z): xx, yy, zz = torch.meshgrid(xs, ys, zs) # sample points [M, 3] pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1).to(device) # in-tile gaussians mask vmin, vmax = pts.amin(0), pts.amax(0) vmin -= block_size * relax_ratio vmax += block_size * relax_ratio mask = (xyzs < vmax).all(-1) & (xyzs > vmin).all(-1) # if hit no gaussian, continue to next block if not mask.any(): continue mask_xyzs = xyzs[mask] # [L, 3] mask_covs = covs[mask] # [L, 6] mask_opas = opacities[mask].view(1, -1) # [L, 1] --> [1, L] # query per point-gaussian pair. g_pts = pts.unsqueeze(1).repeat(1, mask_covs.shape[0], 1) - mask_xyzs.unsqueeze(0) # [M, L, 3] g_covs = mask_covs.unsqueeze(0).repeat(pts.shape[0], 1, 1) # [M, L, 6] # batch on gaussian to avoid OOM batch_g = 1024 val = 0 for start in range(0, g_covs.shape[1], batch_g): end = min(start + batch_g, g_covs.shape[1]) w = gaussian_3d_coeff(g_pts[:, start:end].reshape(-1, 3), g_covs[:, start:end].reshape(-1, 6)).reshape(pts.shape[0], -1) # [M, l] val += (mask_opas[:, start:end] * w).sum(-1) # kiui.lo(val, mask_opas, w) occ[xi * split_size: xi * split_size + len(xs), yi * split_size: yi * split_size + len(ys), zi * split_size: zi * split_size + len(zs)] = val.reshape(len(xs), len(ys), len(zs)) return occ def extract_mesh(self, path, density_thresh=1, resolution=128, decimate_target=1e5): os.makedirs(os.path.dirname(path), exist_ok=True) occ = self.extract_fields(resolution).detach().cpu().numpy() vertices, triangles = mcubes.marching_cubes(occ, density_thresh) vertices = vertices / (resolution - 1.0) * 2 - 1 # transform back to the original space vertices = vertices / self.scale + self.center.detach().cpu().numpy()
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # def gaussian_3d_coeff(xyzs, covs): # xyzs: [N, 3] # covs: [N, 6] x, y, z = xyzs[:, 0], xyzs[:, 1], xyzs[:, 2] a, b, c, d, e, f = covs[:, 0], covs[:, 1], covs[:, 2], covs[:, 3], covs[:, 4], covs[:, 5] # eps must be small enough !!! inv_det = 1 / (a * d * f + 2 * e * c * b - e**2 * a - c**2 * d - b**2 * f + 1e-24) inv_a = (d * f - e**2) * inv_det inv_b = (e * c - b * f) * inv_det inv_c = (e * b - c * d) * inv_det inv_d = (a * f - c**2) * inv_det inv_e = (b * c - e * a) * inv_det inv_f = (a * d - b**2) * inv_det power = -0.5 * (x**2 * inv_a + y**2 * inv_d + z**2 * inv_f) - x * y * inv_b - x * z * inv_c - y * z * inv_e power[power > 0] = -1e10 # abnormal values... make weights 0 return torch.exp(power) class GaussianModel: def setup_functions(self): def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation): L = build_scaling_rotation(scaling_modifier * scaling, rotation) actual_covariance = L @ L.transpose(1, 2) symm = strip_symmetric(actual_covariance) return symm self.scaling_activation = torch.exp self.scaling_inverse_activation = torch.log self.covariance_activation = build_covariance_from_scaling_rotation self.opacity_activation = torch.sigmoid self.inverse_opacity_activation = inverse_sigmoid self.rotation_activation = torch.nn.functional.normalize def __init__(self, sh_degree : int, args): self.active_sh_degree = 0 self.max_sh_degree = sh_degree self._xyz = torch.empty(0) # self._deformation = torch.empty(0) self._deformation = deform_network(args) # self.grid = TriPlaneGrid() self._features_dc = torch.empty(0) self._features_rest = torch.empty(0) self._scaling = torch.empty(0) self._rotation = torch.empty(0) self._opacity = torch.empty(0) self.max_radii2D = torch.empty(0) self.xyz_gradient_accum = torch.empty(0) self.denom = torch.empty(0) self.optimizer = None self.percent_dense = 0 self.spatial_lr_scale = 0 self._deformation_table = torch.empty(0) self.setup_functions() def capture(self): return ( self.active_sh_degree, self._xyz, self._deformation.state_dict(), self._deformation_table, # self.grid, self._features_dc, self._features_rest, self._scaling, self._rotation, self._opacity, self.max_radii2D, self.xyz_gradient_accum, self.denom, self.optimizer.state_dict(), self.spatial_lr_scale, ) def restore(self, model_args, training_args): (self.active_sh_degree, self._xyz, self._deformation_table, self._deformation, # self.grid, self._features_dc, self._features_rest, self._scaling, self._rotation, self._opacity, self.max_radii2D, xyz_gradient_accum, denom, opt_dict, self.spatial_lr_scale) = model_args self.training_setup(training_args) self.xyz_gradient_accum = xyz_gradient_accum self.denom = denom self.optimizer.load_state_dict(opt_dict) @property def get_scaling(self): return self.scaling_activation(self._scaling) @property def get_rotation(self): return self.rotation_activation(self._rotation) @property def get_xyz(self): return self._xyz @property def get_features(self): features_dc = self._features_dc features_rest = self._features_rest return torch.cat((features_dc, features_rest), dim=1) @property def get_opacity(self): return self.opacity_activation(self._opacity) @torch.no_grad() def extract_fields(self, resolution=128, num_blocks=16, relax_ratio=1.5): # resolution: resolution of field block_size = 2 / num_blocks assert resolution % block_size == 0 split_size = resolution // num_blocks opacities = self.get_opacity # pre-filter low opacity gaussians to save computation mask = (opacities > 0.005).squeeze(1) opacities = opacities[mask] xyzs = self.get_xyz[mask] stds = self.get_scaling[mask] # normalize to ~ [-1, 1] mn, mx = xyzs.amin(0), xyzs.amax(0) self.center = (mn + mx) / 2 self.scale = 1.8 / (mx - mn).amax().item() xyzs = (xyzs - self.center) * self.scale stds = stds * self.scale covs = self.covariance_activation(stds, 1, self._rotation[mask]) # tile device = opacities.device occ = torch.zeros([resolution] * 3, dtype=torch.float32, device=device) X = torch.linspace(-1, 1, resolution).split(split_size) Y = torch.linspace(-1, 1, resolution).split(split_size) Z = torch.linspace(-1, 1, resolution).split(split_size) # loop blocks (assume max size of gaussian is small than relax_ratio * block_size !!!) for xi, xs in enumerate(X): for yi, ys in enumerate(Y): for zi, zs in enumerate(Z): xx, yy, zz = torch.meshgrid(xs, ys, zs) # sample points [M, 3] pts = torch.cat([xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)], dim=-1).to(device) # in-tile gaussians mask vmin, vmax = pts.amin(0), pts.amax(0) vmin -= block_size * relax_ratio vmax += block_size * relax_ratio mask = (xyzs < vmax).all(-1) & (xyzs > vmin).all(-1) # if hit no gaussian, continue to next block if not mask.any(): continue mask_xyzs = xyzs[mask] # [L, 3] mask_covs = covs[mask] # [L, 6] mask_opas = opacities[mask].view(1, -1) # [L, 1] --> [1, L] # query per point-gaussian pair. g_pts = pts.unsqueeze(1).repeat(1, mask_covs.shape[0], 1) - mask_xyzs.unsqueeze(0) # [M, L, 3] g_covs = mask_covs.unsqueeze(0).repeat(pts.shape[0], 1, 1) # [M, L, 6] # batch on gaussian to avoid OOM batch_g = 1024 val = 0 for start in range(0, g_covs.shape[1], batch_g): end = min(start + batch_g, g_covs.shape[1]) w = gaussian_3d_coeff(g_pts[:, start:end].reshape(-1, 3), g_covs[:, start:end].reshape(-1, 6)).reshape(pts.shape[0], -1) # [M, l] val += (mask_opas[:, start:end] * w).sum(-1) # kiui.lo(val, mask_opas, w) occ[xi * split_size: xi * split_size + len(xs), yi * split_size: yi * split_size + len(ys), zi * split_size: zi * split_size + len(zs)] = val.reshape(len(xs), len(ys), len(zs)) return occ def extract_mesh(self, path, density_thresh=1, resolution=128, decimate_target=1e5): os.makedirs(os.path.dirname(path), exist_ok=True) occ = self.extract_fields(resolution).detach().cpu().numpy() vertices, triangles = mcubes.marching_cubes(occ, density_thresh) vertices = vertices / (resolution - 1.0) * 2 - 1 # transform back to the original space vertices = vertices / self.scale + self.center.detach().cpu().numpy()
vertices, triangles = clean_mesh(vertices, triangles, remesh=True, remesh_size=0.015)
7
2023-12-28 08:17:40+00:00
16k
FoundationVision/UniRef
detectron2/data/datasets/coco.py
[ { "identifier": "Boxes", "path": "detectron2/structures/boxes.py", "snippet": "class Boxes:\n \"\"\"\n This structure stores a list of boxes as a Nx4 torch.Tensor.\n It supports some common methods about boxes\n (`area`, `clip`, `nonempty`, etc),\n and also behaves like a Tensor\n (sup...
import contextlib import datetime import io import json import logging import numpy as np import os import shutil import pycocotools.mask as mask_util import detectron2.data.datasets # noqa # add pre-defined metadata import sys from fvcore.common.timer import Timer from iopath.common.file_io import file_lock from PIL import Image from detectron2.structures import Boxes, BoxMode, PolygonMasks, RotatedBoxes from detectron2.utils.file_io import PathManager from .. import DatasetCatalog, MetadataCatalog from pycocotools.coco import COCO from detectron2.utils.logger import setup_logger from detectron2.utils.visualizer import Visualizer
13,194
# the category ids to contiguous ids in [0, 80). # It works by looking at the "categories" field in the json, therefore # if users' own json also have incontiguous ids, we'll # apply this mapping as well but print a warning. if not (min(cat_ids) == 1 and max(cat_ids) == len(cat_ids)): if "coco" not in dataset_name: logger.warning( """ Category ids in annotations are not in [1, #categories]! We'll apply a mapping for you. """ ) id_map = {v: i for i, v in enumerate(cat_ids)} meta.thing_dataset_id_to_contiguous_id = id_map # sort indices for reproducible results img_ids = sorted(coco_api.imgs.keys()) # imgs is a list of dicts, each looks something like: # {'license': 4, # 'url': 'http://farm6.staticflickr.com/5454/9413846304_881d5e5c3b_z.jpg', # 'file_name': 'COCO_val2014_000000001268.jpg', # 'height': 427, # 'width': 640, # 'date_captured': '2013-11-17 05:57:24', # 'id': 1268} imgs = coco_api.loadImgs(img_ids) # anns is a list[list[dict]], where each dict is an annotation # record for an object. The inner list enumerates the objects in an image # and the outer list enumerates over images. Example of anns[0]: # [{'segmentation': [[192.81, # 247.09, # ... # 219.03, # 249.06]], # 'area': 1035.749, # 'iscrowd': 0, # 'image_id': 1268, # 'bbox': [192.81, 224.8, 74.73, 33.43], # 'category_id': 16, # 'id': 42986}, # ...] anns = [coco_api.imgToAnns[img_id] for img_id in img_ids] total_num_valid_anns = sum([len(x) for x in anns]) total_num_anns = len(coco_api.anns) if total_num_valid_anns < total_num_anns: logger.warning( f"{json_file} contains {total_num_anns} annotations, but only " f"{total_num_valid_anns} of them match to images in the file." ) if "minival" not in json_file: # The popular valminusminival & minival annotations for COCO2014 contain this bug. # However the ratio of buggy annotations there is tiny and does not affect accuracy. # Therefore we explicitly white-list them. ann_ids = [ann["id"] for anns_per_image in anns for ann in anns_per_image] assert len(set(ann_ids)) == len(ann_ids), "Annotation ids in '{}' are not unique!".format( json_file ) imgs_anns = list(zip(imgs, anns)) logger.info("Loaded {} images in COCO format from {}".format(len(imgs_anns), json_file)) dataset_dicts = [] ann_keys = ["iscrowd", "bbox", "keypoints", "category_id"] + (extra_annotation_keys or []) num_instances_without_valid_segmentation = 0 for (img_dict, anno_dict_list) in imgs_anns: record = {} record["file_name"] = os.path.join(image_root, img_dict["file_name"]) record["height"] = img_dict["height"] record["width"] = img_dict["width"] image_id = record["image_id"] = img_dict["id"] objs = [] for anno in anno_dict_list: # Check that the image_id in this annotation is the same as # the image_id we're looking at. # This fails only when the data parsing logic or the annotation file is buggy. # The original COCO valminusminival2014 & minival2014 annotation files # actually contains bugs that, together with certain ways of using COCO API, # can trigger this assertion. assert anno["image_id"] == image_id assert anno.get("ignore", 0) == 0, '"ignore" in COCO json file is not supported.' obj = {key: anno[key] for key in ann_keys if key in anno} if "bbox" in obj and len(obj["bbox"]) == 0: raise ValueError( f"One annotation of image {image_id} contains empty 'bbox' value! " "This json does not have valid COCO format." ) segm = anno.get("segmentation", None) if segm: # either list[list[float]] or dict(RLE) if isinstance(segm, dict): if isinstance(segm["counts"], list): # convert to compressed RLE segm = mask_util.frPyObjects(segm, *segm["size"]) else: # filter out invalid polygons (< 3 points) segm = [poly for poly in segm if len(poly) % 2 == 0 and len(poly) >= 6] if len(segm) == 0: num_instances_without_valid_segmentation += 1 continue # ignore this instance obj["segmentation"] = segm keypts = anno.get("keypoints", None) if keypts: # list[int] for idx, v in enumerate(keypts): if idx % 3 != 2: # COCO's segmentation coordinates are floating points in [0, H or W], # but keypoint coordinates are integers in [0, H-1 or W-1] # Therefore we assume the coordinates are "pixel indices" and # add 0.5 to convert to floating point coordinates. keypts[idx] = v + 0.5 obj["keypoints"] = keypts
# Copyright (c) Facebook, Inc. and its affiliates. """ This file contains functions to parse COCO-format annotations into dicts in "Detectron2 format". """ logger = logging.getLogger(__name__) __all__ = ["load_coco_json", "load_sem_seg", "convert_to_coco_json", "register_coco_instances"] def load_coco_json(json_file, image_root, dataset_name=None, extra_annotation_keys=None, dataset_name_in_dict="coco"): """ Load a json file with COCO's instances annotation format. Currently supports instance detection, instance segmentation, and person keypoints annotations. Args: json_file (str): full path to the json file in COCO instances annotation format. image_root (str or path-like): the directory where the images in this json file exists. dataset_name (str or None): the name of the dataset (e.g., coco_2017_train). When provided, this function will also do the following: * Put "thing_classes" into the metadata associated with this dataset. * Map the category ids into a contiguous range (needed by standard dataset format), and add "thing_dataset_id_to_contiguous_id" to the metadata associated with this dataset. This option should usually be provided, unless users need to load the original json content and apply more processing manually. extra_annotation_keys (list[str]): list of per-annotation keys that should also be loaded into the dataset dict (besides "iscrowd", "bbox", "keypoints", "category_id", "segmentation"). The values for these keys will be returned as-is. For example, the densepose annotations are loaded in this way. Returns: list[dict]: a list of dicts in Detectron2 standard dataset dicts format (See `Using Custom Datasets </tutorials/datasets.html>`_ ) when `dataset_name` is not None. If `dataset_name` is None, the returned `category_ids` may be incontiguous and may not conform to the Detectron2 standard format. Notes: 1. This function does not read the image files. The results do not have the "image" field. """ timer = Timer() json_file = PathManager.get_local_path(json_file) with contextlib.redirect_stdout(io.StringIO()): coco_api = COCO(json_file) if timer.seconds() > 1: logger.info("Loading {} takes {:.2f} seconds.".format(json_file, timer.seconds())) id_map = None if dataset_name is not None: meta = MetadataCatalog.get(dataset_name) cat_ids = sorted(coco_api.getCatIds()) cats = coco_api.loadCats(cat_ids) # The categories in a custom json file may not be sorted. thing_classes = [c["name"] for c in sorted(cats, key=lambda x: x["id"])] meta.thing_classes = thing_classes # In COCO, certain category ids are artificially removed, # and by convention they are always ignored. # We deal with COCO's id issue and translate # the category ids to contiguous ids in [0, 80). # It works by looking at the "categories" field in the json, therefore # if users' own json also have incontiguous ids, we'll # apply this mapping as well but print a warning. if not (min(cat_ids) == 1 and max(cat_ids) == len(cat_ids)): if "coco" not in dataset_name: logger.warning( """ Category ids in annotations are not in [1, #categories]! We'll apply a mapping for you. """ ) id_map = {v: i for i, v in enumerate(cat_ids)} meta.thing_dataset_id_to_contiguous_id = id_map # sort indices for reproducible results img_ids = sorted(coco_api.imgs.keys()) # imgs is a list of dicts, each looks something like: # {'license': 4, # 'url': 'http://farm6.staticflickr.com/5454/9413846304_881d5e5c3b_z.jpg', # 'file_name': 'COCO_val2014_000000001268.jpg', # 'height': 427, # 'width': 640, # 'date_captured': '2013-11-17 05:57:24', # 'id': 1268} imgs = coco_api.loadImgs(img_ids) # anns is a list[list[dict]], where each dict is an annotation # record for an object. The inner list enumerates the objects in an image # and the outer list enumerates over images. Example of anns[0]: # [{'segmentation': [[192.81, # 247.09, # ... # 219.03, # 249.06]], # 'area': 1035.749, # 'iscrowd': 0, # 'image_id': 1268, # 'bbox': [192.81, 224.8, 74.73, 33.43], # 'category_id': 16, # 'id': 42986}, # ...] anns = [coco_api.imgToAnns[img_id] for img_id in img_ids] total_num_valid_anns = sum([len(x) for x in anns]) total_num_anns = len(coco_api.anns) if total_num_valid_anns < total_num_anns: logger.warning( f"{json_file} contains {total_num_anns} annotations, but only " f"{total_num_valid_anns} of them match to images in the file." ) if "minival" not in json_file: # The popular valminusminival & minival annotations for COCO2014 contain this bug. # However the ratio of buggy annotations there is tiny and does not affect accuracy. # Therefore we explicitly white-list them. ann_ids = [ann["id"] for anns_per_image in anns for ann in anns_per_image] assert len(set(ann_ids)) == len(ann_ids), "Annotation ids in '{}' are not unique!".format( json_file ) imgs_anns = list(zip(imgs, anns)) logger.info("Loaded {} images in COCO format from {}".format(len(imgs_anns), json_file)) dataset_dicts = [] ann_keys = ["iscrowd", "bbox", "keypoints", "category_id"] + (extra_annotation_keys or []) num_instances_without_valid_segmentation = 0 for (img_dict, anno_dict_list) in imgs_anns: record = {} record["file_name"] = os.path.join(image_root, img_dict["file_name"]) record["height"] = img_dict["height"] record["width"] = img_dict["width"] image_id = record["image_id"] = img_dict["id"] objs = [] for anno in anno_dict_list: # Check that the image_id in this annotation is the same as # the image_id we're looking at. # This fails only when the data parsing logic or the annotation file is buggy. # The original COCO valminusminival2014 & minival2014 annotation files # actually contains bugs that, together with certain ways of using COCO API, # can trigger this assertion. assert anno["image_id"] == image_id assert anno.get("ignore", 0) == 0, '"ignore" in COCO json file is not supported.' obj = {key: anno[key] for key in ann_keys if key in anno} if "bbox" in obj and len(obj["bbox"]) == 0: raise ValueError( f"One annotation of image {image_id} contains empty 'bbox' value! " "This json does not have valid COCO format." ) segm = anno.get("segmentation", None) if segm: # either list[list[float]] or dict(RLE) if isinstance(segm, dict): if isinstance(segm["counts"], list): # convert to compressed RLE segm = mask_util.frPyObjects(segm, *segm["size"]) else: # filter out invalid polygons (< 3 points) segm = [poly for poly in segm if len(poly) % 2 == 0 and len(poly) >= 6] if len(segm) == 0: num_instances_without_valid_segmentation += 1 continue # ignore this instance obj["segmentation"] = segm keypts = anno.get("keypoints", None) if keypts: # list[int] for idx, v in enumerate(keypts): if idx % 3 != 2: # COCO's segmentation coordinates are floating points in [0, H or W], # but keypoint coordinates are integers in [0, H-1 or W-1] # Therefore we assume the coordinates are "pixel indices" and # add 0.5 to convert to floating point coordinates. keypts[idx] = v + 0.5 obj["keypoints"] = keypts
obj["bbox_mode"] = BoxMode.XYWH_ABS
1
2023-12-22 13:31:33+00:00
16k
xhuangcv/humannorm
threestudio/models/geometry/tetrahedra_sdf_grid.py
[ { "identifier": "BaseExplicitGeometry", "path": "threestudio/models/geometry/base.py", "snippet": "class BaseExplicitGeometry(BaseGeometry):\n @dataclass\n class Config(BaseGeometry.Config):\n radius: float = 1.0\n\n cfg: Config\n\n def configure(self) -> None:\n self.bbox: Flo...
from dataclasses import dataclass, field from threestudio.models.geometry.base import ( BaseExplicitGeometry, BaseGeometry, contract_to_unisphere, ) from threestudio.models.geometry.implicit_sdf import ImplicitSDF from threestudio.models.geometry.implicit_volume import ImplicitVolume from threestudio.models.isosurface import MarchingTetrahedraHelper from threestudio.models.mesh import Mesh from threestudio.models.networks import get_encoding, get_mlp from threestudio.utils.ops import scale_tensor from threestudio.utils.typing import * from pysdf import SDF from tqdm import tqdm import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import threestudio import trimesh
14,299
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone()) self.isosurface_helper = MarchingTetrahedraHelper( self.cfg.isosurface_resolution, f"load/tets/{self.cfg.isosurface_resolution}_tets.npz", ) self.sdf: Float[Tensor, "Nv 1"] self.deformation: Optional[Float[Tensor, "Nv 3"]] if not self.cfg.fix_geometry: self.register_parameter( "sdf", nn.Parameter( torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ) ), ) if self.cfg.isosurface_deformable_grid: self.register_parameter( "deformation", nn.Parameter( torch.zeros_like(self.isosurface_helper.grid_vertices) ), ) else: self.deformation = None else: self.register_buffer( "sdf", torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ), ) if self.cfg.isosurface_deformable_grid: self.register_buffer( "deformation", torch.zeros_like(self.isosurface_helper.grid_vertices), ) else: self.deformation = None if not self.cfg.geometry_only: self.encoding = get_encoding( self.cfg.n_input_dims, self.cfg.pos_encoding_config ) self.feature_network = get_mlp( self.encoding.n_output_dims, self.cfg.n_feature_dims, self.cfg.mlp_network_config, )
@threestudio.register("tetrahedra-sdf-grid") class TetrahedraSDFGrid(BaseExplicitGeometry): @dataclass class Config(BaseExplicitGeometry.Config): isosurface_resolution: int = 128 isosurface_deformable_grid: bool = True isosurface_remove_outliers: bool = False isosurface_outlier_n_faces_threshold: Union[int, float] = 0.01 n_input_dims: int = 3 n_feature_dims: int = 3 pos_encoding_config: dict = field( default_factory=lambda: { "otype": "HashGrid", "n_levels": 16, "n_features_per_level": 2, "log2_hashmap_size": 19, "base_resolution": 16, "per_level_scale": 1.447269237440378, } ) mlp_network_config: dict = field( default_factory=lambda: { "otype": "VanillaMLP", "activation": "ReLU", "output_activation": "none", "n_neurons": 64, "n_hidden_layers": 1, } ) shape_init: Optional[str] = None shape_init_params: Optional[Any] = None force_shape_init: bool = False geometry_only: bool = False fix_geometry: bool = False cfg: Config def configure(self) -> None: super().configure() # this should be saved to state_dict, register as buffer self.isosurface_bbox: Float[Tensor, "2 3"] self.register_buffer("isosurface_bbox", self.bbox.clone()) self.isosurface_helper = MarchingTetrahedraHelper( self.cfg.isosurface_resolution, f"load/tets/{self.cfg.isosurface_resolution}_tets.npz", ) self.sdf: Float[Tensor, "Nv 1"] self.deformation: Optional[Float[Tensor, "Nv 3"]] if not self.cfg.fix_geometry: self.register_parameter( "sdf", nn.Parameter( torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ) ), ) if self.cfg.isosurface_deformable_grid: self.register_parameter( "deformation", nn.Parameter( torch.zeros_like(self.isosurface_helper.grid_vertices) ), ) else: self.deformation = None else: self.register_buffer( "sdf", torch.zeros( (self.isosurface_helper.grid_vertices.shape[0], 1), dtype=torch.float32, ), ) if self.cfg.isosurface_deformable_grid: self.register_buffer( "deformation", torch.zeros_like(self.isosurface_helper.grid_vertices), ) else: self.deformation = None if not self.cfg.geometry_only: self.encoding = get_encoding( self.cfg.n_input_dims, self.cfg.pos_encoding_config ) self.feature_network = get_mlp( self.encoding.n_output_dims, self.cfg.n_feature_dims, self.cfg.mlp_network_config, )
self.mesh: Optional[Mesh] = None
6
2023-12-23 12:37:48+00:00
16k
Con6924/SPM
evaluate_task.py
[ { "identifier": "config", "path": "src/configs/config.py", "snippet": "PRECISION_TYPES = Literal[\"fp32\", \"fp16\", \"bf16\", \"float32\", \"float16\", \"bfloat16\"]\nclass PretrainedModelConfig(BaseModel):\nclass NetworkConfig(BaseModel):\nclass TrainConfig(BaseModel): \nclass SaveConfig(BaseModel)...
import argparse import gc import warnings import torch from pathlib import Path from typing import Literal from torch.utils.data import DataLoader from accelerate import PartialState, Accelerator from src.configs import config from src.configs.config import RootConfig from src.configs.generation_config import GenerationConfig from src.engine import train_util from src.evaluation import * from src.models import model_util from src.models.spm import SPMLayer, SPMNetwork from src.models.merge_spm import load_state_dict from src.misc.sld_pipeline import SLDPipeline
11,942
dataset_class = I2PDataset elif args.task == "coco": dataset_class = Coco30kGenerationDataset else: raise ValueError(f"Unknown task: {args.task}") dataset = dataset_class(**task_args, base_cfg=cfg) dataloader = DataLoader(dataset, batch_size=num_processes, num_workers=0, shuffle=False) return dataloader def get_evaluator(args): evaluator_class = None if args.task == "general": evaluator_class = ClipEvaluator elif args.task == "artwork": evaluator_class = ArtworkEvaluator elif args.task == "i2p": evaluator_class = I2PEvaluator elif args.task == "coco": evaluator_class = CocoEvaluator else: raise ValueError(f"Unknown task: {args.task}") evaluator = evaluator_class( save_folder=args.img_save_path, output_path=args.save_path ) return evaluator def calculate_matching_score( prompt_tokens, prompt_embeds, erased_prompt_tokens, erased_prompt_embeds, matching_metric: MATCHING_METRICS, special_token_ids: set[int], weight_dtype: torch.dtype = torch.float32, ): scores = [] if "allone" in matching_metric: scores.append(torch.ones(prompt_embeds.shape[0]).to("cpu", dtype=weight_dtype)) if "clipcos" in matching_metric: clipcos = torch.cosine_similarity( prompt_embeds.flatten(1, 2), erased_prompt_embeds.flatten(1, 2), dim=-1 ).cpu() scores.append(clipcos) if "tokenuni" in matching_metric: prompt_set = set(prompt_tokens[0].tolist()) - special_token_ids tokenuni = [] for ep in erased_prompt_tokens: ep_set = set(ep.tolist()) - special_token_ids tokenuni.append(len(prompt_set.intersection(ep_set)) / len(ep_set)) scores.append(torch.tensor(tokenuni).to("cpu", dtype=weight_dtype)) return torch.max(torch.stack(scores), dim=0)[0] @torch.no_grad() def infer_with_spm( dataloader: DataLoader, spm_paths: list[str], matching_metric: MATCHING_METRICS, facilitate_factor: float = 1.0, assigned_multipliers: list[float] = None, finetuned_model_path: str = None, sld_target_concept: str = None, base_model: str = "CompVis/stable-diffusion-v1-4", v2: bool = False, precision: str = "fp32", ): spm_model_paths = [ lp / f"{lp.name}_last.safetensors" if lp.is_dir() else lp for lp in spm_paths ] weight_dtype = config.parse_precision(precision) if finetuned_model_path is not None and Path(finetuned_model_path).is_dir(): # folder path for the diffuser model base_model = finetuned_model_path print(f"Using models from {base_model}") # load the pretrained SD tokenizer, text_encoder, unet, pipe = model_util.load_checkpoint_model( base_model, v2=v2, weight_dtype=weight_dtype, device=distributed_state.device, ) special_token_ids = set( tokenizer.convert_tokens_to_ids(tokenizer.special_tokens_map.values()) ) text_encoder.to(distributed_state.device, dtype=weight_dtype) text_encoder.eval() unet.to(distributed_state.device, dtype=weight_dtype) unet.enable_xformers_memory_efficient_attention() unet.requires_grad_(False) unet.eval() if len(spm_model_paths) > 0: # load the SPM models spms, metadatas = zip( *[ load_state_dict(spm_model_path, weight_dtype) for spm_model_path in spm_model_paths ] ) # check if SPMs are compatible assert all([metadata["rank"] == metadatas[0]["rank"] for metadata in metadatas]) # get the erased concept erased_prompts = [md["prompts"].split(",") for md in metadatas] erased_prompts_count = [len(ep) for ep in erased_prompts] print(f"Erased prompts: {erased_prompts}") erased_prompts_flatten = [item for sublist in erased_prompts for item in sublist] erased_prompt_embeds, erased_prompt_tokens = train_util.encode_prompts( tokenizer, text_encoder, erased_prompts_flatten, return_tokens=True ) # create the SPM network
DIFFUSERS_CACHE_DIR = ".cache/" UNET_NAME = "unet" TEXT_ENCODER_NAME = "text_encoder" MATCHING_METRICS = Literal[ "clipcos", "clipcos_tokenuni", "tokenuni", "allone", ] distributed_state = PartialState() accelerator = Accelerator() def flush(): torch.cuda.empty_cache() gc.collect() def parse_extra_args(extra_args): if extra_args is None or extra_args == ['']: return {} extra_args_dict = {} for extra_arg in extra_args: key, value = extra_arg.split("=") # convert value to various types if value.isdigit(): value = int(value) elif value.replace(".", "", 1).isdigit(): value = float(value) elif value[0] == "[" and value[-1] == "]": value = [i.replace('+', ' ') for i in value[1:-1].split(",")] value = [v.strip() for v in value] if value[0].isdigit(): value = [int(v) for v in value] elif value[0].replace(".", "", 1).isdigit(): value = [float(v) for v in value] extra_args_dict[key] = value return extra_args_dict def get_dataloader(args, num_processes=1): # parse task_args arguments task_args = parse_extra_args(args.task_args) task_args["save_folder"] = args.img_save_path task_args["output_path"] = args.save_path # parse generation arguments cfg = parse_extra_args(args.generation_cfg) cfg = GenerationConfig(**cfg) dataset_class = None if args.task == "general": dataset_class = ClipTemplateDataset elif args.task == "artwork": dataset_class = ArtworkDataset elif args.task == "i2p": dataset_class = I2PDataset elif args.task == "coco": dataset_class = Coco30kGenerationDataset else: raise ValueError(f"Unknown task: {args.task}") dataset = dataset_class(**task_args, base_cfg=cfg) dataloader = DataLoader(dataset, batch_size=num_processes, num_workers=0, shuffle=False) return dataloader def get_evaluator(args): evaluator_class = None if args.task == "general": evaluator_class = ClipEvaluator elif args.task == "artwork": evaluator_class = ArtworkEvaluator elif args.task == "i2p": evaluator_class = I2PEvaluator elif args.task == "coco": evaluator_class = CocoEvaluator else: raise ValueError(f"Unknown task: {args.task}") evaluator = evaluator_class( save_folder=args.img_save_path, output_path=args.save_path ) return evaluator def calculate_matching_score( prompt_tokens, prompt_embeds, erased_prompt_tokens, erased_prompt_embeds, matching_metric: MATCHING_METRICS, special_token_ids: set[int], weight_dtype: torch.dtype = torch.float32, ): scores = [] if "allone" in matching_metric: scores.append(torch.ones(prompt_embeds.shape[0]).to("cpu", dtype=weight_dtype)) if "clipcos" in matching_metric: clipcos = torch.cosine_similarity( prompt_embeds.flatten(1, 2), erased_prompt_embeds.flatten(1, 2), dim=-1 ).cpu() scores.append(clipcos) if "tokenuni" in matching_metric: prompt_set = set(prompt_tokens[0].tolist()) - special_token_ids tokenuni = [] for ep in erased_prompt_tokens: ep_set = set(ep.tolist()) - special_token_ids tokenuni.append(len(prompt_set.intersection(ep_set)) / len(ep_set)) scores.append(torch.tensor(tokenuni).to("cpu", dtype=weight_dtype)) return torch.max(torch.stack(scores), dim=0)[0] @torch.no_grad() def infer_with_spm( dataloader: DataLoader, spm_paths: list[str], matching_metric: MATCHING_METRICS, facilitate_factor: float = 1.0, assigned_multipliers: list[float] = None, finetuned_model_path: str = None, sld_target_concept: str = None, base_model: str = "CompVis/stable-diffusion-v1-4", v2: bool = False, precision: str = "fp32", ): spm_model_paths = [ lp / f"{lp.name}_last.safetensors" if lp.is_dir() else lp for lp in spm_paths ] weight_dtype = config.parse_precision(precision) if finetuned_model_path is not None and Path(finetuned_model_path).is_dir(): # folder path for the diffuser model base_model = finetuned_model_path print(f"Using models from {base_model}") # load the pretrained SD tokenizer, text_encoder, unet, pipe = model_util.load_checkpoint_model( base_model, v2=v2, weight_dtype=weight_dtype, device=distributed_state.device, ) special_token_ids = set( tokenizer.convert_tokens_to_ids(tokenizer.special_tokens_map.values()) ) text_encoder.to(distributed_state.device, dtype=weight_dtype) text_encoder.eval() unet.to(distributed_state.device, dtype=weight_dtype) unet.enable_xformers_memory_efficient_attention() unet.requires_grad_(False) unet.eval() if len(spm_model_paths) > 0: # load the SPM models spms, metadatas = zip( *[ load_state_dict(spm_model_path, weight_dtype) for spm_model_path in spm_model_paths ] ) # check if SPMs are compatible assert all([metadata["rank"] == metadatas[0]["rank"] for metadata in metadatas]) # get the erased concept erased_prompts = [md["prompts"].split(",") for md in metadatas] erased_prompts_count = [len(ep) for ep in erased_prompts] print(f"Erased prompts: {erased_prompts}") erased_prompts_flatten = [item for sublist in erased_prompts for item in sublist] erased_prompt_embeds, erased_prompt_tokens = train_util.encode_prompts( tokenizer, text_encoder, erased_prompts_flatten, return_tokens=True ) # create the SPM network
network = SPMNetwork(
6
2023-12-26 03:19:16+00:00
16k
dakpinaroglu/Frame2seq
frame2seq/openfold/model/structure_module.py
[ { "identifier": "Linear", "path": "frame2seq/openfold/model/primitives.py", "snippet": "class Linear(nn.Linear):\n \"\"\"\n A Linear layer with built-in nonstandard initializations. Called just\n like torch.nn.Linear.\n\n Implements the initializers in 1.11.4, plus some additional ones found...
from functools import reduce from operator import mul from typing import Optional, Tuple, Sequence from frame2seq.openfold.model.primitives import Linear, LayerNorm, ipa_point_weights_init_ from frame2seq.openfold.np.residue_constants import ( restype_rigid_group_default_frame, restype_atom14_to_rigid_group, restype_atom14_mask, restype_atom14_rigid_group_positions, ) from frame2seq.openfold.utils.feats import ( frames_and_literature_positions_to_atom14_pos, torsion_angles_to_frames, ) from frame2seq.openfold.utils.precision_utils import is_fp16_enabled from frame2seq.openfold.utils.rigid_utils import Rotation, Rigid from frame2seq.openfold.utils.tensor_utils import ( dict_multimap, permute_final_dims, flatten_final_dims, ) import importlib import math import sys import torch import torch.nn as nn
12,511
# Copyright 2021 AlQuraishi Laboratory # Copyright 2021 DeepMind Technologies Limited # # 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. attn_core_inplace_cuda = False class AngleResnetBlock(nn.Module): def __init__(self, c_hidden): """ Args: c_hidden: Hidden channel dimension """ super(AngleResnetBlock, self).__init__() self.c_hidden = c_hidden
# Copyright 2021 AlQuraishi Laboratory # Copyright 2021 DeepMind Technologies Limited # # 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. attn_core_inplace_cuda = False class AngleResnetBlock(nn.Module): def __init__(self, c_hidden): """ Args: c_hidden: Hidden channel dimension """ super(AngleResnetBlock, self).__init__() self.c_hidden = c_hidden
self.linear_1 = Linear(self.c_hidden, self.c_hidden, init="relu")
0
2023-12-25 09:29:36+00:00
16k
KyanChen/TTP
mmseg/models/decode_heads/san_head.py
[ { "identifier": "TransformerEncoderLayer", "path": "mmseg/models/backbones/vit.py", "snippet": "class TransformerEncoderLayer(BaseModule):\n \"\"\"Implements one encoder layer in Vision Transformer.\n\n Args:\n embed_dims (int): The feature dimension.\n num_heads (int): Parallel atte...
from functools import partial from typing import Dict, List, Tuple from mmcv.cnn import ConvModule, build_norm_layer from mmcv.cnn.bricks.transformer import BaseTransformerLayer from mmcv.ops import point_sample from mmengine.dist import all_reduce from mmengine.model.weight_init import (caffe2_xavier_init, normal_init, trunc_normal_) from mmengine.runner.checkpoint import CheckpointLoader, load_state_dict from mmengine.structures import InstanceData from torch import Tensor from torch.nn import functional as F from mmseg.models.backbones.vit import TransformerEncoderLayer from mmseg.registry import MODELS from mmseg.utils import (ConfigType, MatchMasks, SampleList, seg_data_to_instance_data) from ..utils import (MLP, LayerNorm2d, PatchEmbed, cross_attn_layer, get_uncertain_point_coords_with_randomness, resize) from .decode_head import BaseDecodeHead import torch import torch.nn as nn
12,157
""" def __init__(self, num_classes: int, san_cfg: ConfigType, maskgen_cfg: ConfigType, deep_supervision_idxs: List[int], train_cfg: ConfigType, **kwargs): super().__init__( in_channels=san_cfg.in_channels, channels=san_cfg.embed_dims, num_classes=num_classes, **kwargs) assert san_cfg.num_queries == maskgen_cfg.sos_token_num, \ 'num_queries in san_cfg should be equal to sos_token_num ' \ 'in maskgen_cfg' del self.conv_seg self.side_adapter_network = SideAdapterNetwork(**san_cfg) self.rec_with_attnbias = RecWithAttnbias(**maskgen_cfg) self.deep_supervision_idxs = deep_supervision_idxs self.train_cfg = train_cfg if train_cfg: self.match_masks = MatchMasks( num_points=train_cfg.num_points, num_queries=san_cfg.num_queries, num_classes=num_classes, assigner=train_cfg.assigner) def init_weights(self): rec_state_dict = None if isinstance(self.init_cfg, dict) and \ self.init_cfg.get('type') == 'Pretrained_Part': checkpoint = CheckpointLoader.load_checkpoint( self.init_cfg['checkpoint'], logger=None, map_location='cpu') rec_state_dict = checkpoint.copy() para_prefix = 'decode_head.rec_with_attnbias' prefix_len = len(para_prefix) + 1 for k, v in checkpoint.items(): rec_state_dict.pop(k) if para_prefix in k: rec_state_dict[k[prefix_len:]] = v self.side_adapter_network.init_weights() self.rec_with_attnbias.init_weights(rec_state_dict) def forward(self, inputs: Tuple[Tensor], deep_supervision_idxs) -> Tuple[List]: """Forward function. Args: inputs (Tuple[Tensor]): A triplet including images, list of multi-level visual features from image encoder and class embeddings from text_encoder. Returns: mask_props (List[Tensor]): Mask proposals predicted by SAN. mask_logits (List[Tensor]): Class logits of mask proposals. """ imgs, clip_feature, class_embeds = inputs # predict mask proposals and attention bias mask_props, attn_biases = self.side_adapter_network( imgs, clip_feature, deep_supervision_idxs) # mask recognition with attention bias mask_embeds = [ self.rec_with_attnbias(att_bias, clip_feature[-1]) for att_bias in attn_biases ] # Obtain class prediction of masks by comparing the similarity # between the image token and the text embedding of class names. mask_logits = [ torch.einsum('bqc,nc->bqn', mask_embed, class_embeds) for mask_embed in mask_embeds ] return mask_props, mask_logits def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], test_cfg: ConfigType) -> Tensor: """Forward function for prediction. Args: inputs (Tuple[Tensor]): Images, visual features from image encoder and class embedding from text encoder. batch_img_metas (dict): List Image info where each dict may also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', 'ori_shape', and 'pad_shape'. For details on the values of these keys see `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. test_cfg (dict): The testing config. Returns: Tensor: Outputs segmentation logits map. """ mask_props, mask_logits = self.forward(inputs, []) return self.predict_by_feat([mask_props[-1], mask_logits[-1]], batch_img_metas) def predict_by_feat(self, seg_logits: List[Tensor], batch_img_metas: List[dict]) -> Tensor: """1. Transform a batch of mask proposals to the input shape. 2. Generate segmentation map with mask proposals and class logits. """ mask_pred = seg_logits[0] cls_score = seg_logits[1] if isinstance(batch_img_metas[0]['img_shape'], torch.Size): # slide inference size = batch_img_metas[0]['img_shape'] elif 'pad_shape' in batch_img_metas[0]: size = batch_img_metas[0]['pad_shape'][:2] else: size = batch_img_metas[0]['img_shape'] # upsample mask mask_pred = F.interpolate( mask_pred, size=size, mode='bilinear', align_corners=False) mask_cls = F.softmax(cls_score, dim=-1)[..., :-1] mask_pred = mask_pred.sigmoid() seg_logits = torch.einsum('bqc,bqhw->bchw', mask_cls, mask_pred) return seg_logits
# Copyright (c) OpenMMLab. All rights reserved. class MLPMaskDecoder(nn.Module): """Module for decoding query and visual features with MLP layers to generate the attention biases and the mask proposals.""" def __init__( self, *, in_channels: int, total_heads: int = 1, total_layers: int = 1, embed_channels: int = 256, mlp_channels: int = 256, mlp_num_layers: int = 3, rescale_attn_bias: bool = False, ): super().__init__() self.total_heads = total_heads self.total_layers = total_layers dense_affine_func = partial(nn.Conv2d, kernel_size=1) # Query Branch self.query_mlp = MLP(in_channels, mlp_channels, embed_channels, mlp_num_layers) # Pixel Branch self.pix_mlp = MLP( in_channels, mlp_channels, embed_channels, mlp_num_layers, affine_func=dense_affine_func, ) # Attention Bias Branch self.attn_mlp = MLP( in_channels, mlp_channels, embed_channels * self.total_heads * self.total_layers, mlp_num_layers, affine_func=dense_affine_func, ) if rescale_attn_bias: self.bias_scaling = nn.Linear(1, 1) else: self.bias_scaling = nn.Identity() def forward(self, query: torch.Tensor, x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: """Forward function. Args: query (Tensor): Query Tokens [B,N,C]. x (Tensor): Visual features [B,C,H,W] Return: mask_preds (Tensor): Mask proposals. attn_bias (List[Tensor]): List of attention bias. """ query = self.query_mlp(query) pix = self.pix_mlp(x) b, c, h, w = pix.shape # preidict mask mask_preds = torch.einsum('bqc,bchw->bqhw', query, pix) # generate attn bias attn = self.attn_mlp(x) attn = attn.reshape(b, self.total_layers, self.total_heads, c, h, w) attn_bias = torch.einsum('bqc,blnchw->blnqhw', query, attn) attn_bias = self.bias_scaling(attn_bias[..., None]).squeeze(-1) attn_bias = attn_bias.chunk(self.total_layers, dim=1) attn_bias = [attn.squeeze(1) for attn in attn_bias] return mask_preds, attn_bias class SideAdapterNetwork(nn.Module): """Side Adapter Network for predicting mask proposals and attention bias. Args: in_channels (int): Number of input channels. Default: 3. clip_channels (int): Number of channels of visual features. Default: 768. embed_dims (int): embedding dimension. Default: 240. patch_size (int): The patch size. Default: 16. patch_bias (bool): Whether use bias in patch embedding. Default: True. num_queries (int): Number of queries for mask proposals. Default: 100. fusion_index (List[int]): The layer number of the encode transformer to fuse with the CLIP feature. Default: [0, 1, 2, 3]. cfg_encoder (ConfigType): Configs for the encode layers. cfg_decoder (ConfigType): Configs for the decode layers. norm_cfg (dict): Config dict for normalization layer. Default: dict(type='LN'). """ def __init__( self, in_channels: int = 3, clip_channels: int = 768, embed_dims: int = 240, patch_size: int = 16, patch_bias: bool = True, num_queries: int = 100, fusion_index: list = [0, 1, 2, 3], cfg_encoder: ConfigType = ..., cfg_decoder: ConfigType = ..., norm_cfg: dict = dict(type='LN'), ): super().__init__() self.patch_embed = PatchEmbed( in_channels=in_channels, embed_dims=embed_dims, conv_type='Conv2d', kernel_size=patch_size, stride=patch_size, padding=0, input_size=(640, 640), bias=patch_bias, norm_cfg=None, init_cfg=None, ) ori_h, ori_w = self.patch_embed.init_out_size num_patches = ori_h * ori_w self.pos_embed = nn.Parameter( torch.randn(1, num_patches, embed_dims) * .02) self.query_pos_embed = nn.Parameter( torch.zeros(1, num_queries, embed_dims)) self.query_embed = nn.Parameter( torch.zeros(1, num_queries, embed_dims)) encode_layers = [] for i in range(cfg_encoder.num_encode_layer): encode_layers.append( TransformerEncoderLayer( embed_dims=embed_dims, num_heads=cfg_encoder.num_heads, feedforward_channels=cfg_encoder.mlp_ratio * embed_dims, norm_cfg=norm_cfg)) self.encode_layers = nn.ModuleList(encode_layers) conv_clips = [] for i in range(len(fusion_index)): conv_clips.append( nn.Sequential( LayerNorm2d(clip_channels), ConvModule( clip_channels, embed_dims, kernel_size=1, norm_cfg=None, act_cfg=None))) self.conv_clips = nn.ModuleList(conv_clips) self.fusion_index = fusion_index self.mask_decoder = MLPMaskDecoder( in_channels=embed_dims, total_heads=cfg_decoder.num_heads, total_layers=cfg_decoder.num_layers, embed_channels=cfg_decoder.embed_channels, mlp_channels=cfg_decoder.mlp_channels, mlp_num_layers=cfg_decoder.num_mlp, rescale_attn_bias=cfg_decoder.rescale) def init_weights(self): trunc_normal_(self.pos_embed, std=0.02) nn.init.normal_(self.query_embed, std=0.02) nn.init.normal_(self.query_pos_embed, std=0.02) for i in range(len(self.conv_clips)): caffe2_xavier_init(self.conv_clips[i][1].conv) def fuse_clip(self, fused_index: int, x: torch.Tensor, clip_feature: torch.Tensor, hwshape: Tuple[int, int], L: int): """Fuse CLIP feature and visual tokens.""" fused_clip = (resize( self.conv_clips[fused_index](clip_feature.contiguous()), size=hwshape, mode='bilinear', align_corners=False)).permute(0, 2, 3, 1).reshape(x[:, -L:, ...].shape) x = torch.cat([x[:, :-L, ...], x[:, -L:, ...] + fused_clip], dim=1) return x def encode_feature(self, image: torch.Tensor, clip_features: List[torch.Tensor], deep_supervision_idxs: List[int]) -> List[List]: """Encode images by a lightweight vision transformer.""" assert len(self.fusion_index) == len(clip_features) x, hwshape = self.patch_embed(image) ori_h, ori_w = self.patch_embed.init_out_size pos_embed = self.pos_embed if self.pos_embed.shape[1] != x.shape[1]: # resize the position embedding pos_embed = ( resize( self.pos_embed.reshape(1, ori_h, ori_w, -1).permute(0, 3, 1, 2), size=hwshape, mode='bicubic', align_corners=False, ).flatten(2).permute(0, 2, 1)) pos_embed = torch.cat([ self.query_pos_embed.expand(pos_embed.shape[0], -1, -1), pos_embed ], dim=1) x = torch.cat([self.query_embed.expand(x.shape[0], -1, -1), x], dim=1) x = x + pos_embed L = hwshape[0] * hwshape[1] fused_index = 0 if self.fusion_index[fused_index] == 0: x = self.fuse_clip(fused_index, x, clip_features[0][0], hwshape, L) fused_index += 1 outs = [] for index, block in enumerate(self.encode_layers, start=1): x = block(x) if index < len(self.fusion_index ) and index == self.fusion_index[fused_index]: x = self.fuse_clip(fused_index, x, clip_features[fused_index][0], hwshape, L) fused_index += 1 x_query = x[:, :-L, ...] x_feat = x[:, -L:, ...].permute(0, 2, 1)\ .reshape(x.shape[0], x.shape[-1], hwshape[0], hwshape[1]) if index in deep_supervision_idxs or index == len( self.encode_layers): outs.append({'query': x_query, 'x': x_feat}) if index < len(self.encode_layers): x = x + pos_embed return outs def decode_feature(self, features): mask_embeds = [] attn_biases = [] for feature in features: mask_embed, attn_bias = self.mask_decoder(**feature) mask_embeds.append(mask_embed) attn_biases.append(attn_bias) return mask_embeds, attn_biases def forward( self, image: torch.Tensor, clip_features: List[torch.Tensor], deep_supervision_idxs: List[int] ) -> Tuple[List[torch.Tensor], List[List[torch.Tensor]]]: """Forward function.""" features = self.encode_feature(image, clip_features, deep_supervision_idxs) mask_embeds, attn_biases = self.decode_feature(features) return mask_embeds, attn_biases class RecWithAttnbias(nn.Module): """Mask recognition module by applying the attention biases to rest deeper CLIP layers. Args: sos_token_format (str): The format of sos token. It should be chosen from ["cls_token", "learnable_token", "pos_embedding"]. Default: 'cls_token'. sos_token_num (int): Number of sos token. It should be equal to the number of quries. Default: 100. num_layers (int): Number of rest CLIP layers for mask recognition. Default: 3. cross_attn (bool): Whether use cross attention to update sos token. Default: False. embed_dims (int): The feature dimension of CLIP layers. Default: 768. num_heads (int): Parallel attention heads of CLIP layers. Default: 768. mlp_ratio (int): Ratio of mlp hidden dim to embedding dim. Default: 4. qkv_bias (bool): Whether to use bias in multihead-attention. Default: True. out_dims (int): Number of channels of the output mask proposals. It should be equal to the out_dims of text_encoder. Default: 512. final_norm (True): Whether use norm layer for sos token. act_cfg (dict): The activation config for FFNs. Default: dict(type='GELU'). norm_cfg (dict): Config dict for normalization layer. Default: dict(type='LN'). frozen_exclude (List): List of parameters that are not to be frozen. """ def __init__(self, sos_token_format: str = 'cls_token', sos_token_num: int = 100, num_layers: int = 3, cross_attn: bool = False, embed_dims: int = 768, num_heads: int = 12, mlp_ratio: int = 4, num_fcs: int = 2, qkv_bias: bool = True, out_dims: int = 512, final_norm: bool = True, act_cfg: dict = dict(type='GELU'), norm_cfg: dict = dict(type='LN'), frozen_exclude: List = []): super().__init__() assert sos_token_format in [ 'cls_token', 'learnable_token', 'pos_embedding' ] self.sos_token_format = sos_token_format self.sos_token_num = sos_token_num self.frozen_exclude = frozen_exclude self.cross_attn = cross_attn self.num_layers = num_layers self.num_heads = num_heads if sos_token_format in ['learnable_token', 'pos_embedding']: self.sos_token = nn.Parameter( torch.randn(sos_token_num, 1, self.proj.shape[0])) self.frozen.append('sos_token') layers = [] for i in range(num_layers): layers.append( BaseTransformerLayer( attn_cfgs=dict( type='MultiheadAttention', embed_dims=embed_dims, num_heads=num_heads, batch_first=False, bias=qkv_bias), ffn_cfgs=dict( type='FFN', embed_dims=embed_dims, feedforward_channels=mlp_ratio * embed_dims, act_cfg=act_cfg), operation_order=('norm', 'self_attn', 'norm', 'ffn'))) self.layers = nn.ModuleList(layers) self.ln_post = build_norm_layer(norm_cfg, embed_dims)[1] self.proj = nn.Linear(embed_dims, out_dims, bias=False) self.final_norm = final_norm self._freeze() def init_weights(self, rec_state_dict): if hasattr(self, 'sos_token'): normal_init(self.sos_token, std=0.02) if rec_state_dict is not None: load_state_dict(self, rec_state_dict, strict=False, logger=None) else: super().init_weights() def _freeze(self): if 'all' in self.frozen_exclude: return for name, param in self.named_parameters(): if not any([exclude in name for exclude in self.frozen_exclude]): param.requires_grad = False def _build_attn_biases(self, attn_biases, target_shape): formatted_attn_biases = [] for attn_bias in attn_biases: # convert it to proper format: N*num_head,L,L # attn_bias: [N, num_head/1, num_sos,H,W] n, num_head, num_sos, h, w = attn_bias.shape # reshape and downsample attn_bias = F.adaptive_max_pool2d( attn_bias.reshape(n, num_head * num_sos, h, w), output_size=target_shape) attn_bias = attn_bias.reshape(n, num_head, num_sos, *target_shape) true_num_head = self.num_heads assert (num_head == 1 or num_head == true_num_head), f'num_head={num_head} is not supported.' if num_head == 1: attn_bias = attn_bias.repeat(1, true_num_head, 1, 1, 1) attn_bias = attn_bias.reshape(n * true_num_head, num_sos, -1) L = attn_bias.shape[-1] if self.cross_attn: # [n*num_head, num_sos, L] formatted_attn_biases.append(attn_bias) else: # [n*num_head, num_sos+1+L, num_sos+1+L] new_attn_bias = attn_bias.new_zeros(num_sos + 1 + L, num_sos + 1 + L) new_attn_bias[:, :num_sos] = -100 new_attn_bias[torch.arange(num_sos), torch.arange(num_sos)] = 0 new_attn_bias[:num_sos, num_sos] = -100 new_attn_bias = ( new_attn_bias[None, ...].expand(n * true_num_head, -1, -1).clone()) new_attn_bias[..., :num_sos, -L:] = attn_bias formatted_attn_biases.append(new_attn_bias) if len(formatted_attn_biases) == 1: formatted_attn_biases = [ formatted_attn_biases[0] for _ in range(self.num_layers) ] return formatted_attn_biases def forward(self, bias: List[Tensor], feature: List[Tensor]): """Forward function to recognize the category of masks Args: bias (List[Tensor]): Attention bias for transformer layers feature (List[Tensor]): Output of the image encoder, including cls_token and img_feature. """ cls_token = feature[1].unsqueeze(0) img_feature = feature[0] b, c, h, w = img_feature.shape # construct clip shadow features x = torch.cat( [cls_token, img_feature.reshape(b, c, -1).permute(2, 0, 1)]) # construct sos token if self.sos_token_format == 'cls_token': sos_token = cls_token.repeat(self.sos_token_num, 1, 1) elif self.sos_token_format == 'learnable_token': sos_token = self.sos_token.expand(-1, b, -1) elif self.sos_token_format == 'pos_embedding': sos_token = self.sos_token.expand(-1, b, -1) + cls_token # construct attn bias attn_biases = self._build_attn_biases(bias, target_shape=(h, w)) if self.cross_attn: for i, block in enumerate(self.layers): if self.cross_attn: sos_token = cross_attn_layer( block, sos_token, x[1:, ], attn_biases[i], ) if i < len(self.layers) - 1: x = block(x) else: x = torch.cat([sos_token, x], dim=0) for i, block in enumerate(self.layers): x = block(x, attn_masks=[attn_biases[i]]) sos_token = x[:self.sos_token_num] sos_token = sos_token.permute(1, 0, 2) # LND -> NLD sos_token = self.ln_post(sos_token) sos_token = self.proj(sos_token) if self.final_norm: sos_token = F.normalize(sos_token, dim=-1) return sos_token @MODELS.register_module() class SideAdapterCLIPHead(BaseDecodeHead): """Side Adapter Network (SAN) for open-vocabulary semantic segmentation with pre-trained vision-language model. This decode head is the implementation of `Side Adapter Network for Open-Vocabulary Semantic Segmentation` <https://arxiv.org/abs/2302.12242>. Modified from https://github.com/MendelXu/SAN/blob/main/san/model/side_adapter/side_adapter.py # noqa:E501 Copyright (c) 2023 MendelXu. Licensed under the MIT License Args: num_classes (int): the number of classes. san_cfg (ConfigType): Configs for SideAdapterNetwork module maskgen_cfg (ConfigType): Configs for RecWithAttnbias module """ def __init__(self, num_classes: int, san_cfg: ConfigType, maskgen_cfg: ConfigType, deep_supervision_idxs: List[int], train_cfg: ConfigType, **kwargs): super().__init__( in_channels=san_cfg.in_channels, channels=san_cfg.embed_dims, num_classes=num_classes, **kwargs) assert san_cfg.num_queries == maskgen_cfg.sos_token_num, \ 'num_queries in san_cfg should be equal to sos_token_num ' \ 'in maskgen_cfg' del self.conv_seg self.side_adapter_network = SideAdapterNetwork(**san_cfg) self.rec_with_attnbias = RecWithAttnbias(**maskgen_cfg) self.deep_supervision_idxs = deep_supervision_idxs self.train_cfg = train_cfg if train_cfg: self.match_masks = MatchMasks( num_points=train_cfg.num_points, num_queries=san_cfg.num_queries, num_classes=num_classes, assigner=train_cfg.assigner) def init_weights(self): rec_state_dict = None if isinstance(self.init_cfg, dict) and \ self.init_cfg.get('type') == 'Pretrained_Part': checkpoint = CheckpointLoader.load_checkpoint( self.init_cfg['checkpoint'], logger=None, map_location='cpu') rec_state_dict = checkpoint.copy() para_prefix = 'decode_head.rec_with_attnbias' prefix_len = len(para_prefix) + 1 for k, v in checkpoint.items(): rec_state_dict.pop(k) if para_prefix in k: rec_state_dict[k[prefix_len:]] = v self.side_adapter_network.init_weights() self.rec_with_attnbias.init_weights(rec_state_dict) def forward(self, inputs: Tuple[Tensor], deep_supervision_idxs) -> Tuple[List]: """Forward function. Args: inputs (Tuple[Tensor]): A triplet including images, list of multi-level visual features from image encoder and class embeddings from text_encoder. Returns: mask_props (List[Tensor]): Mask proposals predicted by SAN. mask_logits (List[Tensor]): Class logits of mask proposals. """ imgs, clip_feature, class_embeds = inputs # predict mask proposals and attention bias mask_props, attn_biases = self.side_adapter_network( imgs, clip_feature, deep_supervision_idxs) # mask recognition with attention bias mask_embeds = [ self.rec_with_attnbias(att_bias, clip_feature[-1]) for att_bias in attn_biases ] # Obtain class prediction of masks by comparing the similarity # between the image token and the text embedding of class names. mask_logits = [ torch.einsum('bqc,nc->bqn', mask_embed, class_embeds) for mask_embed in mask_embeds ] return mask_props, mask_logits def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], test_cfg: ConfigType) -> Tensor: """Forward function for prediction. Args: inputs (Tuple[Tensor]): Images, visual features from image encoder and class embedding from text encoder. batch_img_metas (dict): List Image info where each dict may also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', 'ori_shape', and 'pad_shape'. For details on the values of these keys see `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. test_cfg (dict): The testing config. Returns: Tensor: Outputs segmentation logits map. """ mask_props, mask_logits = self.forward(inputs, []) return self.predict_by_feat([mask_props[-1], mask_logits[-1]], batch_img_metas) def predict_by_feat(self, seg_logits: List[Tensor], batch_img_metas: List[dict]) -> Tensor: """1. Transform a batch of mask proposals to the input shape. 2. Generate segmentation map with mask proposals and class logits. """ mask_pred = seg_logits[0] cls_score = seg_logits[1] if isinstance(batch_img_metas[0]['img_shape'], torch.Size): # slide inference size = batch_img_metas[0]['img_shape'] elif 'pad_shape' in batch_img_metas[0]: size = batch_img_metas[0]['pad_shape'][:2] else: size = batch_img_metas[0]['img_shape'] # upsample mask mask_pred = F.interpolate( mask_pred, size=size, mode='bilinear', align_corners=False) mask_cls = F.softmax(cls_score, dim=-1)[..., :-1] mask_pred = mask_pred.sigmoid() seg_logits = torch.einsum('bqc,bqhw->bchw', mask_cls, mask_pred) return seg_logits
def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList,
2
2023-12-23 08:36:47+00:00
16k
see2023/Bert-VITS2-ext
train_ms.py
[ { "identifier": "config", "path": "config.py", "snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, ...
import platform import os import torch import torch.distributed as dist import logging import argparse import datetime import gc import commons import utils from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from config import config from data_utils import ( TextAudioSpeakerLoader, TextAudioSpeakerCollate, DistributedBucketSampler, AudioVisemesLoader, ) from models import ( SynthesizerTrn, MultiPeriodDiscriminator, DurationDiscriminator, WavLMDiscriminator, VisemesNet, ) from losses import ( generator_loss, discriminator_loss, feature_loss, kl_loss, WavLMLoss, ) from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols
13,146
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) logger = logging.getLogger(__name__) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 global_step = 0 global_visemes_step = 0 def run_only_visemes(hps): # 使用最简单的单机模式,仅训练隐变量z到表情(visemes)的全连接 VisemesFCNet 的参数 global global_visemes_step torch.manual_seed(hps.train.seed) torch.cuda.set_device(0)
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) logger = logging.getLogger(__name__) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 global_step = 0 global_visemes_step = 0 def run_only_visemes(hps): # 使用最简单的单机模式,仅训练隐变量z到表情(visemes)的全连接 VisemesFCNet 的参数 global global_visemes_step torch.manual_seed(hps.train.seed) torch.cuda.set_device(0)
train_dataset = AudioVisemesLoader(hps.data.training_visemes_files, hps.data)
4
2023-12-27 03:09:11+00:00
16k
chinhsuanwu/ifusion-threestudio
threestudio/systems/base.py
[ { "identifier": "Exporter", "path": "threestudio/models/exporters/base.py", "snippet": "class Exporter(BaseObject):\n @dataclass\n class Config(BaseObject.Config):\n save_video: bool = False\n\n cfg: Config\n\n def configure(\n self,\n geometry: BaseImplicitGeometry,\n ...
import os import pytorch_lightning as pl import torch.nn.functional as F import threestudio from dataclasses import dataclass, field from threestudio.models.exporters.base import Exporter, ExporterOutput from threestudio.systems.utils import parse_optimizer, parse_scheduler from threestudio.utils.base import ( Updateable, update_end_if_possible, update_if_possible, ) from threestudio.utils.config import parse_structured from threestudio.utils.misc import ( C, cleanup, find_last_path, get_device, load_module_weights, ) from threestudio.utils.saving import SaverMixin from threestudio.utils.typing import * from threestudio.utils.config import load_config, parse_structured
11,182
norms = grad_norm(self.geometry, norm_type=2) print(norms) """ pass class BaseLift3DSystem(BaseSystem): @dataclass class Config(BaseSystem.Config): geometry_type: str = "" geometry: dict = field(default_factory=dict) geometry_convert_from: Optional[str] = None geometry_convert_inherit_texture: bool = False # used to override configurations of the previous geometry being converted from, # for example isosurface_threshold geometry_convert_override: dict = field(default_factory=dict) material_type: str = "" material: dict = field(default_factory=dict) background_type: str = "" background: dict = field(default_factory=dict) renderer_type: str = "" renderer: dict = field(default_factory=dict) guidance_type: str = "" guidance: dict = field(default_factory=dict) prompt_processor_type: str = "" prompt_processor: dict = field(default_factory=dict) # geometry export configurations, no need to specify in training exporter_type: str = "mesh-exporter" exporter: dict = field(default_factory=dict) cfg: Config def configure(self) -> None: self.cfg.geometry_convert_from = find_last_path(self.cfg.geometry_convert_from) self.cfg.weights = find_last_path(self.cfg.weights) if ( self.cfg.geometry_convert_from # from_coarse must be specified and not self.cfg.weights # not initialized from coarse when weights are specified and not self.resumed # not initialized from coarse when resumed from checkpoints ): threestudio.info("Initializing geometry from a given checkpoint ...") prev_cfg = load_config( os.path.join( os.path.dirname(self.cfg.geometry_convert_from), "../configs/parsed.yaml", ) ) # TODO: hard-coded relative path prev_system_cfg: BaseLift3DSystem.Config = parse_structured( self.Config, prev_cfg.system ) prev_geometry_cfg = prev_system_cfg.geometry prev_geometry_cfg.update(self.cfg.geometry_convert_override) prev_geometry = threestudio.find(prev_system_cfg.geometry_type)( prev_geometry_cfg ) state_dict, epoch, global_step = load_module_weights( self.cfg.geometry_convert_from, module_name="geometry", map_location="cpu", ) prev_geometry.load_state_dict(state_dict, strict=False) # restore step-dependent states prev_geometry.do_update_step(epoch, global_step, on_load_weights=True) # convert from coarse stage geometry prev_geometry = prev_geometry.to(get_device()) self.geometry = threestudio.find(self.cfg.geometry_type).create_from( prev_geometry, self.cfg.geometry, copy_net=self.cfg.geometry_convert_inherit_texture, ) del prev_geometry cleanup() else: self.geometry = threestudio.find(self.cfg.geometry_type)(self.cfg.geometry) self.material = threestudio.find(self.cfg.material_type)(self.cfg.material) self.background = threestudio.find(self.cfg.background_type)( self.cfg.background ) self.renderer = threestudio.find(self.cfg.renderer_type)( self.cfg.renderer, geometry=self.geometry, material=self.material, background=self.background, ) def on_fit_start(self) -> None: if self._save_dir is not None: threestudio.info(f"Validation results will be saved to {self._save_dir}") else: threestudio.warn( f"Saving directory not set for the system, visualization results will not be saved" ) def on_test_end(self) -> None: if self._save_dir is not None: threestudio.info(f"Test results saved to {self._save_dir}") def on_predict_start(self) -> None: self.exporter: Exporter = threestudio.find(self.cfg.exporter_type)( self.cfg.exporter, geometry=self.geometry, material=self.material, background=self.background, ) def predict_step(self, batch, batch_idx): if self.exporter.cfg.save_video: self.test_step(batch, batch_idx) def on_predict_epoch_end(self) -> None: if self.exporter.cfg.save_video: self.on_test_epoch_end()
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None): state_dict, epoch, global_step = load_module_weights( weights, ignore_modules=ignore_modules, map_location="cpu" ) self.load_state_dict(state_dict, strict=False) # restore step-dependent states self.do_update_step(epoch, global_step, on_load_weights=True) def set_resume_status(self, current_epoch: int, global_step: int): # restore correct epoch and global step in eval self._resumed_eval = True self._resumed_eval_status["current_epoch"] = current_epoch self._resumed_eval_status["global_step"] = global_step @property def resumed(self): # whether from resumed checkpoint return self._resumed @property def true_global_step(self): if self._resumed_eval: return self._resumed_eval_status["global_step"] else: return self.global_step @property def true_current_epoch(self): if self._resumed_eval: return self._resumed_eval_status["current_epoch"] else: return self.current_epoch def configure(self) -> None: pass def post_configure(self) -> None: """ executed after weights are loaded """ pass def C(self, value: Any) -> float: return C(value, self.true_current_epoch, self.true_global_step) def configure_optimizers(self): optim = parse_optimizer(self.cfg.optimizer, self) ret = { "optimizer": optim, } if self.cfg.scheduler is not None: ret.update( { "lr_scheduler": parse_scheduler(self.cfg.scheduler, optim), } ) return ret def training_step(self, batch, batch_idx): raise NotImplementedError def validation_step(self, batch, batch_idx): raise NotImplementedError def on_train_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.train_dataloader.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) def on_validation_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.val_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_validation_step: # cleanup to save vram cleanup() def on_validation_epoch_end(self): raise NotImplementedError def test_step(self, batch, batch_idx): raise NotImplementedError def on_test_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.test_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_test_epoch_end(self): pass def predict_step(self, batch, batch_idx): raise NotImplementedError def on_predict_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.predict_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_predict_epoch_end(self): pass def preprocess_data(self, batch, stage): pass """ Implementing on_after_batch_transfer of DataModule does the same. But on_after_batch_transfer does not support DP. """ def on_train_batch_start(self, batch, batch_idx, unused=0): self.preprocess_data(batch, "train") self.dataset = self.trainer.train_dataloader.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_validation_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "validation") self.dataset = self.trainer.val_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_test_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "test") self.dataset = self.trainer.test_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_predict_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "predict") self.dataset = self.trainer.predict_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False): pass def on_before_optimizer_step(self, optimizer): """ # some gradient-related debugging goes here, example: from lightning.pytorch.utilities import grad_norm norms = grad_norm(self.geometry, norm_type=2) print(norms) """ pass class BaseLift3DSystem(BaseSystem): @dataclass class Config(BaseSystem.Config): geometry_type: str = "" geometry: dict = field(default_factory=dict) geometry_convert_from: Optional[str] = None geometry_convert_inherit_texture: bool = False # used to override configurations of the previous geometry being converted from, # for example isosurface_threshold geometry_convert_override: dict = field(default_factory=dict) material_type: str = "" material: dict = field(default_factory=dict) background_type: str = "" background: dict = field(default_factory=dict) renderer_type: str = "" renderer: dict = field(default_factory=dict) guidance_type: str = "" guidance: dict = field(default_factory=dict) prompt_processor_type: str = "" prompt_processor: dict = field(default_factory=dict) # geometry export configurations, no need to specify in training exporter_type: str = "mesh-exporter" exporter: dict = field(default_factory=dict) cfg: Config def configure(self) -> None: self.cfg.geometry_convert_from = find_last_path(self.cfg.geometry_convert_from) self.cfg.weights = find_last_path(self.cfg.weights) if ( self.cfg.geometry_convert_from # from_coarse must be specified and not self.cfg.weights # not initialized from coarse when weights are specified and not self.resumed # not initialized from coarse when resumed from checkpoints ): threestudio.info("Initializing geometry from a given checkpoint ...") prev_cfg = load_config( os.path.join( os.path.dirname(self.cfg.geometry_convert_from), "../configs/parsed.yaml", ) ) # TODO: hard-coded relative path prev_system_cfg: BaseLift3DSystem.Config = parse_structured( self.Config, prev_cfg.system ) prev_geometry_cfg = prev_system_cfg.geometry prev_geometry_cfg.update(self.cfg.geometry_convert_override) prev_geometry = threestudio.find(prev_system_cfg.geometry_type)( prev_geometry_cfg ) state_dict, epoch, global_step = load_module_weights( self.cfg.geometry_convert_from, module_name="geometry", map_location="cpu", ) prev_geometry.load_state_dict(state_dict, strict=False) # restore step-dependent states prev_geometry.do_update_step(epoch, global_step, on_load_weights=True) # convert from coarse stage geometry prev_geometry = prev_geometry.to(get_device()) self.geometry = threestudio.find(self.cfg.geometry_type).create_from( prev_geometry, self.cfg.geometry, copy_net=self.cfg.geometry_convert_inherit_texture, ) del prev_geometry cleanup() else: self.geometry = threestudio.find(self.cfg.geometry_type)(self.cfg.geometry) self.material = threestudio.find(self.cfg.material_type)(self.cfg.material) self.background = threestudio.find(self.cfg.background_type)( self.cfg.background ) self.renderer = threestudio.find(self.cfg.renderer_type)( self.cfg.renderer, geometry=self.geometry, material=self.material, background=self.background, ) def on_fit_start(self) -> None: if self._save_dir is not None: threestudio.info(f"Validation results will be saved to {self._save_dir}") else: threestudio.warn( f"Saving directory not set for the system, visualization results will not be saved" ) def on_test_end(self) -> None: if self._save_dir is not None: threestudio.info(f"Test results saved to {self._save_dir}") def on_predict_start(self) -> None: self.exporter: Exporter = threestudio.find(self.cfg.exporter_type)( self.cfg.exporter, geometry=self.geometry, material=self.material, background=self.background, ) def predict_step(self, batch, batch_idx): if self.exporter.cfg.save_video: self.test_step(batch, batch_idx) def on_predict_epoch_end(self) -> None: if self.exporter.cfg.save_video: self.on_test_epoch_end()
exporter_output: List[ExporterOutput] = self.exporter()
1
2023-12-27 20:30:33+00:00
16k
gardenifi/server
app/raspi/mqtt.py
[ { "identifier": "Services", "path": "app/raspi/services.py", "snippet": "class Services:\n \"\"\"\n The `Services` class provides various methods for managing and controlling\n services related to a Raspberry Pi device, such as turning on/off valves,\n storing and deleting program cycles, lo...
import time import os import json import threading import sys import paho.mqtt.client as mqtt from threading import Thread from loguru import logger from app.raspi.services import Services from app.raspi.const import ( MQTT_CLIENT_ID, MQTT_TOPIC_STATUS, MQTT_TOPIC_METADATA, MQTT_TOPIC_CONFIG, MQTT_TOPIC_CMD, MQTT_TOPIC_VALVES, MQTT_STATUS_ERR, PROGRAM, PROGRAM_EXT, MQTT_STATUS_OK, MQTT_OK, MQTT_END, MQTT_USER, MQTT_PASS, MQTT_HOST, MQTT_PORT, ) from app.raspi.helpers import Helpers from app.raspi.const import Command
11,026
) Mqtt().get_periodic_updates_thread().start() else: logger.info(f"Connect returned result code: {return_code}") @staticmethod def handle_valves(client, data): """Handle valves.""" try: logger.info(f"valves data received={data}") Helpers().set_valves(data) except Exception as exception: logger.error(f"Error: {exception}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + str(exception)[0:128] + MQTT_END) # Program Configuration handler # 1. It should parse the configuration as a JSON string # 2. If it is correct it should store it as a local file # 3. A scheduler should launch to turn on the irrigator for every cycle @staticmethod def handle_config(client, data): """Handle cfg.""" try: json_data = json.loads(data) logger.info(f"prestored programs={json_data}") for program in json_data: logger.info(f"program={program}") if program == {}: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) return Services().store_program_cycles(program, True) Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) except Exception as exception: logger.error(f"Error: {exception}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + str(exception)[0:128] + MQTT_END) @staticmethod def handle_command(client, data): """Handle cmd.""" try: json_data = json.loads(data) logger.info(json_data) cmd = json_data["cmd"] command = Command(cmd) try: valve = json_data["out"] except Exception as exception: logger.warning( f"Could not find valve out parameter. \ Will use valve 1: {exception}" ) valve = 1 file_path = PROGRAM + str(valve) + PROGRAM_EXT if command in (Command.TURN_ON_VALVE, Command.TURN_OFF_VALVE): Helpers().toggle(cmd, "out" + str(valve)) statuses = Helpers().get_toggle_statuses() logger.info(f"Publishing right away Statuses to MQTT topic: {MQTT_TOPIC_STATUS}: {statuses}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, str(statuses)) elif command == Command.SEND_PROGRAM: logger.info(f"Looking for {file_path}") if os.path.exists(file_path): logger.info(f"{file_path} exists!") with open(file_path, encoding="utf-8") as json_file: json_data = json.load(json_file) Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, str(json_data)) else: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + file_path + " does not exist!" + MQTT_END) elif command == Command.DELETE_PROGRAM: if not Services().delete_program(valve): Mqtt.publish_to_topic( client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + file_path + " does not exist! Cannot be deleted." + MQTT_END ) elif command == Command.SEND_TIMEZONE: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + str(Helpers().get_timezone() + MQTT_END)) elif command == Command.REBOOT_RPI: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) Helpers().system_reboot() elif command == Command.UPDATE_RPI: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) Helpers().system_update() else: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + "Wrong command used!" + MQTT_END) except Exception as exception: logger.error(f"Error: {exception}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + str(exception)[0:128] + MQTT_END) @staticmethod def publish_to_topic(client, topic, data, retained=True): """Publish to MQTT Topic.""" client.publish(topic, data, qos=2, retain=retained) # The callback for when a PUBLISH message is received from the server. @staticmethod def on_message(client, userdata, msg): """OnMessage handler.""" topic = msg.topic data = msg.payload.decode("utf-8") logger.info(f"Received message from topic:{topic}, userdata:{userdata}, data:{data}") if topic == MQTT_TOPIC_CONFIG: Mqtt.handle_config(client, data) elif msg.topic == MQTT_TOPIC_CMD: Mqtt.handle_command(client, data) elif msg.topic == MQTT_TOPIC_VALVES: Mqtt.handle_valves(client, data) @staticmethod def send_periodic_updates(client): """Send periodic updates.""" while True: try: logger.info("Sending Periodic Updates to status topic every 10s...") statuses = Helpers().get_toggle_statuses() logger.info(f"Publishing Statuses to MQTT topic: {MQTT_TOPIC_STATUS}: {statuses}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, str(statuses)) metadata = {} metadata["ip_address"] = Helpers().extract_local_ip() metadata["uptime"] = Helpers().get_uptime() metadata["git_commit"] = Helpers().get_git_commit_id()
"""MIT License Copyright (c) 2023, Marios Karagiannopoulos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. **Attribution Requirement:** When using or distributing the software, an attribution to Marios Karagiannopoulos must be included. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class Mqtt: """MQTT Methods Class.""" __instance = None __lock = threading.Lock() client = None def __new__(cls): """ Create a new instance of the Mqtt class using the singleton design pattern. Returns: An instance of the Mqtt class. Example Usage: instance = Mqtt() """ if cls.__instance is None: with cls.__lock: cls.__instance = super().__new__(cls) # pylint: disable=duplicate-code cls._mqtt_thread = None cls._periodic_updates_thread = None logger.debug(f"Returning Mqtt Object Class: {cls.__instance}") return cls.__instance @classmethod def destroy_instance(cls): """ Destroy the instance of the Mqtt class. This method sets the instance of the Mqtt class to None, effectively destroying the instance. Example Usage: ```python instance = Mqtt() # Create an instance of the Mqtt class Mqtt.destroy_instance() # Destroy the instance print(instance) # Output: None ``` Inputs: None Outputs: None """ logger.debug(f"Destroying Mqtt Object Class: {cls.__instance}") cls.__instance = None cls._mqtt_thread = None cls._periodic_updates_thread = None def get_mqtt_thread(self): """Getter.""" logger.debug(f"Getting current thread: {self._mqtt_thread}") return self._mqtt_thread def set_mqtt_thread(self, mqtt_thread): """Setter.""" logger.debug(f"Setting new thread: {mqtt_thread}") self._mqtt_thread = mqtt_thread def get_periodic_updates_thread(self): """Getter.""" return self._periodic_updates_thread def set_periodic_updates_thread(self, periodic_updates_thread): """Setter.""" self._periodic_updates_thread = periodic_updates_thread def is_running(self): """Check whether mqtt thread state.""" # logger.info(str(mqtt_thread)) # logger.info(str(mqtt_thread is not None)) # logger.info(str(mqtt_thread.is_alive())) return self._mqtt_thread is not None and self._mqtt_thread.is_alive() @staticmethod def on_disconnect(client, data, return_code=0): """OnDisconnect callback.""" logger.debug(f"MQTT OnDisconnect: {client}:{data}:{return_code}") # The callback for when the client # receives a CONNACK response from the server. @staticmethod def on_connect(client, userdata, flags, return_code): """OnConnect callback.""" logger.debug(f"MQTT OnConnect: {client}:{userdata}:{flags}:{return_code}") client.connected_flag = True # subscribe to the RASPIRRI TOPICS logger.debug( f"MQTT OnConnect: Subscribing to topics:\ {MQTT_TOPIC_STATUS},\ {MQTT_TOPIC_CONFIG},\ {MQTT_TOPIC_CMD},\ {MQTT_TOPIC_VALVES}" ) client.subscribe(MQTT_TOPIC_STATUS) client.subscribe(MQTT_TOPIC_CONFIG) client.subscribe(MQTT_TOPIC_CMD) client.subscribe(MQTT_TOPIC_VALVES) if return_code == 0: logger.info("Connected successfully") Helpers().load_toggle_statuses_from_file() if Mqtt().get_periodic_updates_thread() is None: Mqtt().set_periodic_updates_thread( Thread(daemon=True, name="PeriodicUpdatesThread", target=Mqtt.send_periodic_updates, args=(client,)) ) Mqtt().get_periodic_updates_thread().start() else: logger.info(f"Connect returned result code: {return_code}") @staticmethod def handle_valves(client, data): """Handle valves.""" try: logger.info(f"valves data received={data}") Helpers().set_valves(data) except Exception as exception: logger.error(f"Error: {exception}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + str(exception)[0:128] + MQTT_END) # Program Configuration handler # 1. It should parse the configuration as a JSON string # 2. If it is correct it should store it as a local file # 3. A scheduler should launch to turn on the irrigator for every cycle @staticmethod def handle_config(client, data): """Handle cfg.""" try: json_data = json.loads(data) logger.info(f"prestored programs={json_data}") for program in json_data: logger.info(f"program={program}") if program == {}: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) return Services().store_program_cycles(program, True) Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) except Exception as exception: logger.error(f"Error: {exception}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + str(exception)[0:128] + MQTT_END) @staticmethod def handle_command(client, data): """Handle cmd.""" try: json_data = json.loads(data) logger.info(json_data) cmd = json_data["cmd"] command = Command(cmd) try: valve = json_data["out"] except Exception as exception: logger.warning( f"Could not find valve out parameter. \ Will use valve 1: {exception}" ) valve = 1 file_path = PROGRAM + str(valve) + PROGRAM_EXT if command in (Command.TURN_ON_VALVE, Command.TURN_OFF_VALVE): Helpers().toggle(cmd, "out" + str(valve)) statuses = Helpers().get_toggle_statuses() logger.info(f"Publishing right away Statuses to MQTT topic: {MQTT_TOPIC_STATUS}: {statuses}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, str(statuses)) elif command == Command.SEND_PROGRAM: logger.info(f"Looking for {file_path}") if os.path.exists(file_path): logger.info(f"{file_path} exists!") with open(file_path, encoding="utf-8") as json_file: json_data = json.load(json_file) Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, str(json_data)) else: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + file_path + " does not exist!" + MQTT_END) elif command == Command.DELETE_PROGRAM: if not Services().delete_program(valve): Mqtt.publish_to_topic( client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + file_path + " does not exist! Cannot be deleted." + MQTT_END ) elif command == Command.SEND_TIMEZONE: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + str(Helpers().get_timezone() + MQTT_END)) elif command == Command.REBOOT_RPI: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) Helpers().system_reboot() elif command == Command.UPDATE_RPI: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_OK + MQTT_OK + MQTT_END) Helpers().system_update() else: Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + "Wrong command used!" + MQTT_END) except Exception as exception: logger.error(f"Error: {exception}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, MQTT_STATUS_ERR + str(exception)[0:128] + MQTT_END) @staticmethod def publish_to_topic(client, topic, data, retained=True): """Publish to MQTT Topic.""" client.publish(topic, data, qos=2, retain=retained) # The callback for when a PUBLISH message is received from the server. @staticmethod def on_message(client, userdata, msg): """OnMessage handler.""" topic = msg.topic data = msg.payload.decode("utf-8") logger.info(f"Received message from topic:{topic}, userdata:{userdata}, data:{data}") if topic == MQTT_TOPIC_CONFIG: Mqtt.handle_config(client, data) elif msg.topic == MQTT_TOPIC_CMD: Mqtt.handle_command(client, data) elif msg.topic == MQTT_TOPIC_VALVES: Mqtt.handle_valves(client, data) @staticmethod def send_periodic_updates(client): """Send periodic updates.""" while True: try: logger.info("Sending Periodic Updates to status topic every 10s...") statuses = Helpers().get_toggle_statuses() logger.info(f"Publishing Statuses to MQTT topic: {MQTT_TOPIC_STATUS}: {statuses}") Mqtt.publish_to_topic(client, MQTT_TOPIC_STATUS, str(statuses)) metadata = {} metadata["ip_address"] = Helpers().extract_local_ip() metadata["uptime"] = Helpers().get_uptime() metadata["git_commit"] = Helpers().get_git_commit_id()
Mqtt.publish_to_topic(client, MQTT_TOPIC_METADATA, str(metadata))
3
2023-12-22 08:06:09+00:00
16k
shibing624/chatgpt-webui
src/models.py
[ { "identifier": "shared", "path": "src/shared.py", "snippet": "class State:\n def interrupt(self):\n def recover(self):\n def set_api_host(self, api_host: str):\n def reset_api_host(self):\n def reset_all(self):\n def set_api_key_queue(self, api_key_list):\n def switching_api_key(se...
import base64 import datetime import json import os import colorama import gradio as gr import requests import traceback import traceback from io import BytesIO from PIL import Image from loguru import logger from src import shared, config from src.base_model import BaseLLMModel, ModelType from src.chatglm import ChatGLMClient from src.llama import LLaMAClient from src.presets import ( INITIAL_SYSTEM_PROMPT, TIMEOUT_ALL, TIMEOUT_STREAMING, STANDARD_ERROR_MSG, CONNECTION_TIMEOUT_MSG, READ_TIMEOUT_MSG, ERROR_RETRIEVE_MSG, GENERAL_ERROR_MSG, CHAT_COMPLETION_URL, SUMMARY_CHAT_SYSTEM_PROMPT ) from src.utils import ( hide_middle_chars, count_token, construct_system, construct_user, get_last_day_of_month, i18n, replace_special_symbols, )
11,056
# -*- coding: utf-8 -*- """ Get model client from model name """ class OpenAIClient(BaseLLMModel): def __init__( self, model_name, api_key, system_prompt=INITIAL_SYSTEM_PROMPT, temperature=1.0, top_p=1.0, user_name="", ) -> None: super().__init__( model_name=model_name, temperature=temperature, top_p=top_p, system_prompt=system_prompt, user=user_name, ) self.api_key = api_key self.need_api_key = True self._refresh_header() def get_answer_stream_iter(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response(stream=True) if response is not None: iter = self._decode_chat_response(response) partial_text = "" for i in iter: partial_text += i yield partial_text else: yield STANDARD_ERROR_MSG + GENERAL_ERROR_MSG def get_answer_at_once(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response() response = json.loads(response.text) content = response["choices"][0]["message"]["content"] total_token_count = response["usage"]["total_tokens"] return content, total_token_count def count_token(self, user_input): input_token_count = count_token(construct_user(user_input)) if self.system_prompt is not None and len(self.all_token_counts) == 0: system_prompt_token_count = count_token( construct_system(self.system_prompt) ) return input_token_count + system_prompt_token_count return input_token_count def billing_info(self): try: curr_time = datetime.datetime.now() last_day_of_month = get_last_day_of_month( curr_time).strftime("%Y-%m-%d") first_day_of_month = curr_time.replace(day=1).strftime("%Y-%m-%d") usage_url = f"{shared.state.usage_api_url}?start_date={first_day_of_month}&end_date={last_day_of_month}" try: usage_data = self._get_billing_data(usage_url) except Exception as e: logger.warning(f"获取API使用情况失败:" + str(e))
# -*- coding: utf-8 -*- """ Get model client from model name """ class OpenAIClient(BaseLLMModel): def __init__( self, model_name, api_key, system_prompt=INITIAL_SYSTEM_PROMPT, temperature=1.0, top_p=1.0, user_name="", ) -> None: super().__init__( model_name=model_name, temperature=temperature, top_p=top_p, system_prompt=system_prompt, user=user_name, ) self.api_key = api_key self.need_api_key = True self._refresh_header() def get_answer_stream_iter(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response(stream=True) if response is not None: iter = self._decode_chat_response(response) partial_text = "" for i in iter: partial_text += i yield partial_text else: yield STANDARD_ERROR_MSG + GENERAL_ERROR_MSG def get_answer_at_once(self): if not self.api_key: raise ValueError("API key is not set") response = self._get_response() response = json.loads(response.text) content = response["choices"][0]["message"]["content"] total_token_count = response["usage"]["total_tokens"] return content, total_token_count def count_token(self, user_input): input_token_count = count_token(construct_user(user_input)) if self.system_prompt is not None and len(self.all_token_counts) == 0: system_prompt_token_count = count_token( construct_system(self.system_prompt) ) return input_token_count + system_prompt_token_count return input_token_count def billing_info(self): try: curr_time = datetime.datetime.now() last_day_of_month = get_last_day_of_month( curr_time).strftime("%Y-%m-%d") first_day_of_month = curr_time.replace(day=1).strftime("%Y-%m-%d") usage_url = f"{shared.state.usage_api_url}?start_date={first_day_of_month}&end_date={last_day_of_month}" try: usage_data = self._get_billing_data(usage_url) except Exception as e: logger.warning(f"获取API使用情况失败:" + str(e))
return i18n("**获取API使用情况失败**")
16
2023-12-27 12:14:26+00:00
16k
camenduru/AnyDoor-online-hf
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n ...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import itertools import torch.nn.functional as F from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from omegaconf import ListConfig from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler
12,325
if batch_size is not None: b = batch_size if batch_size is not None else shape[0] shape = [batch_size] + list(shape) else: b = batch_size = shape[0] if x_T is None: img = torch.randn(shape, device=self.device) else: img = x_T intermediates = [] if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation', total=timesteps) if verbose else reversed( range(0, timesteps)) if type(temperature) == float: temperature = [temperature] * timesteps for i in iterator: ts = torch.full((b,), i, device=self.device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img, x0_partial = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, return_x0=True, temperature=temperature[i], noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if mask is not None: assert x0 is not None img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(x0_partial) if callback: callback(i) if img_callback: img_callback(img, i) return img, intermediates @torch.no_grad() def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t device = self.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim:
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if reset_ema: assert exists(ckpt_path) if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) if reset_ema: assert self.use_ema print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) else: self.register_buffer('logvar', logvar) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) elif self.parameterization == "v": lvlb_weights = torch.ones_like(self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))) else: raise NotImplementedError("mu not supported") lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") @torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] if self.make_it_fit: n_params = len([name for name, _ in itertools.chain(self.named_parameters(), self.named_buffers())]) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys:\n {missing}") if len(unexpected) > 0: print(f"\nUnexpected Keys:\n {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def predict_start_from_z_and_v(self, x_t, t, v): # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def predict_eps_from_z_and_v(self, x_t, t, v): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_v(self, x, noise, t): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x ) def get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): for k in self.ucg_training: p = self.ucg_training[k]["p"] val = self.ucg_training[k]["val"] if val is None: val = "" for i in range(len(batch[k])): if self.ucg_prng.choice(2, p=[1 - p, p]): batch[k][i] = val loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, force_null_conditioning=False, *args, **kwargs): self.force_null_conditioning = force_null_conditioning self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning: conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) reset_ema = kwargs.pop("reset_ema", False) reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True if reset_ema: assert self.use_ema print( f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() def make_cond_schedule(self, ): self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx, dataloader_idx): # only for very first batch if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt: assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously' # set rescale weight to 1./std of encodings print("### USING STD-RESCALING ###") x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer('scale_factor', 1. / z.flatten().std()) print(f"setting self.scale_factor to {self.scale_factor}") print("### USING STD-RESCALING ###") def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append(self.decode_first_stage(zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented") return self.scale_factor * z def get_learned_conditioning(self, c): #c 1,3,224,224 if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): #1,1,1024 c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip(L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"]) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, return_x=False): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None and not self.force_null_conditioning: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox', "txt"]: xc = batch[cond_key] elif cond_key in ['class_label', 'cls']: xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_x: out.extend([x]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c) return loss def forward(self, x, c, *args, **kwargs): #t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() t = self.time_steps.reshape( (x.shape[0],) ).to(self.device).long() if self.model.conditioning_key is not None: assert c is not None if self.cond_stage_trainable: c = self.get_learned_conditioning(c) if self.shorten_cond_schedule: # TODO: drop this option tc = self.cond_ids[t].to(self.device) c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) return self.p_losses(x, c, t, *args, **kwargs) def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is expected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, t, **cond) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0) return mean_flat(kl_prior) / np.log(2.0) def p_losses(self, x_start, cond, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_output = self.apply_model(x_noisy, t, cond) loss_dict = {} prefix = 'train' if self.training else 'val' if self.parameterization == "x0": target = x_start elif self.parameterization == "eps": target = noise elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError() loss_simple = self.get_loss(model_output, target, mean=False) #boundary = self.boundary.to(loss_simple.device) #boundary = F.interpolate(boundary, size = (64,64)) * 5 + 1.0 #16,1,64,64 #print(loss_simple.shape) #16,4,64,64 loss_simple = loss_simple.mean([1, 2, 3]) #.mean([1, 2, 3]) loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()}) logvar_t = self.logvar[t].to(self.device) loss = loss_simple / torch.exp(logvar_t) + logvar_t # loss = loss_simple / torch.exp(self.logvar) + self.logvar if self.learn_logvar: loss_dict.update({f'{prefix}/loss_gamma': loss.mean()}) loss_dict.update({'logvar': self.logvar.data.mean()}) loss = self.l_simple_weight * loss.mean() loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3)) loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean() loss_dict.update({f'{prefix}/loss_vlb': loss_vlb}) loss += (self.original_elbo_weight * loss_vlb) loss_dict.update({f'{prefix}/loss': loss}) #print(self.parameterization, self.learn_logvar, self.original_elbo_weight, self.lvlb_weights[t]) return loss, loss_dict def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False, return_x0=False, score_corrector=None, corrector_kwargs=None): t_in = t model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) if score_corrector is not None: assert self.parameterization == "eps" model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs) if return_codebook_ids: model_out, logits = model_out if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out else: raise NotImplementedError() if clip_denoised: x_recon.clamp_(-1., 1.) if quantize_denoised: x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) if return_codebook_ids: return model_mean, posterior_variance, posterior_log_variance, logits elif return_x0: return model_mean, posterior_variance, posterior_log_variance, x_recon else: return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_codebook_ids=False, quantize_denoised=False, return_x0=False, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): b, *_, device = *x.shape, x.device outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_codebook_ids=return_codebook_ids, quantize_denoised=quantize_denoised, return_x0=return_x0, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if return_codebook_ids: raise DeprecationWarning("Support dropped.") model_mean, _, model_log_variance, logits = outputs elif return_x0: model_mean, _, model_log_variance, x0 = outputs else: model_mean, _, model_log_variance = outputs noise = noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) if return_codebook_ids: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1) if return_x0: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0 else: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False, img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t timesteps = self.num_timesteps if batch_size is not None: b = batch_size if batch_size is not None else shape[0] shape = [batch_size] + list(shape) else: b = batch_size = shape[0] if x_T is None: img = torch.randn(shape, device=self.device) else: img = x_T intermediates = [] if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation', total=timesteps) if verbose else reversed( range(0, timesteps)) if type(temperature) == float: temperature = [temperature] * timesteps for i in iterator: ts = torch.full((b,), i, device=self.device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img, x0_partial = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, return_x0=True, temperature=temperature[i], noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if mask is not None: assert x0 is not None img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(x0_partial) if callback: callback(i) if img_callback: img_callback(img, i) return img, intermediates @torch.no_grad() def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t device = self.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim:
ddim_sampler = DDIMSampler(self)
16
2023-12-25 04:48:34+00:00
16k
smonsays/modular-hyperteacher
metax/data/imitation.py
[ { "identifier": "Environment", "path": "metax/data/envs/base.py", "snippet": "class Environment(abc.ABC):\n @abc.abstractproperty\n def num_actions(self) -> int:\n \"\"\" Number of possible actions.\"\"\"\n\n @abc.abstractproperty\n def observation_shape(self):\n \"\"\"The shap...
from functools import partial from typing import Optional from chex import PRNGKey from metax.data.envs.base import Environment from metax.data.envs.grid import CompositionalGrid from metax.data.envs.preference import CompositionalPreference from .base import Dataloader, MetaDataset, MultitaskDataset import jax import jax.numpy as jnp import jax.tree_util as jtu
11,188
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class ImitationMetaDataloader(Dataloader): def __init__( self, env: Environment, num_tasks: int, shots_train: int, shots_test: int, meta_batch_size: int, mode: str, train_test_split: bool, rng: PRNGKey, ): super().__init__(input_shape=env.observation_shape, output_dim=env.num_actions) self.env = env self.num_tasks = num_tasks self.shots_train = shots_train self.shots_test = shots_test self.meta_batch_size = meta_batch_size self.mode = mode self.train_test_split = train_test_split self.fixed_rng = rng assert num_tasks % meta_batch_size == 0, "num_tasks must be divisible by meta_batch_size" self.num_steps = num_tasks // meta_batch_size @property def sample_input(self): return jnp.zeros((1,) + self.env.observation_shape) def __len__(self): return self.num_steps def __iter__(self): for rng in jax.random.split(self.fixed_rng, self.num_steps): # Sample batch and wrap as MetaDataset rngs_batch = jax.random.split(rng, self.meta_batch_size) yield self.sample_metatask(rngs_batch) @partial(jax.jit, static_argnames="self") @partial(jax.vmap, in_axes=(None, 0)) def sample_metatask(self, rng: PRNGKey) -> MetaDataset: rng_goal, rng_task = jax.random.split(rng, 2) goal, info = self.env.reset_goal(rng_goal, mode=self.mode) @jax.vmap def sample_task(rng): rng_reset, rng_demo = jax.random.split(rng, 2) env_state, _ = self.env.reset(rng_reset, goal=goal) trajectory, actions = self.env.demonstrate(rng_demo, env_state) return MultitaskDataset( x=trajectory.observation, y=actions, task_id=jnp.full(actions.shape[:1], info["task_id"]), info={ "mask": ~trajectory.done, "embeddings": jnp.repeat(info["embedding"][None, :], actions.shape[0], axis=0), }, ) rngs_task = jax.random.split(rng_task, self.shots_train + self.shots_test) train_and_test_task = sample_task(rngs_task) if self.train_test_split: # Split into train and test set return MetaDataset( train=jtu.tree_map( lambda x: x[:self.shots_train].reshape(-1, *x.shape[2:]), train_and_test_task ), test=jtu.tree_map( lambda x: x[self.shots_train:].reshape(-1, *x.shape[2:]), train_and_test_task ), ) else: # No train_test split means, meta.train == meta.test set return MetaDataset( train=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), test=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), ) def create_imitation_metaloader( name, meta_batch_size, shots_train, shots_test, train_test_split, num_tasks_train, num_tasks_test, num_tasks_valid, num_tasks_ood: Optional[int] = None, seed=None, **kwargs, ): ood_sets_hot = None if name == "compositional_grid": env = CompositionalGrid( grid_size=kwargs["grid_size"], num_interactions=kwargs["num_interactions"], num_mazes=kwargs["num_mazes"], num_objects=kwargs["num_objects"], num_distractors=kwargs["num_distractors"], frac_ood=kwargs["frac_ood"], task_support=kwargs["task_support"], seed=seed, ) elif name == "compositional_preference": # Return the various OOD tasks for the compositional preference env. ood_sets_hot = jnp.arange(kwargs["num_hot"] + 1, kwargs["num_preferences"] + 1)
""" Copyright (c) Simon Schug All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class ImitationMetaDataloader(Dataloader): def __init__( self, env: Environment, num_tasks: int, shots_train: int, shots_test: int, meta_batch_size: int, mode: str, train_test_split: bool, rng: PRNGKey, ): super().__init__(input_shape=env.observation_shape, output_dim=env.num_actions) self.env = env self.num_tasks = num_tasks self.shots_train = shots_train self.shots_test = shots_test self.meta_batch_size = meta_batch_size self.mode = mode self.train_test_split = train_test_split self.fixed_rng = rng assert num_tasks % meta_batch_size == 0, "num_tasks must be divisible by meta_batch_size" self.num_steps = num_tasks // meta_batch_size @property def sample_input(self): return jnp.zeros((1,) + self.env.observation_shape) def __len__(self): return self.num_steps def __iter__(self): for rng in jax.random.split(self.fixed_rng, self.num_steps): # Sample batch and wrap as MetaDataset rngs_batch = jax.random.split(rng, self.meta_batch_size) yield self.sample_metatask(rngs_batch) @partial(jax.jit, static_argnames="self") @partial(jax.vmap, in_axes=(None, 0)) def sample_metatask(self, rng: PRNGKey) -> MetaDataset: rng_goal, rng_task = jax.random.split(rng, 2) goal, info = self.env.reset_goal(rng_goal, mode=self.mode) @jax.vmap def sample_task(rng): rng_reset, rng_demo = jax.random.split(rng, 2) env_state, _ = self.env.reset(rng_reset, goal=goal) trajectory, actions = self.env.demonstrate(rng_demo, env_state) return MultitaskDataset( x=trajectory.observation, y=actions, task_id=jnp.full(actions.shape[:1], info["task_id"]), info={ "mask": ~trajectory.done, "embeddings": jnp.repeat(info["embedding"][None, :], actions.shape[0], axis=0), }, ) rngs_task = jax.random.split(rng_task, self.shots_train + self.shots_test) train_and_test_task = sample_task(rngs_task) if self.train_test_split: # Split into train and test set return MetaDataset( train=jtu.tree_map( lambda x: x[:self.shots_train].reshape(-1, *x.shape[2:]), train_and_test_task ), test=jtu.tree_map( lambda x: x[self.shots_train:].reshape(-1, *x.shape[2:]), train_and_test_task ), ) else: # No train_test split means, meta.train == meta.test set return MetaDataset( train=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), test=jtu.tree_map(lambda x: x.reshape(-1, *x.shape[2:]), train_and_test_task), ) def create_imitation_metaloader( name, meta_batch_size, shots_train, shots_test, train_test_split, num_tasks_train, num_tasks_test, num_tasks_valid, num_tasks_ood: Optional[int] = None, seed=None, **kwargs, ): ood_sets_hot = None if name == "compositional_grid": env = CompositionalGrid( grid_size=kwargs["grid_size"], num_interactions=kwargs["num_interactions"], num_mazes=kwargs["num_mazes"], num_objects=kwargs["num_objects"], num_distractors=kwargs["num_distractors"], frac_ood=kwargs["frac_ood"], task_support=kwargs["task_support"], seed=seed, ) elif name == "compositional_preference": # Return the various OOD tasks for the compositional preference env. ood_sets_hot = jnp.arange(kwargs["num_hot"] + 1, kwargs["num_preferences"] + 1)
env = CompositionalPreference(
2
2023-12-22 16:35:49+00:00
16k
AContesini/Convert_PDF_to_DOCX_or_vice-versa
venv/Lib/site-packages/tqdm/cli.py
[ { "identifier": "TqdmKeyError", "path": "venv/Lib/site-packages/tqdm/std.py", "snippet": "class TqdmKeyError(KeyError):\n pass" }, { "identifier": "TqdmTypeError", "path": "venv/Lib/site-packages/tqdm/std.py", "snippet": "class TqdmTypeError(TypeError):\n pass" }, { "identi...
import logging import re import sys from ast import literal_eval as numeric from .std import TqdmKeyError, TqdmTypeError, tqdm from .version import __version__ from importlib import resources from os import path from shutil import copyfile
14,060
if not tmp: if buf: fp_write(buf) if callback_len: # n += 1 + buf.count(delim) callback(1 + buf.count(delim)) else: for i in buf.split(delim): callback(i) getattr(fout, 'flush', lambda: None)() return # n while True: i = tmp.find(delim) if i < 0: buf += tmp break fp_write(buf + tmp[:i + len(delim)]) # n += 1 callback(1 if callback_len else (buf + tmp[:i])) buf = b'' tmp = tmp[i + len_delim:] # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file') # The 8 leading spaces are required for consistency CLI_EXTRA_DOC = r""" Extra CLI Options ----------------- name : type, optional TODO: find out why this is needed. delim : chr, optional Delimiting character [default: '\n']. Use '\0' for null. N.B.: on Windows systems, Python converts '\n' to '\r\n'. buf_size : int, optional String buffer size in bytes [default: 256] used when `delim` is specified. bytes : bool, optional If true, will count bytes, ignore `delim`, and default `unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'. tee : bool, optional If true, passes `stdin` to both `stderr` and `stdout`. update : bool, optional If true, will treat input as newly elapsed iterations, i.e. numbers to pass to `update()`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. update_to : bool, optional If true, will treat input as total elapsed iterations, i.e. numbers to assign to `self.n`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. null : bool, optional If true, will discard input (no stdout). manpath : str, optional Directory in which to install tqdm man pages. comppath : str, optional Directory in which to place tqdm completion. log : str, optional CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET. """ def main(fp=sys.stderr, argv=None): """ Parameters (internal use only) --------- fp : file-like object for tqdm argv : list (default: sys.argv[1:]) """ if argv is None: argv = sys.argv[1:] try: log_idx = argv.index('--log') except ValueError: for i in argv: if i.startswith('--log='): logLevel = i[len('--log='):] break else: logLevel = 'INFO' else: # argv.pop(log_idx) # logLevel = argv.pop(log_idx) logLevel = argv[log_idx + 1] logging.basicConfig(level=getattr(logging, logLevel), format="%(levelname)s:%(module)s:%(lineno)d:%(message)s") d = tqdm.__doc__ + CLI_EXTRA_DOC opt_types = dict(RE_OPTS.findall(d)) # opt_types['delim'] = 'chr' for o in UNSUPPORTED_OPTS: opt_types.pop(o) log.debug(sorted(opt_types.items())) # d = RE_OPTS.sub(r' --\1=<\1> : \2', d) split = RE_OPTS.split(d) opt_types_desc = zip(split[1::3], split[2::3], split[3::3]) d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else '\n --{0}=<{1}> : {2}{3}').format( otd[0].replace('_', '-'), otd[0], *otd[1:]) for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS) help_short = "Usage:\n tqdm [--help | options]\n" d = help_short + """ Options: -h, --help Print this help and exit. -v, --version Print version and exit. """ + d.strip('\n') + '\n' # opts = docopt(d, version=__version__) if any(v in argv for v in ('-v', '--version')):
""" Module version for monitoring CLI pipes (`... | python -m tqdm | ...`). """ __all__ = ["main"] log = logging.getLogger(__name__) def cast(val, typ): log.debug((val, typ)) if " or " in typ: for t in typ.split(" or "): try: return cast(val, t) except TqdmTypeError: pass raise TqdmTypeError(val + ' : ' + typ) # sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n') if typ == 'bool': if (val == 'True') or (val == ''): return True elif val == 'False': return False else: raise TqdmTypeError(val + ' : ' + typ) try: return eval(typ + '("' + val + '")') except Exception: if typ == 'chr': return chr(ord(eval('"' + val + '"'))).encode() else: raise TqdmTypeError(val + ' : ' + typ) def posix_pipe(fin, fout, delim=b'\\n', buf_size=256, callback=lambda float: None, callback_len=True): """ Params ------ fin : binary file with `read(buf_size : int)` method fout : binary file with `write` (and optionally `flush`) methods. callback : function(float), e.g.: `tqdm.update` callback_len : If (default: True) do `callback(len(buffer))`. Otherwise, do `callback(data) for data in buffer.split(delim)`. """ fp_write = fout.write if not delim: while True: tmp = fin.read(buf_size) # flush at EOF if not tmp: getattr(fout, 'flush', lambda: None)() return fp_write(tmp) callback(len(tmp)) # return buf = b'' len_delim = len(delim) # n = 0 while True: tmp = fin.read(buf_size) # flush at EOF if not tmp: if buf: fp_write(buf) if callback_len: # n += 1 + buf.count(delim) callback(1 + buf.count(delim)) else: for i in buf.split(delim): callback(i) getattr(fout, 'flush', lambda: None)() return # n while True: i = tmp.find(delim) if i < 0: buf += tmp break fp_write(buf + tmp[:i + len(delim)]) # n += 1 callback(1 if callback_len else (buf + tmp[:i])) buf = b'' tmp = tmp[i + len_delim:] # ((opt, type), ... ) RE_OPTS = re.compile(r'\n {4}(\S+)\s{2,}:\s*([^,]+)') # better split method assuming no positional args RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)') # TODO: add custom support for some of the following? UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file') # The 8 leading spaces are required for consistency CLI_EXTRA_DOC = r""" Extra CLI Options ----------------- name : type, optional TODO: find out why this is needed. delim : chr, optional Delimiting character [default: '\n']. Use '\0' for null. N.B.: on Windows systems, Python converts '\n' to '\r\n'. buf_size : int, optional String buffer size in bytes [default: 256] used when `delim` is specified. bytes : bool, optional If true, will count bytes, ignore `delim`, and default `unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'. tee : bool, optional If true, passes `stdin` to both `stderr` and `stdout`. update : bool, optional If true, will treat input as newly elapsed iterations, i.e. numbers to pass to `update()`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. update_to : bool, optional If true, will treat input as total elapsed iterations, i.e. numbers to assign to `self.n`. Note that this is slow (~2e5 it/s) since every input must be decoded as a number. null : bool, optional If true, will discard input (no stdout). manpath : str, optional Directory in which to install tqdm man pages. comppath : str, optional Directory in which to place tqdm completion. log : str, optional CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET. """ def main(fp=sys.stderr, argv=None): """ Parameters (internal use only) --------- fp : file-like object for tqdm argv : list (default: sys.argv[1:]) """ if argv is None: argv = sys.argv[1:] try: log_idx = argv.index('--log') except ValueError: for i in argv: if i.startswith('--log='): logLevel = i[len('--log='):] break else: logLevel = 'INFO' else: # argv.pop(log_idx) # logLevel = argv.pop(log_idx) logLevel = argv[log_idx + 1] logging.basicConfig(level=getattr(logging, logLevel), format="%(levelname)s:%(module)s:%(lineno)d:%(message)s") d = tqdm.__doc__ + CLI_EXTRA_DOC opt_types = dict(RE_OPTS.findall(d)) # opt_types['delim'] = 'chr' for o in UNSUPPORTED_OPTS: opt_types.pop(o) log.debug(sorted(opt_types.items())) # d = RE_OPTS.sub(r' --\1=<\1> : \2', d) split = RE_OPTS.split(d) opt_types_desc = zip(split[1::3], split[2::3], split[3::3]) d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else '\n --{0}=<{1}> : {2}{3}').format( otd[0].replace('_', '-'), otd[0], *otd[1:]) for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS) help_short = "Usage:\n tqdm [--help | options]\n" d = help_short + """ Options: -h, --help Print this help and exit. -v, --version Print version and exit. """ + d.strip('\n') + '\n' # opts = docopt(d, version=__version__) if any(v in argv for v in ('-v', '--version')):
sys.stdout.write(__version__ + '\n')
3
2023-12-24 15:46:18+00:00
16k
pkariz/grin-explorer
backend/api/views.py
[ { "identifier": "fetch_and_store_block", "path": "backend/api/bootstrap.py", "snippet": "def fetch_and_store_block(blockchain, block_height, prefetch=True):\n # initialize node api\n node_api = NodeV2API(blockchain.node)\n if block_height < 0:\n # no such block height\n raise Node...
from asgiref.sync import async_to_sync from django.contrib.contenttypes.models import ContentType from django.db.models.deletion import ProtectedError from django.views.generic import TemplateView from django.views.decorators.cache import never_cache from dramatiq_abort import abort from rest_framework import status from rest_framework.exceptions import APIException from rest_framework.exceptions import NotFound from rest_framework.exceptions import ValidationError as DRFValidationError from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from slugify import slugify from .bootstrap import fetch_and_store_block, update_blockchain_progress from .exceptions import UpdateBlockchainProgressError from .helpers import get_filter_backends, load_data_from_redis from .filters import ( BlockFilter, CustomBlockSearchFilter, NodeFilter, NodeGroupFilter, ) from .mixins import CustomModelViewSet from .models import Blockchain, Block, Reorg, Node, NodeGroup, DramatiqTask from .serializers import ( BlockchainSerializer, BlockchainExtendedSerializer, BlockSerializer, BlockDetailSerializer, NodeSerializer, NodeGroupSerializer, DramatiqTaskSerializer, ) from .tasks import bootstrap_blockchain, delete_blockchain import channels import logging import pytz
10,860
# call this view for each block it will get. In this case there will be # many fast sequential calls to this view, there might be too many # postgres connections opened so view executions might actually fail. # The suggested solution is to comment out 'block_accepted_url' in # node's config file, run the node, wait for it to sync, uncomment # 'block_accepted_url' and then manually bootstrap it. blockchain = self.get_object() # check if new block has been receiver when this blockchain is in the # process of being deleted. deleting = DramatiqTask.objects.filter( type=DramatiqTask.Type.BLOCKCHAIN_DELETE, object_id=blockchain.id, content_type=ContentType.objects.get_for_model(blockchain) ).exists() if deleting: # nothing to do, ignore the new block return Response(status=status.HTTP_404_NOT_FOUND) # get request data height = request.data['data']['header']['height'] hash = request.data['hash'] # prev_hash comes as list of int bytes, so we convert it to hex # NOTE: the same is true for some other data which we currently don't # need so we don't transform it, eg. data.header.kernel_root prev_hash = None if request.data['data']['header']['prev_hash']: prev_hash = bytes(request.data['data']['header']['prev_hash']).hex() logger.info( 'Block accepted', extra={ 'height': height, 'hash': hash, 'prev_hash': prev_hash, 'blockchain': blockchain.slug, }, ) web_socket_msg_type = 'send_block' # handle reorg case # we expect blocks to come ordered by height, there are some edge cases # here which are not handled, but they're unlikely to happen (eg. reorg # happens but websocket calls for first blocks fails while for later it # doesn't and then the code bellow wouldn't spot a reorg) block_at_this_height = blockchain.blocks\ .filter(height=height, reorg__isnull=True)\ .first() # we fetch here because anyone can call this view - we don't want to # work with fake data new_block = fetch_and_store_block(blockchain, height, prefetch=False) if block_at_this_height: if block_at_this_height.hash == new_block.hash: # probably have fetched this block while bootstraping, accepted # view got called a bit later so we already have it, noop return Response(status=status.HTTP_200_OK) logger.info( 'Block accepted - reorg spotted', extra={ 'block_at_this_height': block_at_this_height, 'block_at_this_height.hash': block_at_this_height.hash, 'block_at_this_height.reorg': block_at_this_height.reorg, 'hash': new_block.hash }, ) # reorg spotted reorged_blocks = list(blockchain.blocks\ .filter(height__gte=height, reorg__isnull=True) .exclude(pk=new_block.pk) .order_by('height')) logger.info('reorged_blocks at start: {}'.format(reorged_blocks)) # these reorged blocks are guaranteed to be reorged, now find any # previous blocks which were also reorged - aka get common # ancestor of the reorged block at 'height' and the new (main) block # find the common ancestor of this block and the reorged block at # the same height. We start with the current height to avoid more # logic for Reorg instance params if new_block.hash == block_at_this_height.hash: # at height X we got H1, then we got H2 (this call), but now it # reorged back to H1, so we don't do anything, no reorg is # stored since we didn't fetch the block in time from the node logger.info('Reorg cancelled out, noop') return Response(status=status.HTTP_200_OK) logger.info('new_block', extra={'hash': new_block.hash, 'prev_hash': new_block.prev_hash}) prev_block_new_chain = new_block prev_block_old_chain = reorged_blocks[0] logger.info('prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) # remove the first one since it will get added again reorged_blocks = reorged_blocks[1:] logger.info('reorged_blocks after [1:]: {}'.format(reorged_blocks)) main_blocks = [] while True: # theoretically we might be missing the block in db but we don't # cover such cases currently if not prev_block_new_chain: logger.info('reached break in IF NOT prev_block_new_chain') # this means that prev_block_old_chain is also None, since # they're both "previous" of their genesis block break if prev_block_new_chain == prev_block_old_chain: logger.info('reached break in IF NOT prev_block_new_chain == prev_block_old_chain') # found the common ancestor break # add to the left because we want to keep it sorted by height reorged_blocks.insert(0, prev_block_old_chain) main_blocks.insert(0, prev_block_new_chain) logger.info('new reorged_blocks: {}'.format(reorged_blocks)) logger.info('new main_blocks: {}'.format(main_blocks)) prev_block_new_chain = prev_block_new_chain.get_previous_block() prev_block_old_chain = prev_block_old_chain.get_previous_block() logger.info('new prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) logger.info('before reorg create: reorged_blocks: {}, main_blocks: {}'.format(reorged_blocks, main_blocks)) reorg = Reorg.objects.create( blockchain=blockchain, start_reorg_block=reorged_blocks[0], end_reorg_block=reorged_blocks[-1], start_main_block=main_blocks[0], ) # Reorg post_save signal fixes .reorg on new/old blocks and fixes # inputs/outputs web_socket_msg_type = 'reorged'
logger = logging.getLogger(__name__) # Serve Vue Application index_view = never_cache(TemplateView.as_view(template_name='index.html')) class NodeGroupViewSet(CustomModelViewSet): """API endpoint for NodeGroup.""" queryset = NodeGroup.objects.all() filterset_class = NodeGroupFilter serializer_class = NodeGroupSerializer lookup_field = 'slug' permission_classes = [IsAuthenticated] def create(self, request, *args, **kwargs): slug = request.data.get('slug') if not slug: request.data['slug'] = slugify(request.data['name'], to_lower=True) return super().create(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): try: return super().destroy(request, *args, **kwargs) except ProtectedError as e: raise DRFValidationError( detail='Node group is related to nodes, delete them first') class NodeViewSet(CustomModelViewSet): """API endpoint for Node.""" queryset = Node.objects.all() filterset_class = NodeFilter serializer_class = NodeSerializer # currently all node views require authentication permission_classes = [IsAuthenticated] lookup_field = 'slug' def create(self, request, *args, **kwargs): slug = request.data.get('slug') if not slug: request.data['slug'] = slugify(request.data['name'], to_lower=True) request.data['group'] = NodeGroup.objects.get(slug=request.data['group']).pk return super().create(request, *args, **kwargs) def update(self, request, *args, **kwargs): # NOTE: super().partial_update calls update(..., partial=True) if not kwargs.get('partial'): # we don't allow full updates - aka PUT raise DRFPermissionDenied() return super().update(request, *args, **kwargs) def partial_update(self, request, slug=None): request.data['group'] = NodeGroup.objects.get(slug=request.data['group']).pk return super().partial_update(request, slug=slug) @action(detail=True, methods=['get']) def reachable(self, request, slug=None): node = self.get_object() try: res = node.is_reachable() except Exception as e: logger.exception('Unreachable node') res = False return Response(res, status=status.HTTP_200_OK) def destroy(self, request, *args, **kwargs): try: return super().destroy(request, *args, **kwargs) except ProtectedError as e: raise DRFValidationError( detail='Node is related to blockchains, delete them first') class BlockchainViewSet(CustomModelViewSet): """API endpoint for Blockchain.""" queryset = Blockchain.objects.all() serializer_class = BlockchainSerializer lookup_field = 'slug' def get_serializer_class(self): # when authenticated we return also NodeSerializer data if self.request.user.is_authenticated: return BlockchainExtendedSerializer return BlockchainSerializer def create(self, request, *args, **kwargs): slug = request.data.get('slug') if not slug: request.data['slug'] = slugify(request.data['name'], to_lower=True) request.data['node'] = request.data['node'] return super().create(request, *args, **kwargs) def destroy(self, request, slug=None): instance = self.get_object() message = delete_blockchain.send(instance.slug) task = DramatiqTask.objects.create( type=DramatiqTask.Type.BLOCKCHAIN_DELETE, status=DramatiqTask.Status.IN_PROGRESS, message_id=message.message_id, content_object=instance, ) return Response( DramatiqTaskSerializer(task).data, status=status.HTTP_200_OK) def _abort_previous_tasks(self, blockchain): conflicting_message_ids = DramatiqTask.objects.filter( status=DramatiqTask.Status.IN_PROGRESS, object_id=blockchain.id, content_type=ContentType.objects.get_for_model(blockchain) ).values_list('message_id', flat=True) # abort previous conflicting tasks if they exist for conflicting_message_id in conflicting_message_ids: abort(conflicting_message_id) @action(detail=True, methods=['post']) def bootstrap(self, request, slug=None): blockchain = self.get_object() if not blockchain.node.is_reachable: raise APIException(detail='Node is unreachable') self._abort_previous_tasks(blockchain) # create a new task message = bootstrap_blockchain.send(blockchain.slug) task = DramatiqTask.objects.create( type=DramatiqTask.Type.BOOTSTRAP, status=DramatiqTask.Status.IN_PROGRESS, message_id=message.message_id, content_object=blockchain, ) return Response( DramatiqTaskSerializer(task).data, status=status.HTTP_200_OK) @action( detail=True, methods=['post'], url_path='bootstrap/abort', url_name='bootstrap-abort', ) def abort_bootstrap(self, request, slug=None): blockchain = self.get_object() self._abort_previous_tasks(blockchain) return Response(status=status.HTTP_200_OK) @action(detail=True, methods=['get']) def graphs(self, request, slug=None): """Returns data for all graphs.""" data = { 'transaction_graph': load_data_from_redis(f'tx_graph__{slug}'), } return Response(data=data, status=status.HTTP_200_OK) @action(detail=True, methods=['post']) def accepted(self, request, slug=None): # NOTE: if node is offline and then you start it again then it will # call this view for each block it will get. In this case there will be # many fast sequential calls to this view, there might be too many # postgres connections opened so view executions might actually fail. # The suggested solution is to comment out 'block_accepted_url' in # node's config file, run the node, wait for it to sync, uncomment # 'block_accepted_url' and then manually bootstrap it. blockchain = self.get_object() # check if new block has been receiver when this blockchain is in the # process of being deleted. deleting = DramatiqTask.objects.filter( type=DramatiqTask.Type.BLOCKCHAIN_DELETE, object_id=blockchain.id, content_type=ContentType.objects.get_for_model(blockchain) ).exists() if deleting: # nothing to do, ignore the new block return Response(status=status.HTTP_404_NOT_FOUND) # get request data height = request.data['data']['header']['height'] hash = request.data['hash'] # prev_hash comes as list of int bytes, so we convert it to hex # NOTE: the same is true for some other data which we currently don't # need so we don't transform it, eg. data.header.kernel_root prev_hash = None if request.data['data']['header']['prev_hash']: prev_hash = bytes(request.data['data']['header']['prev_hash']).hex() logger.info( 'Block accepted', extra={ 'height': height, 'hash': hash, 'prev_hash': prev_hash, 'blockchain': blockchain.slug, }, ) web_socket_msg_type = 'send_block' # handle reorg case # we expect blocks to come ordered by height, there are some edge cases # here which are not handled, but they're unlikely to happen (eg. reorg # happens but websocket calls for first blocks fails while for later it # doesn't and then the code bellow wouldn't spot a reorg) block_at_this_height = blockchain.blocks\ .filter(height=height, reorg__isnull=True)\ .first() # we fetch here because anyone can call this view - we don't want to # work with fake data new_block = fetch_and_store_block(blockchain, height, prefetch=False) if block_at_this_height: if block_at_this_height.hash == new_block.hash: # probably have fetched this block while bootstraping, accepted # view got called a bit later so we already have it, noop return Response(status=status.HTTP_200_OK) logger.info( 'Block accepted - reorg spotted', extra={ 'block_at_this_height': block_at_this_height, 'block_at_this_height.hash': block_at_this_height.hash, 'block_at_this_height.reorg': block_at_this_height.reorg, 'hash': new_block.hash }, ) # reorg spotted reorged_blocks = list(blockchain.blocks\ .filter(height__gte=height, reorg__isnull=True) .exclude(pk=new_block.pk) .order_by('height')) logger.info('reorged_blocks at start: {}'.format(reorged_blocks)) # these reorged blocks are guaranteed to be reorged, now find any # previous blocks which were also reorged - aka get common # ancestor of the reorged block at 'height' and the new (main) block # find the common ancestor of this block and the reorged block at # the same height. We start with the current height to avoid more # logic for Reorg instance params if new_block.hash == block_at_this_height.hash: # at height X we got H1, then we got H2 (this call), but now it # reorged back to H1, so we don't do anything, no reorg is # stored since we didn't fetch the block in time from the node logger.info('Reorg cancelled out, noop') return Response(status=status.HTTP_200_OK) logger.info('new_block', extra={'hash': new_block.hash, 'prev_hash': new_block.prev_hash}) prev_block_new_chain = new_block prev_block_old_chain = reorged_blocks[0] logger.info('prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) # remove the first one since it will get added again reorged_blocks = reorged_blocks[1:] logger.info('reorged_blocks after [1:]: {}'.format(reorged_blocks)) main_blocks = [] while True: # theoretically we might be missing the block in db but we don't # cover such cases currently if not prev_block_new_chain: logger.info('reached break in IF NOT prev_block_new_chain') # this means that prev_block_old_chain is also None, since # they're both "previous" of their genesis block break if prev_block_new_chain == prev_block_old_chain: logger.info('reached break in IF NOT prev_block_new_chain == prev_block_old_chain') # found the common ancestor break # add to the left because we want to keep it sorted by height reorged_blocks.insert(0, prev_block_old_chain) main_blocks.insert(0, prev_block_new_chain) logger.info('new reorged_blocks: {}'.format(reorged_blocks)) logger.info('new main_blocks: {}'.format(main_blocks)) prev_block_new_chain = prev_block_new_chain.get_previous_block() prev_block_old_chain = prev_block_old_chain.get_previous_block() logger.info('new prev_block_new_chain: {}, prev_block_old_chain: {}'.format(prev_block_new_chain, prev_block_old_chain)) logger.info('before reorg create: reorged_blocks: {}, main_blocks: {}'.format(reorged_blocks, main_blocks)) reorg = Reorg.objects.create( blockchain=blockchain, start_reorg_block=reorged_blocks[0], end_reorg_block=reorged_blocks[-1], start_main_block=main_blocks[0], ) # Reorg post_save signal fixes .reorg on new/old blocks and fixes # inputs/outputs web_socket_msg_type = 'reorged'
web_socket_msg = BlockSerializer(new_block).data
18
2023-12-24 22:15:11+00:00
16k
wuhy68/Parameter-Efficient-MoE
train_moe.py
[ { "identifier": "CamelidaeConfig", "path": "camelidae/configuration_camelidae.py", "snippet": "class CamelidaeConfig(PretrainedConfig):\n r\"\"\"\n This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA\n model according to the specifi...
import os import gc import json import math import random import copy import logging import torch import utils import bitsandbytes as bnb import transformers import warnings import transformers.integrations import transformers.modeling_utils from os.path import exists, join, isdir from copy import deepcopy from dataclasses import dataclass, field from typing import Dict, Optional, Sequence, Callable, List, Tuple, Union, Any from torch import nn from torch.utils.data import Dataset from transformers import Trainer, BitsAndBytesConfig, set_seed from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training from peft.tuners.lora import LoraLayer from camelidae.configuration_camelidae import CamelidaeConfig from camelidae.modeling_camelidae import LlamaForCausalLM from transformers_utils import ( get_keys_to_not_convert, _load_pretrained_model, )
11,041
@dataclass class DataCollatorForSupervisedDataset(object): """Collate examples for supervised fine-tuning.""" tokenizer: transformers.PreTrainedTokenizer def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: input_ids, labels = tuple( [instance[key] for instance in instances] for key in ("input_ids", "labels") ) input_ids = torch.nn.utils.rnn.pad_sequence( input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id ) labels = torch.nn.utils.rnn.pad_sequence( labels, batch_first=True, padding_value=IGNORE_INDEX ) return dict( input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ) class SavePeftModelCallback(transformers.TrainerCallback): def save_model(self, args, state, kwargs): # print('Saving PEFT checkpoint...') if state.best_model_checkpoint is not None: checkpoint_folder = os.path.join( state.best_model_checkpoint, "adapter_model" ) else: checkpoint_folder = os.path.join( args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}" ) peft_model_path = os.path.join(checkpoint_folder, "adapter_model") model = kwargs["model"] model.save_pretrained(peft_model_path) moe_state = {} for param_tensor in model.state_dict(): if "adapter" in param_tensor: moe_state.update({param_tensor: model.state_dict()[param_tensor]}) # if "adapter" in param_tensor or "norm" in param_tensor: # moe_state.update({param_tensor: model.state_dict()[param_tensor]}) moe_model_path = os.path.join(checkpoint_folder, "moe_model.bin") # print(moe_state.keys()) torch.save(moe_state, moe_model_path) pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin") if os.path.exists(pytorch_model_path): os.remove(pytorch_model_path) def on_save(self, args, state, control, **kwargs): self.save_model(args, state, kwargs) return control def on_train_end(self, args, state, control, **kwargs): def touch(fname, times=None): with open(fname, "a"): os.utime(fname, times) touch(join(args.output_dir, "completed")) self.save_model(args, state, kwargs) def make_supervised_data_module( tokenizer: transformers.PreTrainedTokenizer, data_args ) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = SupervisedDataset( tokenizer=tokenizer, data_path=data_args.data_path ) data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) return dict( train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator ) def find_all_linear_names(model, bits=4): cls = ( bnb.nn.Linear4bit if bits == 4 else (bnb.nn.Linear8bitLt if bits == 8 else torch.nn.Linear) ) lora_module_names = set() for name, module in model.named_modules(): if isinstance(module, cls): names = name.split(".") lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if "lm_head" in lora_module_names: # needed for 16-bit lora_module_names.remove("lm_head") return list(lora_module_names) def print_trainable_parameters(model): """ Prints the number of trainable parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): all_param += param.numel() if param.requires_grad: trainable_params += param.numel() print( f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}" ) def train(): parser = transformers.HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments) ) model_args, data_args, training_args = parser.parse_args_into_dataclasses() training_args.ddp_find_unused_parameters = False set_seed(42)
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # 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. warnings.filterwarnings("ignore") transformers.integrations.get_keys_to_not_convert = get_keys_to_not_convert transformers.modeling_utils.PreTrainedModel._load_pretrained_model = ( _load_pretrained_model ) IGNORE_INDEX = -100 DEFAULT_PAD_TOKEN = "[PAD]" @dataclass class ModelArguments: model_name_or_path: Optional[str] = field(default="facebook/opt-125m") @dataclass class DataArguments: data_path: str = field( default=None, metadata={"help": "Path to the training data."} ) @dataclass class TrainingArguments(transformers.TrainingArguments): report_to: str = field(default="none") cache_dir: Optional[str] = field(default=None) optim: str = field( default="paged_adamw_32bit" ) # "paged_lion_8bit", "paged_adamw_8bit", "paged_lion_32bit", "paged_adamw_32bit" lr_scheduler_type: str = field( default="constant_with_warmup" ) # "constant", "constant_with_warmup", "cosine", "cosine_with_restarts", "linear" model_max_length: int = field( default=2048, metadata={ "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)." }, ) def _tokenize_fn( strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer ) -> Dict: """Tokenize a list of strings.""" tokenized_list = [ tokenizer( text, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ) for text in strings ] input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list] input_ids_lens = labels_lens = [ tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list ] return dict( input_ids=input_ids, labels=labels, input_ids_lens=input_ids_lens, labels_lens=labels_lens, ) def preprocess( sources: Sequence[str], targets: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, ) -> Dict: """Preprocess the data by tokenizing.""" examples = [s + t for s, t in zip(sources, targets)] examples_tokenized, sources_tokenized = [ _tokenize_fn(strings, tokenizer) for strings in (examples, sources) ] input_ids = examples_tokenized["input_ids"] labels = copy.deepcopy(input_ids) for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]): label[:source_len] = IGNORE_INDEX return dict(input_ids=input_ids, labels=labels) class SupervisedDataset(Dataset): """Dataset for supervised fine-tuning.""" def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer): super(SupervisedDataset, self).__init__() logging.warning("Loading data: {}".format(data_path)) data_list = utils.jload(data_path) # Preprocess Data logging.warning("Processing data") self.tokenizer = tokenizer self.sources = [] self.targets = [] for idx in range(len(data_list)): data = data_list[idx] corpus = data["corpus"] if corpus != "": # pretrain mode source = f"{tokenizer.bos_token}" self.sources.append(source) target = f"{corpus}{tokenizer.eos_token}" self.targets.append(target) else: # instruction mode instruction = data["instruction"] conversation = data["conversation"] if len(conversation) == 1: if instruction == "": source = f"{tokenizer.bos_token}" else: source = f"{tokenizer.bos_token}### System:\n{instruction}\n" source += ( f"### Human:\n{conversation[0]['input']}\n### Assistant:\n" ) self.sources.append(source) target = f"{conversation[0]['output']}{tokenizer.eos_token}" self.targets.append(target) # else: # dialog mode del data_list gc.collect() # ## Debug Mode # self.sources = self.sources[:10000] # self.targets = self.targets[:10000] # logging.warning("Tokenizing inputs... This may take some time...") # data_dict = preprocess(sources, targets, tokenizer) # del sources, targets # gc.collect() # self.input_ids = data_dict["input_ids"] # self.labels = data_dict["labels"] # del data_dict # gc.collect() logging.warning("there are {} data in dataset".format(len(self.sources))) def __len__(self): return len(self.sources) def __getitem__(self, i): # return dict(input_ids=self.input_ids[i], labels=self.labels[i]) source = [self.sources[i]] target = [self.targets[i]] data_dict = preprocess(source, target, self.tokenizer) input_ids = data_dict["input_ids"][0] labels = data_dict["labels"][0] return dict(input_ids=input_ids, labels=labels) @dataclass class DataCollatorForSupervisedDataset(object): """Collate examples for supervised fine-tuning.""" tokenizer: transformers.PreTrainedTokenizer def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]: input_ids, labels = tuple( [instance[key] for instance in instances] for key in ("input_ids", "labels") ) input_ids = torch.nn.utils.rnn.pad_sequence( input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id ) labels = torch.nn.utils.rnn.pad_sequence( labels, batch_first=True, padding_value=IGNORE_INDEX ) return dict( input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ) class SavePeftModelCallback(transformers.TrainerCallback): def save_model(self, args, state, kwargs): # print('Saving PEFT checkpoint...') if state.best_model_checkpoint is not None: checkpoint_folder = os.path.join( state.best_model_checkpoint, "adapter_model" ) else: checkpoint_folder = os.path.join( args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}" ) peft_model_path = os.path.join(checkpoint_folder, "adapter_model") model = kwargs["model"] model.save_pretrained(peft_model_path) moe_state = {} for param_tensor in model.state_dict(): if "adapter" in param_tensor: moe_state.update({param_tensor: model.state_dict()[param_tensor]}) # if "adapter" in param_tensor or "norm" in param_tensor: # moe_state.update({param_tensor: model.state_dict()[param_tensor]}) moe_model_path = os.path.join(checkpoint_folder, "moe_model.bin") # print(moe_state.keys()) torch.save(moe_state, moe_model_path) pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin") if os.path.exists(pytorch_model_path): os.remove(pytorch_model_path) def on_save(self, args, state, control, **kwargs): self.save_model(args, state, kwargs) return control def on_train_end(self, args, state, control, **kwargs): def touch(fname, times=None): with open(fname, "a"): os.utime(fname, times) touch(join(args.output_dir, "completed")) self.save_model(args, state, kwargs) def make_supervised_data_module( tokenizer: transformers.PreTrainedTokenizer, data_args ) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = SupervisedDataset( tokenizer=tokenizer, data_path=data_args.data_path ) data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer) return dict( train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator ) def find_all_linear_names(model, bits=4): cls = ( bnb.nn.Linear4bit if bits == 4 else (bnb.nn.Linear8bitLt if bits == 8 else torch.nn.Linear) ) lora_module_names = set() for name, module in model.named_modules(): if isinstance(module, cls): names = name.split(".") lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if "lm_head" in lora_module_names: # needed for 16-bit lora_module_names.remove("lm_head") return list(lora_module_names) def print_trainable_parameters(model): """ Prints the number of trainable parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): all_param += param.numel() if param.requires_grad: trainable_params += param.numel() print( f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}" ) def train(): parser = transformers.HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments) ) model_args, data_args, training_args = parser.parse_args_into_dataclasses() training_args.ddp_find_unused_parameters = False set_seed(42)
model_config = CamelidaeConfig.from_pretrained(model_args.model_name_or_path)
0
2023-12-22 02:54:29+00:00
16k
lchen1019/Image_Cropper
ISAT/widgets/mainwindow.py
[ { "identifier": "Ui_MainWindow", "path": "ISAT/ui/MainWindow.py", "snippet": "class Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(1280, 764)\n MainWindow.setMinimumSize(QtCore.QSize(800, 600))\n font ...
from PyQt5 import QtWidgets, QtCore, QtGui from ISAT.ui.MainWindow import Ui_MainWindow from ISAT.widgets.files_dock_widget import FilesDockWidget from ISAT.widgets.canvas import AnnotationScene, AnnotationView from ISAT.configs import STATUSMode, MAPMode, load_config, save_config, CONFIG_FILE, DEFAULT_CONFIG_FILE, CHECKPOINT_PATH, ISAT_ROOT from ISAT.annotation import Object, Annotation from ISAT.widgets.polygon import Polygon, PromptPoint from ISAT.widgets.converter_dialog import ConverterDialog from PIL import Image from PyQt5.QtCore import QThread, pyqtSignal import os import json import functools import imgviz import ISAT.icons_rc import numpy as np import cv2 # 调整图像饱和度
12,578
# -*- coding: utf-8 -*- # @Author : LG class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.image_root: str = None self.label_root:str = None self.files_list: list = [] self.current_index = None self.current_file_index: int = None self.current_group = 1 self.config_file = CONFIG_FILE if os.path.exists(CONFIG_FILE) else DEFAULT_CONFIG_FILE self.saved = True self.can_be_annotated = True self.load_finished = False self.png_palette = None # 图像拥有调色盘,说明是单通道的标注png文件 self.instance_cmap = imgviz.label_colormap() # 标注目标
# -*- coding: utf-8 -*- # @Author : LG class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.image_root: str = None self.label_root:str = None self.files_list: list = [] self.current_index = None self.current_file_index: int = None self.current_group = 1 self.config_file = CONFIG_FILE if os.path.exists(CONFIG_FILE) else DEFAULT_CONFIG_FILE self.saved = True self.can_be_annotated = True self.load_finished = False self.png_palette = None # 图像拥有调色盘,说明是单通道的标注png文件 self.instance_cmap = imgviz.label_colormap() # 标注目标
self.current_label:Annotation = None
13
2023-12-24 16:19:16+00:00
16k
khabbazan/Mattermost-Subscriptions
helpers/channels_graphql_ws/subscription.py
[ { "identifier": "GraphqlWsConsumer", "path": "helpers/channels_graphql_ws/graphql_ws_consumer.py", "snippet": "class GraphqlWsConsumer(ch_websocket.AsyncJsonWebsocketConsumer):\n \"\"\"Channels consumer for the WebSocket GraphQL backend.\n\n NOTE: Each instance of this class maintains one WebSocke...
import asyncio import collections import hashlib import logging import asgiref.sync import channels.db import channels.layers import graphene import graphene.types.objecttype import graphene.types.utils import graphene.utils.get_unbound_function import graphene.utils.props from typing import Optional from .graphql_ws_consumer import GraphqlWsConsumer from .serializer import Serializer
12,692
Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Required. Args: payload: The `payload` from the `broadcast` invocation. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. Returns: The same that any Graphene resolver returns. [async] subscribe(root, info, *args, **kwds): Called when client subscribes. Define this to do some extra work when client subscribes and to group subscriptions into different subscription groups. Method signature is the same as in other GraphQL "resolver" methods but it may return the subscription groups names to put the subscription into. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Optional. Args: root: Root resolver object. Typically `None`. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. Returns: The list or tuple of subscription group names this subscription instance belongs to. Later the subscription will trigger on publishes to any of that groups. If method returns None (default behavior) then the subscription is only put to the default group (the one which corresponds to the `Subscription` subclass). [async] unsubscribed(root, info, *args, **kwds): Called when client unsubscribes. Define this to be notified when client unsubscribes. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Args: root: Always `None`. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. The methods enlisted above receives "standard" set of GraphQL resolver arguments. The `info` field has `context` which can be used to transmit some useful payload between these methods. For example if `subscribe` sets `info.context.zen=42` then `publish` will have access to this value as `info.context.zen`. Static methods of subscription subclass: broadcast(): Call this to notify all subscriptions in the group. unsubscribe(): Call this to stop all subscriptions in the group. NOTE: If you call any of these methods from the asynchronous context then `await` the result of the call. """ # ----------------------------------------------------------------------- PUBLIC API # Subscription notifications queue limit. Set this to control the # amount of notifications server keeps in the queue when # notifications come faster than server processes them. Setting this # to 1 drops all notifications in the queue except the latest one. # Useful to skip intermediate notifications, e.g. progress reports. notification_queue_limit: Optional[int] = None @classmethod def broadcast(cls, *, group=None, payload=None): """Call this method to notify all subscriptions in the group. Can be called from both synchronous and asynchronous contexts. It is necessary to `await` if called from the async context. Args: group: Name of the subscription group which members must be notified. `None` means that all the subscriptions of type will be triggered. payload: The payload delivered to the `publish` handler. NOTE: The `payload` is serialized before sending to the subscription group. """ try: event_loop = asyncio.get_event_loop() except RuntimeError: pass else: if event_loop.is_running(): return event_loop.create_task(cls.broadcast_async(group=group, payload=payload)) return cls.broadcast_sync(group=group, payload=payload) @classmethod async def broadcast_async(cls, *, group=None, payload=None): """Broadcast, asynchronous version.""" # Manually serialize the `payload` to allow transfer of Django # models inside `payload`, auto serialization does not do this.
# Copyright (C) DATADVANCE, 2010-2023 # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """Graphene-like subscription class. The `Subscription` class itself is a "creative" copy of `Mutation` class from the Graphene (`graphene/types/mutation.py`). """ # Module logger. LOG = logging.getLogger(__name__) class Subscription(graphene.ObjectType): """Subscription type definition. Subclass this the Subscription class to define a GraphQL subscription. The class works with the `GraphqlWsConsumer` which maintains a WebSocket connection with the client. The subclass specifies the following methods. You can define each of them as a `@classmethod`, as a `@staticmethod`, or even as a regular method (like Graphene typically does). It shall work fine either way. NOTE, if you define the method as a regular method (not a classmethod or a staticmethod) you will receive the first argument (`payload`/`root`) into the `self` argument. [async] publish(payload, info, *args, **kwds): This method invoked each time subscription "triggers". Raising an exception here will lead to sending the notification with the error. Technically the WebSocket message will contain extra field "extensions.code" holding the classname of the exception raised. To suppress the notification return `None`. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Required. Args: payload: The `payload` from the `broadcast` invocation. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. Returns: The same that any Graphene resolver returns. [async] subscribe(root, info, *args, **kwds): Called when client subscribes. Define this to do some extra work when client subscribes and to group subscriptions into different subscription groups. Method signature is the same as in other GraphQL "resolver" methods but it may return the subscription groups names to put the subscription into. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Optional. Args: root: Root resolver object. Typically `None`. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. Returns: The list or tuple of subscription group names this subscription instance belongs to. Later the subscription will trigger on publishes to any of that groups. If method returns None (default behavior) then the subscription is only put to the default group (the one which corresponds to the `Subscription` subclass). [async] unsubscribed(root, info, *args, **kwds): Called when client unsubscribes. Define this to be notified when client unsubscribes. Can be implemented as both asynchronous (`async def`) or synchronous (`def`) function. Asynchronous implementation runs blazingly fast in the main event loop of the main thread. You must be careful with blocking calls though. You can offload blocking operations to a thread in such cases. Synchronous implementation always runs in a worker thread which comes with a price of extra overhead. Args: root: Always `None`. info: The value of `info.context` is a Channels websocket context with all the connection information. args, kwds: Values of the GraphQL subscription inputs. The methods enlisted above receives "standard" set of GraphQL resolver arguments. The `info` field has `context` which can be used to transmit some useful payload between these methods. For example if `subscribe` sets `info.context.zen=42` then `publish` will have access to this value as `info.context.zen`. Static methods of subscription subclass: broadcast(): Call this to notify all subscriptions in the group. unsubscribe(): Call this to stop all subscriptions in the group. NOTE: If you call any of these methods from the asynchronous context then `await` the result of the call. """ # ----------------------------------------------------------------------- PUBLIC API # Subscription notifications queue limit. Set this to control the # amount of notifications server keeps in the queue when # notifications come faster than server processes them. Setting this # to 1 drops all notifications in the queue except the latest one. # Useful to skip intermediate notifications, e.g. progress reports. notification_queue_limit: Optional[int] = None @classmethod def broadcast(cls, *, group=None, payload=None): """Call this method to notify all subscriptions in the group. Can be called from both synchronous and asynchronous contexts. It is necessary to `await` if called from the async context. Args: group: Name of the subscription group which members must be notified. `None` means that all the subscriptions of type will be triggered. payload: The payload delivered to the `publish` handler. NOTE: The `payload` is serialized before sending to the subscription group. """ try: event_loop = asyncio.get_event_loop() except RuntimeError: pass else: if event_loop.is_running(): return event_loop.create_task(cls.broadcast_async(group=group, payload=payload)) return cls.broadcast_sync(group=group, payload=payload) @classmethod async def broadcast_async(cls, *, group=None, payload=None): """Broadcast, asynchronous version.""" # Manually serialize the `payload` to allow transfer of Django # models inside `payload`, auto serialization does not do this.
serialized_payload = await channels.db.database_sync_to_async(Serializer.serialize, thread_sensitive=False)(payload)
1
2023-12-25 11:40:56+00:00
16k
facebookresearch/ca_body
ca_body/models/mesh_vae_drivable.py
[ { "identifier": "ConvBlock", "path": "ca_body/nn/blocks.py", "snippet": "class ConvBlock(nn.Module):\n def __init__(\n self,\n in_channels,\n out_channels,\n size,\n lrelu_slope=0.2,\n kernel_size=3,\n padding=1,\n wnorm_dim=0,\n ):\n ...
import logging import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F import ca_body.nn.layers as la from typing import Dict, Optional, Tuple from torchvision.utils import make_grid from torchvision.transforms.functional import gaussian_blur from ca_body.nn.blocks import ( ConvBlock, ConvDownBlock, UpConvBlockDeep, tile2d, weights_initializer, ) from ca_body.nn.dof_cal import LearnableBlur from ca_body.utils.geom import ( GeometryModule, compute_view_cos, depth_discontuity_mask, depth2normals, ) from ca_body.nn.shadow import ShadowUNet, PoseToShadow from ca_body.nn.unet import UNetWB from ca_body.nn.color_cal import CalV5 from ca_body.utils.image import linear2displayBatch from ca_body.utils.lbs import LBSModule from ca_body.utils.render import RenderLayer from ca_body.utils.seams import SeamSampler from ca_body.utils.render import RenderLayer from ca_body.nn.face import FaceDecoderFrontal
13,133
x = self.conv_blocks[b](x) # NOTE: here we do resampling at feature level x = self.seam_sampler.impaint(x) x = self.seam_sampler.resample(x) x = self.seam_sampler.resample(x) verts_features, tex_features = th.split(x, self.n_channels[-1], 1) verts_uv_delta_rec = self.verts_conv(verts_features) # TODO: need to get values verts_delta_rec = self.geo_fn.from_uv(verts_uv_delta_rec) tex_mean_rec = self.tex_conv(tex_features) preds = { 'geom_delta_rec': verts_delta_rec, 'geom_uv_delta_rec': verts_uv_delta_rec, 'tex_mean_rec': tex_mean_rec, 'embs_conv': embs_conv, 'pose_conv': pose_conv, } return preds class FaceEncoder(nn.Module): """A joint encoder for tex and geometry.""" def __init__( self, noise_std, assets, n_embs=256, uv_size=512, logvar_scale=0.1, n_vert_in=7306 * 3, prefix="face_", ): """Fixed-width conv encoder.""" super().__init__() # TODO: self.noise_std = noise_std self.n_embs = n_embs self.logvar_scale = logvar_scale self.prefix = prefix self.uv_size = uv_size assert self.uv_size == 512 tex_cond_mask = assets.mugsy_face_mask[..., 0] tex_cond_mask = th.as_tensor(tex_cond_mask, dtype=th.float32)[np.newaxis, np.newaxis] tex_cond_mask = F.interpolate( tex_cond_mask, (self.uv_size, self.uv_size), mode="bilinear", align_corners=True ) self.register_buffer("tex_cond_mask", tex_cond_mask) self.conv_blocks = nn.Sequential( ConvDownBlock(3, 4, 512), ConvDownBlock(4, 8, 256), ConvDownBlock(8, 16, 128), ConvDownBlock(16, 32, 64), ConvDownBlock(32, 64, 32), ConvDownBlock(64, 128, 16), ConvDownBlock(128, 128, 8), ) self.geommod = nn.Sequential(la.LinearWN(n_vert_in, 256), nn.LeakyReLU(0.2, inplace=True)) self.jointmod = nn.Sequential( la.LinearWN(256 + 128 * 4 * 4, 512), nn.LeakyReLU(0.2, inplace=True) ) # TODO: should we put initializer self.mu = la.LinearWN(512, self.n_embs) self.logvar = la.LinearWN(512, self.n_embs) self.apply(weights_initializer(0.2)) self.mu.apply(weights_initializer(1.0)) self.logvar.apply(weights_initializer(1.0)) # TODO: compute_losses()? def forward(self, face_geom: th.Tensor, face_tex: th.Tensor, **kwargs): B = face_geom.shape[0] tex_cond = F.interpolate( face_tex, (self.uv_size, self.uv_size), mode="bilinear", align_corners=False ) tex_cond = (tex_cond / 255.0 - 0.5) * self.tex_cond_mask x = self.conv_blocks(tex_cond) tex_enc = x.reshape(B, 4 * 4 * 128) geom_enc = self.geommod(face_geom.reshape(B, -1)) x = self.jointmod(th.cat([tex_enc, geom_enc], dim=1)) embs_mu = self.mu(x) embs_logvar = self.logvar_scale * self.logvar(x) # NOTE: the noise is only applied to the input-conditioned values if self.training: noise = th.randn_like(embs_mu) embs = embs_mu + th.exp(embs_logvar) * noise * self.noise_std else: embs = embs_mu.clone() preds = {"embs": embs, "embs_mu": embs_mu, "embs_logvar": embs_logvar, "tex_cond": tex_cond} preds = {f"{self.prefix}{k}": v for k, v in preds.items()} return preds class UNetViewDecoder(nn.Module): def __init__(self, geo_fn, net_uv_size, seam_sampler, n_init_ftrs=8): super().__init__() self.geo_fn = geo_fn self.net_uv_size = net_uv_size self.unet = UNetWB(4, 3, n_init_ftrs=n_init_ftrs, size=net_uv_size) self.register_buffer("faces", self.geo_fn.vi.to(th.int64), persistent=False) def forward(self, geom_rec, tex_mean_rec, camera_pos): with th.no_grad():
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. logger = logging.getLogger(__name__) class CameraPixelBias(nn.Module): def __init__(self, image_height, image_width, cameras, ds_rate) -> None: super().__init__() self.image_height = image_height self.image_width = image_width self.cameras = cameras self.n_cameras = len(cameras) bias = th.zeros( (self.n_cameras, 1, image_width // ds_rate, image_height // ds_rate), dtype=th.float32 ) self.register_parameter("bias", nn.Parameter(bias)) def forward(self, idxs: th.Tensor): bias_up = F.interpolate( self.bias[idxs], size=(self.image_height, self.image_width), mode='bilinear' ) return bias_up class AutoEncoder(nn.Module): def __init__( self, encoder, decoder, decoder_view, encoder_face, # hqlp decoder to get the codes decoder_face, shadow_net, upscale_net, assets, pose_to_shadow=None, renderer=None, cal=None, pixel_cal=None, learn_blur: bool = True, ): super().__init__() # TODO: should we have a shared LBS here? self.geo_fn = GeometryModule( assets.topology.vi, assets.topology.vt, assets.topology.vti, assets.topology.v2uv, uv_size=1024, impaint=True, ) self.lbs_fn = LBSModule( assets.lbs_model_json, assets.lbs_config_dict, assets.lbs_template_verts, assets.lbs_scale, assets.global_scaling, ) self.seam_sampler = SeamSampler(assets.seam_data_1024) self.seam_sampler_2k = SeamSampler(assets.seam_data_2048) # joint tex -> body and clothes # TODO: why do we have a joint one in the first place? tex_mean = gaussian_blur(th.as_tensor(assets.tex_mean)[np.newaxis], kernel_size=11) self.register_buffer("tex_mean", F.interpolate(tex_mean, (2048, 2048), mode='bilinear')) # this is shared self.tex_std = assets.tex_var if 'tex_var' in assets else 64.0 face_cond_mask = th.as_tensor(assets.face_cond_mask, dtype=th.float32)[ np.newaxis, np.newaxis ] self.register_buffer("face_cond_mask", face_cond_mask) meye_mask = self.geo_fn.to_uv( th.as_tensor(assets.mouth_eyes_mask_geom[np.newaxis, :, np.newaxis]) ) meye_mask = F.interpolate(meye_mask, (2048, 2048), mode='bilinear') self.register_buffer("meye_mask", meye_mask) self.decoder = ConvDecoder( geo_fn=self.geo_fn, seam_sampler=self.seam_sampler, **decoder, assets=assets, ) # embs for everything but face non_head_mask = 1.0 - assets.face_mask self.encoder = Encoder( geo_fn=self.geo_fn, mask=non_head_mask, **encoder, ) self.encoder_face = FaceEncoder( assets=assets, **encoder_face, ) # using face decoder to generate better conditioning decoder_face_ckpt_path = None if 'ckpt' in decoder_face: decoder_face_ckpt_path = decoder_face.pop('ckpt') self.decoder_face = FaceDecoderFrontal(assets=assets, **decoder_face) if decoder_face_ckpt_path is not None: self.decoder_face.load_state_dict(th.load(decoder_face_ckpt_path), strict=False) self.decoder_view = UNetViewDecoder( self.geo_fn, seam_sampler=self.seam_sampler, **decoder_view, ) self.shadow_net = ShadowUNet( ao_mean=assets.ao_mean, interp_mode="bilinear", biases=False, **shadow_net, ) self.pose_to_shadow_enabled = False if pose_to_shadow is not None: self.pose_to_shadow_enabled = True self.pose_to_shadow = PoseToShadow(**pose_to_shadow) self.upscale_net = UpscaleNet( in_channels=6, size=1024, upscale_factor=2, out_channels=3, **upscale_net ) self.pixel_cal_enabled = False if pixel_cal is not None: self.pixel_cal_enabled = True self.pixel_cal = CameraPixelBias(**pixel_cal, cameras=assets.camera_ids) self.learn_blur_enabled = False if learn_blur: self.learn_blur_enabled = True self.learn_blur = LearnableBlur(assets.camera_ids) # training-only stuff self.cal_enabled = False if cal is not None: self.cal_enabled = True self.cal = CalV5(**cal, cameras=assets.camera_ids) self.rendering_enabled = False if renderer is not None: self.rendering_enabled = True self.renderer = RenderLayer( h=renderer.image_height, w=renderer.image_width, vt=self.geo_fn.vt, vi=self.geo_fn.vi, vti=self.geo_fn.vti, flip_uvs=False, ) @th.jit.unused def compute_summaries(self, preds, batch): # TODO: switch to common summaries? # return compute_summaries_mesh(preds, batch) rgb = linear2displayBatch(preds['rgb'][:, :3]) rgb_gt = linear2displayBatch(batch['image']) depth = preds['depth'][:, np.newaxis] mask = depth > 0.0 normals = ( 255 * (1.0 - depth2normals(depth, batch['focal'], batch['princpt'])) / 2.0 ) * mask grid_rgb = make_grid(rgb, nrow=16).permute(1, 2, 0).clip(0, 255).to(th.uint8) grid_rgb_gt = make_grid(rgb_gt, nrow=16).permute(1, 2, 0).clip(0, 255).to(th.uint8) grid_normals = make_grid(normals, nrow=16).permute(1, 2, 0).clip(0, 255).to(th.uint8) progress_image = th.cat([grid_rgb, grid_rgb_gt, grid_normals], dim=0) return { 'progress_image': (progress_image, 'png'), } def forward_tex(self, tex_mean_rec, tex_view_rec, shadow_map): x = th.cat([tex_mean_rec, tex_view_rec], dim=1) tex_rec = tex_mean_rec + tex_view_rec tex_rec = self.seam_sampler.impaint(tex_rec) tex_rec = self.seam_sampler.resample(tex_rec) tex_rec = F.interpolate(tex_rec, size=(2048, 2048), mode="bilinear", align_corners=False) tex_rec = tex_rec + self.upscale_net(x) tex_rec = tex_rec * self.tex_std + self.tex_mean shadow_map = self.seam_sampler_2k.impaint(shadow_map) shadow_map = self.seam_sampler_2k.resample(shadow_map) shadow_map = self.seam_sampler_2k.resample(shadow_map) tex_rec = tex_rec * shadow_map tex_rec = self.seam_sampler_2k.impaint(tex_rec) tex_rec = self.seam_sampler_2k.resample(tex_rec) tex_rec = self.seam_sampler_2k.resample(tex_rec) return tex_rec def encode(self, geom: th.Tensor, lbs_motion: th.Tensor, face_embs_hqlp: th.Tensor): with th.no_grad(): verts_unposed = self.lbs_fn.unpose(geom, lbs_motion) verts_unposed_uv = self.geo_fn.to_uv(verts_unposed) # extract face region for geom + tex enc_preds = self.encoder(motion=lbs_motion, verts_unposed=verts_unposed) # TODO: probably need to rename these to `face_embs_mugsy` or smth # TODO: we need the same thing for face? # enc_face_preds = self.encoder_face(verts_unposed_uv) with th.no_grad(): face_dec_preds = self.decoder_face(face_embs_hqlp) enc_face_preds = self.encoder_face(**face_dec_preds) preds = { **enc_preds, **enc_face_preds, 'face_dec_preds': face_dec_preds, } return preds def forward( self, # TODO: should we try using this as well for cond? lbs_motion: th.Tensor, campos: th.Tensor, geom: Optional[th.Tensor] = None, ao: Optional[th.Tensor] = None, K: Optional[th.Tensor] = None, Rt: Optional[th.Tensor] = None, image_bg: Optional[th.Tensor] = None, image: Optional[th.Tensor] = None, image_mask: Optional[th.Tensor] = None, embs: Optional[th.Tensor] = None, _index: Optional[Dict[str, th.Tensor]] = None, face_embs: Optional[th.Tensor] = None, embs_conv: Optional[th.Tensor] = None, tex_seg: Optional[th.Tensor] = None, encode=True, iteration: Optional[int] = None, **kwargs, ): B = lbs_motion.shape[0] if not th.jit.is_scripting() and encode: # NOTE: these are `face_embs_hqlp` enc_preds = self.encode(geom, lbs_motion, face_embs) embs = enc_preds['embs'] # NOTE: these are `face_embs` in body space face_embs_body = enc_preds['face_embs'] dec_preds = self.decoder( motion=lbs_motion, embs=embs, face_embs=face_embs_body, embs_conv=embs_conv, ) geom_rec = self.lbs_fn.pose(dec_preds['geom_delta_rec'], lbs_motion) dec_view_preds = self.decoder_view( geom_rec=geom_rec, tex_mean_rec=dec_preds["tex_mean_rec"], camera_pos=campos, ) # TODO: should we train an AO model? if self.training and self.pose_to_shadow_enabled: shadow_preds = self.shadow_net(ao_map=ao) pose_shadow_preds = self.pose_to_shadow(lbs_motion) shadow_preds['pose_shadow_map'] = pose_shadow_preds['shadow_map'] elif self.pose_to_shadow_enabled: shadow_preds = self.pose_to_shadow(lbs_motion) else: shadow_preds = self.shadow_net(ao_map=ao) tex_rec = self.forward_tex( dec_preds["tex_mean_rec"], dec_view_preds["tex_view_rec"], shadow_preds["shadow_map"], ) if not th.jit.is_scripting() and self.cal_enabled: tex_rec = self.cal(tex_rec, self.cal.name_to_idx(_index['camera'])) preds = { 'geom': geom_rec, 'tex_rec': tex_rec, **dec_preds, **shadow_preds, **dec_view_preds, } if not th.jit.is_scripting() and encode: preds.update(**enc_preds) if not th.jit.is_scripting() and self.rendering_enabled: # NOTE: this is a reduced version tested for forward only renders = self.renderer( preds['geom'], tex_rec, K=K, Rt=Rt, ) preds.update(rgb=renders['render']) if not th.jit.is_scripting() and self.learn_blur_enabled: preds['rgb'] = self.learn_blur(preds['rgb'], _index['camera']) preds['learn_blur_weights'] = self.learn_blur.reg(_index['camera']) if not th.jit.is_scripting() and self.pixel_cal_enabled: assert self.cal_enabled cam_idxs = self.cal.name_to_idx(_index['camera']) pixel_bias = self.pixel_cal(cam_idxs) preds['rgb'] = preds['rgb'] + pixel_bias return preds class Encoder(nn.Module): """A joint encoder for tex and geometry.""" def __init__( self, geo_fn, n_embs, noise_std, mask, logvar_scale=0.1, ): """Fixed-width conv encoder.""" super().__init__() self.noise_std = noise_std self.n_embs = n_embs self.geo_fn = geo_fn self.logvar_scale = logvar_scale self.verts_conv = ConvDownBlock(3, 8, 512) mask = th.as_tensor(mask[np.newaxis, np.newaxis], dtype=th.float32) mask = F.interpolate(mask, size=(512, 512), mode='bilinear').to(th.bool) self.register_buffer("mask", mask) self.joint_conv_blocks = nn.Sequential( ConvDownBlock(8, 16, 256), ConvDownBlock(16, 32, 128), ConvDownBlock(32, 32, 64), ConvDownBlock(32, 64, 32), ConvDownBlock(64, 128, 16), ConvDownBlock(128, 128, 8), # ConvDownBlock(128, 128, 4), ) # TODO: should we put initializer self.mu = la.LinearWN(4 * 4 * 128, self.n_embs) self.logvar = la.LinearWN(4 * 4 * 128, self.n_embs) self.apply(weights_initializer(0.2)) self.mu.apply(weights_initializer(1.0)) self.logvar.apply(weights_initializer(1.0)) def forward(self, motion, verts_unposed): preds = {} B = motion.shape[0] # converting motion to the unposed verts_cond = ( F.interpolate(self.geo_fn.to_uv(verts_unposed), size=(512, 512), mode='bilinear') * self.mask ) verts_cond = self.verts_conv(verts_cond) # tex_cond = F.interpolate(tex_avg, size=(512, 512), mode='bilinear') * self.mask # tex_cond = self.tex_conv(tex_cond) # joint_cond = th.cat([verts_cond, tex_cond], dim=1) joint_cond = verts_cond x = self.joint_conv_blocks(joint_cond) x = x.reshape(B, -1) embs_mu = self.mu(x) embs_logvar = self.logvar_scale * self.logvar(x) # NOTE: the noise is only applied to the input-conditioned values if self.training: noise = th.randn_like(embs_mu) embs = embs_mu + th.exp(embs_logvar) * noise * self.noise_std else: embs = embs_mu.clone() preds.update( embs=embs, embs_mu=embs_mu, embs_logvar=embs_logvar, ) return preds class ConvDecoder(nn.Module): """Multi-region view-independent decoder.""" def __init__( self, geo_fn, uv_size, seam_sampler, init_uv_size, n_pose_dims, n_pose_enc_channels, n_embs, n_embs_enc_channels, n_face_embs, n_init_channels, n_min_channels, assets, ): super().__init__() self.geo_fn = geo_fn self.uv_size = uv_size self.init_uv_size = init_uv_size self.n_pose_dims = n_pose_dims self.n_pose_enc_channels = n_pose_enc_channels self.n_embs = n_embs self.n_embs_enc_channels = n_embs_enc_channels self.n_face_embs = n_face_embs self.n_blocks = int(np.log2(self.uv_size // init_uv_size)) self.sizes = [init_uv_size * 2**s for s in range(self.n_blocks + 1)] # TODO: just specify a sequence? self.n_channels = [ max(n_init_channels // 2**b, n_min_channels) for b in range(self.n_blocks + 1) ] logger.info(f"ConvDecoder: n_channels = {self.n_channels}") self.local_pose_conv_block = ConvBlock( n_pose_dims, n_pose_enc_channels, init_uv_size, kernel_size=1, padding=0, ) self.embs_fc = nn.Sequential( la.LinearWN(n_embs, 4 * 4 * 128), nn.LeakyReLU(0.2, inplace=True), ) # TODO: should we switch to the basic version? self.embs_conv_block = nn.Sequential( UpConvBlockDeep(128, 128, 8), UpConvBlockDeep(128, 128, 16), UpConvBlockDeep(128, 64, 32), UpConvBlockDeep(64, n_embs_enc_channels, 64), ) self.face_embs_fc = nn.Sequential( la.LinearWN(n_face_embs, 4 * 4 * 32), nn.LeakyReLU(0.2, inplace=True), ) self.face_embs_conv_block = nn.Sequential( UpConvBlockDeep(32, 64, 8), UpConvBlockDeep(64, 64, 16), UpConvBlockDeep(64, n_embs_enc_channels, 32), ) n_groups = 2 self.joint_conv_block = ConvBlock( n_pose_enc_channels + n_embs_enc_channels, n_init_channels, self.init_uv_size, ) self.conv_blocks = nn.ModuleList([]) for b in range(self.n_blocks): self.conv_blocks.append( UpConvBlockDeep( self.n_channels[b] * n_groups, self.n_channels[b + 1] * n_groups, self.sizes[b + 1], groups=n_groups, ), ) self.verts_conv = la.Conv2dWNUB( in_channels=self.n_channels[-1], out_channels=3, kernel_size=3, height=self.uv_size, width=self.uv_size, padding=1, ) self.tex_conv = la.Conv2dWNUB( in_channels=self.n_channels[-1], out_channels=3, kernel_size=3, height=self.uv_size, width=self.uv_size, padding=1, ) self.apply(weights_initializer(0.2)) self.verts_conv.apply(weights_initializer(1.0)) self.tex_conv.apply(weights_initializer(1.0)) self.seam_sampler = seam_sampler # NOTE: removing head region from pose completely pose_cond_mask = th.as_tensor( assets.pose_cond_mask[np.newaxis] * (1 - assets.head_cond_mask[np.newaxis, np.newaxis]), dtype=th.int32, ) self.register_buffer("pose_cond_mask", pose_cond_mask) face_cond_mask = th.as_tensor(assets.face_cond_mask, dtype=th.float32)[ np.newaxis, np.newaxis ] self.register_buffer("face_cond_mask", face_cond_mask) body_cond_mask = th.as_tensor(assets.body_cond_mask, dtype=th.float32)[ np.newaxis, np.newaxis ] self.register_buffer("body_cond_mask", body_cond_mask) def forward(self, motion, embs, face_embs, embs_conv: Optional[th.Tensor] = None): # processing pose pose = motion[:, 6:] B = pose.shape[0] non_head_mask = (self.body_cond_mask * (1.0 - self.face_cond_mask)).clip(0.0, 1.0) pose_masked = tile2d(pose, self.init_uv_size) * self.pose_cond_mask pose_conv = self.local_pose_conv_block(pose_masked) * non_head_mask # TODO: decoding properly? if embs_conv is None: embs_conv = self.embs_conv_block(self.embs_fc(embs).reshape(B, 128, 4, 4)) face_conv = self.face_embs_conv_block(self.face_embs_fc(face_embs).reshape(B, 32, 4, 4)) # merging embeddings with spatial masks embs_conv[:, :, 32:, :32] = ( face_conv * self.face_cond_mask[:, :, 32:, :32] + embs_conv[:, :, 32:, :32] * non_head_mask[:, :, 32:, :32] ) joint = th.cat([pose_conv, embs_conv], axis=1) joint = self.joint_conv_block(joint) x = th.cat([joint, joint], axis=1) for b in range(self.n_blocks): x = self.conv_blocks[b](x) # NOTE: here we do resampling at feature level x = self.seam_sampler.impaint(x) x = self.seam_sampler.resample(x) x = self.seam_sampler.resample(x) verts_features, tex_features = th.split(x, self.n_channels[-1], 1) verts_uv_delta_rec = self.verts_conv(verts_features) # TODO: need to get values verts_delta_rec = self.geo_fn.from_uv(verts_uv_delta_rec) tex_mean_rec = self.tex_conv(tex_features) preds = { 'geom_delta_rec': verts_delta_rec, 'geom_uv_delta_rec': verts_uv_delta_rec, 'tex_mean_rec': tex_mean_rec, 'embs_conv': embs_conv, 'pose_conv': pose_conv, } return preds class FaceEncoder(nn.Module): """A joint encoder for tex and geometry.""" def __init__( self, noise_std, assets, n_embs=256, uv_size=512, logvar_scale=0.1, n_vert_in=7306 * 3, prefix="face_", ): """Fixed-width conv encoder.""" super().__init__() # TODO: self.noise_std = noise_std self.n_embs = n_embs self.logvar_scale = logvar_scale self.prefix = prefix self.uv_size = uv_size assert self.uv_size == 512 tex_cond_mask = assets.mugsy_face_mask[..., 0] tex_cond_mask = th.as_tensor(tex_cond_mask, dtype=th.float32)[np.newaxis, np.newaxis] tex_cond_mask = F.interpolate( tex_cond_mask, (self.uv_size, self.uv_size), mode="bilinear", align_corners=True ) self.register_buffer("tex_cond_mask", tex_cond_mask) self.conv_blocks = nn.Sequential( ConvDownBlock(3, 4, 512), ConvDownBlock(4, 8, 256), ConvDownBlock(8, 16, 128), ConvDownBlock(16, 32, 64), ConvDownBlock(32, 64, 32), ConvDownBlock(64, 128, 16), ConvDownBlock(128, 128, 8), ) self.geommod = nn.Sequential(la.LinearWN(n_vert_in, 256), nn.LeakyReLU(0.2, inplace=True)) self.jointmod = nn.Sequential( la.LinearWN(256 + 128 * 4 * 4, 512), nn.LeakyReLU(0.2, inplace=True) ) # TODO: should we put initializer self.mu = la.LinearWN(512, self.n_embs) self.logvar = la.LinearWN(512, self.n_embs) self.apply(weights_initializer(0.2)) self.mu.apply(weights_initializer(1.0)) self.logvar.apply(weights_initializer(1.0)) # TODO: compute_losses()? def forward(self, face_geom: th.Tensor, face_tex: th.Tensor, **kwargs): B = face_geom.shape[0] tex_cond = F.interpolate( face_tex, (self.uv_size, self.uv_size), mode="bilinear", align_corners=False ) tex_cond = (tex_cond / 255.0 - 0.5) * self.tex_cond_mask x = self.conv_blocks(tex_cond) tex_enc = x.reshape(B, 4 * 4 * 128) geom_enc = self.geommod(face_geom.reshape(B, -1)) x = self.jointmod(th.cat([tex_enc, geom_enc], dim=1)) embs_mu = self.mu(x) embs_logvar = self.logvar_scale * self.logvar(x) # NOTE: the noise is only applied to the input-conditioned values if self.training: noise = th.randn_like(embs_mu) embs = embs_mu + th.exp(embs_logvar) * noise * self.noise_std else: embs = embs_mu.clone() preds = {"embs": embs, "embs_mu": embs_mu, "embs_logvar": embs_logvar, "tex_cond": tex_cond} preds = {f"{self.prefix}{k}": v for k, v in preds.items()} return preds class UNetViewDecoder(nn.Module): def __init__(self, geo_fn, net_uv_size, seam_sampler, n_init_ftrs=8): super().__init__() self.geo_fn = geo_fn self.net_uv_size = net_uv_size self.unet = UNetWB(4, 3, n_init_ftrs=n_init_ftrs, size=net_uv_size) self.register_buffer("faces", self.geo_fn.vi.to(th.int64), persistent=False) def forward(self, geom_rec, tex_mean_rec, camera_pos): with th.no_grad():
view_cos = compute_view_cos(geom_rec, self.faces, camera_pos)
7
2023-12-27 15:31:35+00:00
16k
open-mmlab/Amphion
modules/wenet_extractor/squeezeformer/encoder.py
[ { "identifier": "DepthwiseConv2dSubsampling4", "path": "modules/wenet_extractor/squeezeformer/subsampling.py", "snippet": "class DepthwiseConv2dSubsampling4(BaseSubsampling):\n \"\"\"Depthwise Convolutional 2D subsampling (to 1/4 length).\n\n Args:\n idim (int): Input dimension.\n od...
import torch import torch.nn as nn from typing import Tuple, Union, Optional, List from modules.wenet_extractor.squeezeformer.subsampling import ( DepthwiseConv2dSubsampling4, TimeReductionLayer1D, TimeReductionLayer2D, TimeReductionLayerStream, ) from modules.wenet_extractor.squeezeformer.encoder_layer import ( SqueezeformerEncoderLayer, ) from modules.wenet_extractor.transformer.embedding import RelPositionalEncoding from modules.wenet_extractor.transformer.attention import MultiHeadedAttention from modules.wenet_extractor.squeezeformer.attention import ( RelPositionMultiHeadedAttention, ) from modules.wenet_extractor.squeezeformer.positionwise_feed_forward import ( PositionwiseFeedForward, ) from modules.wenet_extractor.squeezeformer.convolution import ConvolutionModule from modules.wenet_extractor.utils.mask import make_pad_mask, add_optional_chunk_mask from modules.wenet_extractor.utils.common import get_activation
14,125
# This module is from [WeNet](https://github.com/wenet-e2e/wenet). # ## Citations # ```bibtex # @inproceedings{yao2021wenet, # title={WeNet: Production oriented Streaming and Non-streaming End-to-End Speech Recognition Toolkit}, # author={Yao, Zhuoyuan and Wu, Di and Wang, Xiong and Zhang, Binbin and Yu, Fan and Yang, Chao and Peng, Zhendong and Chen, Xiaoyu and Xie, Lei and Lei, Xin}, # booktitle={Proc. Interspeech}, # year={2021}, # address={Brno, Czech Republic }, # organization={IEEE} # } # @article{zhang2022wenet, # title={WeNet 2.0: More Productive End-to-End Speech Recognition Toolkit}, # author={Zhang, Binbin and Wu, Di and Peng, Zhendong and Song, Xingchen and Yao, Zhuoyuan and Lv, Hang and Xie, Lei and Yang, Chao and Pan, Fuping and Niu, Jianwei}, # journal={arXiv preprint arXiv:2203.15455}, # year={2022} # } # class SqueezeformerEncoder(nn.Module): def __init__( self, input_size: int = 80, encoder_dim: int = 256, output_size: int = 256, attention_heads: int = 4, num_blocks: int = 12, reduce_idx: Optional[Union[int, List[int]]] = 5, recover_idx: Optional[Union[int, List[int]]] = 11, feed_forward_expansion_factor: int = 4, dw_stride: bool = False, input_dropout_rate: float = 0.1, pos_enc_layer_type: str = "rel_pos", time_reduction_layer_type: str = "conv1d", do_rel_shift: bool = True, feed_forward_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.1, cnn_module_kernel: int = 31, cnn_norm_type: str = "batch_norm", dropout: float = 0.1, causal: bool = False, adaptive_scale: bool = True, activation_type: str = "swish", init_weights: bool = True, global_cmvn: torch.nn.Module = None, normalize_before: bool = False, use_dynamic_chunk: bool = False, concat_after: bool = False, static_chunk_size: int = 0, use_dynamic_left_chunk: bool = False, ): """Construct SqueezeformerEncoder Args: input_size to use_dynamic_chunk, see in Transformer BaseEncoder. encoder_dim (int): The hidden dimension of encoder layer. output_size (int): The output dimension of final projection layer. attention_heads (int): Num of attention head in attention module. num_blocks (int): Num of encoder layers. reduce_idx Optional[Union[int, List[int]]]: reduce layer index, from 40ms to 80ms per frame. recover_idx Optional[Union[int, List[int]]]: recover layer index, from 80ms to 40ms per frame. feed_forward_expansion_factor (int): Enlarge coefficient of FFN. dw_stride (bool): Whether do depthwise convolution on subsampling module. input_dropout_rate (float): Dropout rate of input projection layer. pos_enc_layer_type (str): Self attention type. time_reduction_layer_type (str): Conv1d or Conv2d reduction layer. do_rel_shift (bool): Whether to do relative shift operation on rel-attention module. cnn_module_kernel (int): Kernel size of CNN module. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. cnn_module_kernel (int): Kernel size of convolution module. adaptive_scale (bool): Whether to use adaptive scale. init_weights (bool): Whether to initialize weights. causal (bool): whether to use causal convolution or not. """ super(SqueezeformerEncoder, self).__init__() self.global_cmvn = global_cmvn self.reduce_idx: Optional[Union[int, List[int]]] = ( [reduce_idx] if type(reduce_idx) == int else reduce_idx ) self.recover_idx: Optional[Union[int, List[int]]] = ( [recover_idx] if type(recover_idx) == int else recover_idx ) self.check_ascending_list() if reduce_idx is None: self.time_reduce = None else: if recover_idx is None: self.time_reduce = "normal" # no recovery at the end else: self.time_reduce = "recover" # recovery at the end assert len(self.reduce_idx) == len(self.recover_idx) self.reduce_stride = 2 self._output_size = output_size self.normalize_before = normalize_before self.static_chunk_size = static_chunk_size self.use_dynamic_chunk = use_dynamic_chunk self.use_dynamic_left_chunk = use_dynamic_left_chunk self.pos_enc_layer_type = pos_enc_layer_type activation = get_activation(activation_type) # self-attention module definition if pos_enc_layer_type != "rel_pos":
# This module is from [WeNet](https://github.com/wenet-e2e/wenet). # ## Citations # ```bibtex # @inproceedings{yao2021wenet, # title={WeNet: Production oriented Streaming and Non-streaming End-to-End Speech Recognition Toolkit}, # author={Yao, Zhuoyuan and Wu, Di and Wang, Xiong and Zhang, Binbin and Yu, Fan and Yang, Chao and Peng, Zhendong and Chen, Xiaoyu and Xie, Lei and Lei, Xin}, # booktitle={Proc. Interspeech}, # year={2021}, # address={Brno, Czech Republic }, # organization={IEEE} # } # @article{zhang2022wenet, # title={WeNet 2.0: More Productive End-to-End Speech Recognition Toolkit}, # author={Zhang, Binbin and Wu, Di and Peng, Zhendong and Song, Xingchen and Yao, Zhuoyuan and Lv, Hang and Xie, Lei and Yang, Chao and Pan, Fuping and Niu, Jianwei}, # journal={arXiv preprint arXiv:2203.15455}, # year={2022} # } # class SqueezeformerEncoder(nn.Module): def __init__( self, input_size: int = 80, encoder_dim: int = 256, output_size: int = 256, attention_heads: int = 4, num_blocks: int = 12, reduce_idx: Optional[Union[int, List[int]]] = 5, recover_idx: Optional[Union[int, List[int]]] = 11, feed_forward_expansion_factor: int = 4, dw_stride: bool = False, input_dropout_rate: float = 0.1, pos_enc_layer_type: str = "rel_pos", time_reduction_layer_type: str = "conv1d", do_rel_shift: bool = True, feed_forward_dropout_rate: float = 0.1, attention_dropout_rate: float = 0.1, cnn_module_kernel: int = 31, cnn_norm_type: str = "batch_norm", dropout: float = 0.1, causal: bool = False, adaptive_scale: bool = True, activation_type: str = "swish", init_weights: bool = True, global_cmvn: torch.nn.Module = None, normalize_before: bool = False, use_dynamic_chunk: bool = False, concat_after: bool = False, static_chunk_size: int = 0, use_dynamic_left_chunk: bool = False, ): """Construct SqueezeformerEncoder Args: input_size to use_dynamic_chunk, see in Transformer BaseEncoder. encoder_dim (int): The hidden dimension of encoder layer. output_size (int): The output dimension of final projection layer. attention_heads (int): Num of attention head in attention module. num_blocks (int): Num of encoder layers. reduce_idx Optional[Union[int, List[int]]]: reduce layer index, from 40ms to 80ms per frame. recover_idx Optional[Union[int, List[int]]]: recover layer index, from 80ms to 40ms per frame. feed_forward_expansion_factor (int): Enlarge coefficient of FFN. dw_stride (bool): Whether do depthwise convolution on subsampling module. input_dropout_rate (float): Dropout rate of input projection layer. pos_enc_layer_type (str): Self attention type. time_reduction_layer_type (str): Conv1d or Conv2d reduction layer. do_rel_shift (bool): Whether to do relative shift operation on rel-attention module. cnn_module_kernel (int): Kernel size of CNN module. activation_type (str): Encoder activation function type. use_cnn_module (bool): Whether to use convolution module. cnn_module_kernel (int): Kernel size of convolution module. adaptive_scale (bool): Whether to use adaptive scale. init_weights (bool): Whether to initialize weights. causal (bool): whether to use causal convolution or not. """ super(SqueezeformerEncoder, self).__init__() self.global_cmvn = global_cmvn self.reduce_idx: Optional[Union[int, List[int]]] = ( [reduce_idx] if type(reduce_idx) == int else reduce_idx ) self.recover_idx: Optional[Union[int, List[int]]] = ( [recover_idx] if type(recover_idx) == int else recover_idx ) self.check_ascending_list() if reduce_idx is None: self.time_reduce = None else: if recover_idx is None: self.time_reduce = "normal" # no recovery at the end else: self.time_reduce = "recover" # recovery at the end assert len(self.reduce_idx) == len(self.recover_idx) self.reduce_stride = 2 self._output_size = output_size self.normalize_before = normalize_before self.static_chunk_size = static_chunk_size self.use_dynamic_chunk = use_dynamic_chunk self.use_dynamic_left_chunk = use_dynamic_left_chunk self.pos_enc_layer_type = pos_enc_layer_type activation = get_activation(activation_type) # self-attention module definition if pos_enc_layer_type != "rel_pos":
encoder_selfattn_layer = MultiHeadedAttention
6
2023-11-15 09:19:27+00:00
16k
BobaZooba/xllm
src/xllm/cli/fuse.py
[ { "identifier": "Config", "path": "src/xllm/core/config.py", "snippet": "class Config:\n \"\"\"\n The `Config` class serves as a comprehensive configuration schema for managing various parameters required during\n the setup and execution of experiments relating to language models, such as train...
from typing import Tuple, Type from transformers import HfArgumentParser, PreTrainedModel, PreTrainedTokenizer from ..core.config import Config from ..run.fuse import fuse from ..utils.cli import setup_cli
12,316
# Copyright 2023 Boris Zubarev. All rights reserved. # # 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. def cli_run_fuse( config_cls: Type[Config] = Config, ) -> Tuple[PreTrainedTokenizer, PreTrainedModel]: """ Provides a command-line interface (CLI) entry point for fusing LoRA parameters into the model after training. This function serves as a script for fusing parameters using the LoRA technique by parsing command-line arguments to configure the process and then invoking the `fuse` function. It also manages CLI-related configurations, including setting up logging for the process. Args: config_cls (Type[Config], defaults to `Config`): The configuration class type to be used for parsing the command-line arguments into a configuration object. This class should define the necessary parameters for the fusing process. Returns: Tuple[PreTrainedTokenizer, PreTrainedModel]: A tuple containing the tokenizer and the LoRA-fused model. The function performs the following steps: - Initializes an `HfArgumentParser` object with `config_cls` to handle command-line arguments. - Parses the arguments into a configuration object. - Sets up CLI interactions including logging to a file (default is `./xllm_fuse.log`). - Calls the `fuse` function with the parsed configuration object to begin the fusing process. - Returns the tokenizer and the model that have been processed. When the script is executed directly from the command line, it will run the following as part of the main program: - Parse the command-line arguments into a `Config` object. - Fuse the LoRA parameters in the trained model while logging the output to `xllm_fuse.log`. - Return the tokenizer and LoRA-fused model. Example CLI usage: ```sh python cli_run_fuse.py --model_name_or_path my_model ``` Note: This function is particularly meant to be used when working with models that were trained with the LoRA technique. It is intended to be used as part of a CLI workflow and should be executed directly from the terminal or within a script. """ parser = HfArgumentParser(config_cls) config = parser.parse_args_into_dataclasses()[0] setup_cli(config=config, logger_path="./xllm_fuse.log")
# Copyright 2023 Boris Zubarev. All rights reserved. # # 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. def cli_run_fuse( config_cls: Type[Config] = Config, ) -> Tuple[PreTrainedTokenizer, PreTrainedModel]: """ Provides a command-line interface (CLI) entry point for fusing LoRA parameters into the model after training. This function serves as a script for fusing parameters using the LoRA technique by parsing command-line arguments to configure the process and then invoking the `fuse` function. It also manages CLI-related configurations, including setting up logging for the process. Args: config_cls (Type[Config], defaults to `Config`): The configuration class type to be used for parsing the command-line arguments into a configuration object. This class should define the necessary parameters for the fusing process. Returns: Tuple[PreTrainedTokenizer, PreTrainedModel]: A tuple containing the tokenizer and the LoRA-fused model. The function performs the following steps: - Initializes an `HfArgumentParser` object with `config_cls` to handle command-line arguments. - Parses the arguments into a configuration object. - Sets up CLI interactions including logging to a file (default is `./xllm_fuse.log`). - Calls the `fuse` function with the parsed configuration object to begin the fusing process. - Returns the tokenizer and the model that have been processed. When the script is executed directly from the command line, it will run the following as part of the main program: - Parse the command-line arguments into a `Config` object. - Fuse the LoRA parameters in the trained model while logging the output to `xllm_fuse.log`. - Return the tokenizer and LoRA-fused model. Example CLI usage: ```sh python cli_run_fuse.py --model_name_or_path my_model ``` Note: This function is particularly meant to be used when working with models that were trained with the LoRA technique. It is intended to be used as part of a CLI workflow and should be executed directly from the terminal or within a script. """ parser = HfArgumentParser(config_cls) config = parser.parse_args_into_dataclasses()[0] setup_cli(config=config, logger_path="./xllm_fuse.log")
tokenizer, model = fuse(config=config)
1
2023-11-10 17:55:03+00:00
16k
AMAAI-Lab/mustango
audioldm_eval/eval.py
[ { "identifier": "load_npy_data", "path": "audioldm_eval/datasets/load_mel.py", "snippet": "def load_npy_data(loader):\n new_train = []\n for mel, waveform, filename in tqdm(loader):\n batch = batch.float().numpy()\n new_train.append(\n batch.reshape(\n -1,\n...
import os import numpy as np import argparse import torch import audioldm_eval.audio as Audio import time import ipdb from audioldm_eval.datasets.load_mel import load_npy_data, MelPairedDataset, WaveDataset from torch.utils.data import DataLoader from tqdm import tqdm from audioldm_eval.metrics.fad import FrechetAudioDistance from audioldm_eval import calculate_fid, calculate_isc, calculate_kid, calculate_kl from skimage.metrics import peak_signal_noise_ratio as psnr from skimage.metrics import structural_similarity as ssim from audioldm_eval.feature_extractors.panns import Cnn14 from audioldm_eval.audio.tools import save_pickle, load_pickle, write_json, load_json from ssr_eval.metrics import AudioMetrics
10,976
num_workers=num_workers, ) resultloader = DataLoader( WaveDataset( groundtruth_path, self.sampling_rate, limit_num=limit_num, ), batch_size=1, sampler=None, num_workers=num_workers, ) pairedloader = DataLoader( MelPairedDataset( generate_files_path, groundtruth_path, self._stft, self.sampling_rate, self.fbin_mean, self.fbin_std, limit_num=limit_num, ), batch_size=1, sampler=None, num_workers=16, ) out = {} metric_lsd = self.calculate_lsd(pairedloader, same_name=same_name) out.update(metric_lsd) featuresdict_2 = self.get_featuresdict(resultloader) featuresdict_1 = self.get_featuresdict(outputloader) # if cfg.have_kl: metric_psnr_ssim = self.calculate_psnr_ssim(pairedloader, same_name=same_name) out.update(metric_psnr_ssim) metric_kl, kl_ref, paths_1 = calculate_kl( featuresdict_1, featuresdict_2, "logits", same_name ) out.update(metric_kl) metric_isc = calculate_isc( featuresdict_1, feat_layer_name="logits", splits=10, samples_shuffle=True, rng_seed=2020, ) out.update(metric_isc) metric_fid = calculate_fid( featuresdict_1, featuresdict_2, feat_layer_name="2048" ) out.update(metric_fid) # Gen, target fad_score = self.frechet.score(generate_files_path, groundtruth_path, limit_num=limit_num) out.update(fad_score) metric_kid = calculate_kid( featuresdict_1, featuresdict_2, feat_layer_name="2048", subsets=100, subset_size=1000, degree=3, gamma=None, coef0=1, rng_seed=2020, ) out.update(metric_kid) ''' print("\n".join((f"{k}: {v:.7f}" for k, v in out.items()))) print("\n") print(limit_num) print( f'KL_Sigmoid: {out.get("kullback_leibler_divergence_sigmoid", float("nan")):8.5f};', f'KL: {out.get("kullback_leibler_divergence_softmax", float("nan")):8.5f};', f'PSNR: {out.get("psnr", float("nan")):.5f}', f'SSIM: {out.get("ssim", float("nan")):.5f}', f'ISc: {out.get("inception_score_mean", float("nan")):8.5f} ({out.get("inception_score_std", float("nan")):5f});', f'KID: {out.get("kernel_inception_distance_mean", float("nan")):.5f}', f'({out.get("kernel_inception_distance_std", float("nan")):.5f})', f'FD: {out.get("frechet_distance", float("nan")):8.5f};', f'FAD: {out.get("frechet_audio_distance", float("nan")):.5f}', f'LSD: {out.get("lsd", float("nan")):.5f}', f'SSIM_STFT: {out.get("ssim_stft", float("nan")):.5f}', ) ''' result = { "frechet_distance": out.get("frechet_distance", float("nan")), "frechet_audio_distance": out.get("frechet_audio_distance", float("nan")), "kl_sigmoid": out.get( "kullback_leibler_divergence_sigmoid", float("nan") ), "kl_softmax": out.get( "kullback_leibler_divergence_softmax", float("nan") ), "lsd": out.get("lsd", float("nan")), "psnr": out.get("psnr", float("nan")), "ssim": out.get("ssim", float("nan")), "ssim_stft": out.get("ssim_stft", float("nan")), "is_mean": out.get("inception_score_mean", float("nan")), "is_std": out.get("inception_score_std", float("nan")), "kid_mean": out.get( "kernel_inception_distance_mean", float("nan") ), "kid_std": out.get( "kernel_inception_distance_std", float("nan") ), } result = {k: round(v, 4) for k, v in result.items()} json_path = generate_files_path + "_evaluation_results.json"
class EvaluationHelper: def __init__(self, sampling_rate, device, backbone="cnn14") -> None: self.device = device self.backbone = backbone self.sampling_rate = sampling_rate self.frechet = FrechetAudioDistance( use_pca=False, use_activation=False, verbose=False, ) self.lsd_metric = AudioMetrics(self.sampling_rate) self.frechet.model = self.frechet.model.to(device) features_list = ["2048", "logits"] if self.sampling_rate == 16000: self.mel_model = Cnn14( features_list=features_list, sample_rate=16000, window_size=512, hop_size=160, mel_bins=64, fmin=50, fmax=8000, classes_num=527, ) elif self.sampling_rate == 32000: self.mel_model = Cnn14( features_list=features_list, sample_rate=32000, window_size=1024, hop_size=320, mel_bins=64, fmin=50, fmax=14000, classes_num=527, ) else: raise ValueError( "We only support the evaluation on 16kHz and 32kHz sampling rate." ) if self.sampling_rate == 16000: self._stft = Audio.TacotronSTFT(512, 160, 512, 64, 16000, 50, 8000) elif self.sampling_rate == 32000: self._stft = Audio.TacotronSTFT(1024, 320, 1024, 64, 32000, 50, 14000) else: raise ValueError( "We only support the evaluation on 16kHz and 32kHz sampling rate." ) self.mel_model.eval() self.mel_model.to(self.device) self.fbin_mean, self.fbin_std = None, None def main( self, generate_files_path, groundtruth_path, limit_num=None, ): self.file_init_check(generate_files_path) self.file_init_check(groundtruth_path) same_name = self.get_filename_intersection_ratio( generate_files_path, groundtruth_path, limit_num=limit_num ) metrics = self.calculate_metrics(generate_files_path, groundtruth_path, same_name, limit_num) return metrics def file_init_check(self, dir): assert os.path.exists(dir), "The path does not exist %s" % dir assert len(os.listdir(dir)) > 1, "There is no files in %s" % dir def get_filename_intersection_ratio( self, dir1, dir2, threshold=0.99, limit_num=None ): self.datalist1 = [os.path.join(dir1, x) for x in os.listdir(dir1)] self.datalist1 = sorted(self.datalist1) self.datalist1 = [item for item in self.datalist1 if item.endswith(".wav")] self.datalist2 = [os.path.join(dir2, x) for x in os.listdir(dir2)] self.datalist2 = sorted(self.datalist2) self.datalist2 = [item for item in self.datalist2 if item.endswith(".wav")] data_dict1 = {os.path.basename(x): x for x in self.datalist1} data_dict2 = {os.path.basename(x): x for x in self.datalist2} keyset1 = set(data_dict1.keys()) keyset2 = set(data_dict2.keys()) intersect_keys = keyset1.intersection(keyset2) if ( len(intersect_keys) / len(keyset1) > threshold and len(intersect_keys) / len(keyset2) > threshold ): ''' print( "+Two path have %s intersection files out of total %s & %s files. Processing two folder with same_name=True" % (len(intersect_keys), len(keyset1), len(keyset2)) ) ''' return True else: ''' print( "-Two path have %s intersection files out of total %s & %s files. Processing two folder with same_name=False" % (len(intersect_keys), len(keyset1), len(keyset2)) ) ''' return False def calculate_lsd(self, pairedloader, same_name=True, time_offset=160 * 7): if same_name == False: return { "lsd": -1, "ssim_stft": -1, } # print("Calculating LSD using a time offset of %s ..." % time_offset) lsd_avg = [] ssim_stft_avg = [] for _, _, filename, (audio1, audio2) in tqdm(pairedloader, leave=False): audio1 = audio1.cpu().numpy()[0, 0] audio2 = audio2.cpu().numpy()[0, 0] # If you use HIFIGAN (verified on 2023-01-12), you need seven frames' offset audio1 = audio1[time_offset:] audio1 = audio1 - np.mean(audio1) audio2 = audio2 - np.mean(audio2) audio1 = audio1 / np.max(np.abs(audio1)) audio2 = audio2 / np.max(np.abs(audio2)) min_len = min(audio1.shape[0], audio2.shape[0]) audio1, audio2 = audio1[:min_len], audio2[:min_len] try: result = self.lsd(audio1, audio2) lsd_avg.append(result["lsd"]) ssim_stft_avg.append(result["ssim"]) except: continue return {"lsd": np.mean(lsd_avg), "ssim_stft": np.mean(ssim_stft_avg)} def lsd(self, audio1, audio2): result = self.lsd_metric.evaluation(audio1, audio2, None) return result def calculate_psnr_ssim(self, pairedloader, same_name=True): if same_name == False: return {"psnr": -1, "ssim": -1} psnr_avg = [] ssim_avg = [] for mel_gen, mel_target, filename, _ in tqdm(pairedloader, leave=False): mel_gen = mel_gen.cpu().numpy()[0] mel_target = mel_target.cpu().numpy()[0] psnrval = psnr(mel_gen, mel_target) if np.isinf(psnrval): print("Infinite value encountered in psnr %s " % filename) continue psnr_avg.append(psnrval) ssim_avg.append(ssim(mel_gen, mel_target)) return {"psnr": np.mean(psnr_avg), "ssim": np.mean(ssim_avg)} def calculate_metrics(self, generate_files_path, groundtruth_path, same_name, limit_num=None): # Generation, target torch.manual_seed(0) num_workers = 0 outputloader = DataLoader( WaveDataset( generate_files_path, self.sampling_rate, limit_num=limit_num, ), batch_size=1, sampler=None, num_workers=num_workers, ) resultloader = DataLoader( WaveDataset( groundtruth_path, self.sampling_rate, limit_num=limit_num, ), batch_size=1, sampler=None, num_workers=num_workers, ) pairedloader = DataLoader( MelPairedDataset( generate_files_path, groundtruth_path, self._stft, self.sampling_rate, self.fbin_mean, self.fbin_std, limit_num=limit_num, ), batch_size=1, sampler=None, num_workers=16, ) out = {} metric_lsd = self.calculate_lsd(pairedloader, same_name=same_name) out.update(metric_lsd) featuresdict_2 = self.get_featuresdict(resultloader) featuresdict_1 = self.get_featuresdict(outputloader) # if cfg.have_kl: metric_psnr_ssim = self.calculate_psnr_ssim(pairedloader, same_name=same_name) out.update(metric_psnr_ssim) metric_kl, kl_ref, paths_1 = calculate_kl( featuresdict_1, featuresdict_2, "logits", same_name ) out.update(metric_kl) metric_isc = calculate_isc( featuresdict_1, feat_layer_name="logits", splits=10, samples_shuffle=True, rng_seed=2020, ) out.update(metric_isc) metric_fid = calculate_fid( featuresdict_1, featuresdict_2, feat_layer_name="2048" ) out.update(metric_fid) # Gen, target fad_score = self.frechet.score(generate_files_path, groundtruth_path, limit_num=limit_num) out.update(fad_score) metric_kid = calculate_kid( featuresdict_1, featuresdict_2, feat_layer_name="2048", subsets=100, subset_size=1000, degree=3, gamma=None, coef0=1, rng_seed=2020, ) out.update(metric_kid) ''' print("\n".join((f"{k}: {v:.7f}" for k, v in out.items()))) print("\n") print(limit_num) print( f'KL_Sigmoid: {out.get("kullback_leibler_divergence_sigmoid", float("nan")):8.5f};', f'KL: {out.get("kullback_leibler_divergence_softmax", float("nan")):8.5f};', f'PSNR: {out.get("psnr", float("nan")):.5f}', f'SSIM: {out.get("ssim", float("nan")):.5f}', f'ISc: {out.get("inception_score_mean", float("nan")):8.5f} ({out.get("inception_score_std", float("nan")):5f});', f'KID: {out.get("kernel_inception_distance_mean", float("nan")):.5f}', f'({out.get("kernel_inception_distance_std", float("nan")):.5f})', f'FD: {out.get("frechet_distance", float("nan")):8.5f};', f'FAD: {out.get("frechet_audio_distance", float("nan")):.5f}', f'LSD: {out.get("lsd", float("nan")):.5f}', f'SSIM_STFT: {out.get("ssim_stft", float("nan")):.5f}', ) ''' result = { "frechet_distance": out.get("frechet_distance", float("nan")), "frechet_audio_distance": out.get("frechet_audio_distance", float("nan")), "kl_sigmoid": out.get( "kullback_leibler_divergence_sigmoid", float("nan") ), "kl_softmax": out.get( "kullback_leibler_divergence_softmax", float("nan") ), "lsd": out.get("lsd", float("nan")), "psnr": out.get("psnr", float("nan")), "ssim": out.get("ssim", float("nan")), "ssim_stft": out.get("ssim_stft", float("nan")), "is_mean": out.get("inception_score_mean", float("nan")), "is_std": out.get("inception_score_std", float("nan")), "kid_mean": out.get( "kernel_inception_distance_mean", float("nan") ), "kid_std": out.get( "kernel_inception_distance_std", float("nan") ), } result = {k: round(v, 4) for k, v in result.items()} json_path = generate_files_path + "_evaluation_results.json"
write_json(result, json_path)
11
2023-11-14 23:29:31+00:00
16k
BraveGroup/Drive-WM
src/diffusers/schedulers/scheduling_dpmsolver_multistep.py
[ { "identifier": "ConfigMixin", "path": "src/diffusers/configuration_utils.py", "snippet": "class ConfigMixin:\n r\"\"\"\n Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also\n provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.sa...
import math import numpy as np import torch from typing import List, Optional, Tuple, Union from ..configuration_utils import ConfigMixin, register_to_config from ..utils import deprecate from ..utils.torch_utils import randn_tensor from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
12,267
elif self.config.solver_type == "heun": x_t = ( (alpha_t / alpha_s0) * sample - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0 - 2.0 * (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise ) return x_t def multistep_dpm_solver_third_order_update( self, model_output_list: List[torch.FloatTensor], *args, sample: torch.FloatTensor = None, **kwargs, ) -> torch.FloatTensor: """ One step for the third-order multistep DPMSolver. Args: model_output_list (`List[torch.FloatTensor]`): The direct outputs from learned diffusion model at current and latter timesteps. sample (`torch.FloatTensor`): A current instance of a sample created by diffusion process. Returns: `torch.FloatTensor`: The sample tensor at the previous timestep. """ timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None) prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None) if sample is None: if len(args) > 2: sample = args[2] else: raise ValueError(" missing`sample` as a required keyward argument") if timestep_list is not None: deprecate( "timestep_list", "1.0.0", "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) if prev_timestep is not None: deprecate( "prev_timestep", "1.0.0", "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) sigma_t, sigma_s0, sigma_s1, sigma_s2 = ( self.sigmas[self.step_index + 1], self.sigmas[self.step_index], self.sigmas[self.step_index - 1], self.sigmas[self.step_index - 2], ) alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1) alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2) lambda_t = torch.log(alpha_t) - torch.log(sigma_t) lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1) lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2) m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3] h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2 r0, r1 = h_0 / h, h_1 / h D0 = m0 D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2) D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1) D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1) if self.config.algorithm_type == "dpmsolver++": # See https://arxiv.org/abs/2206.00927 for detailed derivations x_t = ( (sigma_t / sigma_s0) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1 - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2 ) elif self.config.algorithm_type == "dpmsolver": # See https://arxiv.org/abs/2206.00927 for detailed derivations x_t = ( (alpha_t / alpha_s0) * sample - (sigma_t * (torch.exp(h) - 1.0)) * D0 - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 - (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2 ) return x_t def _init_step_index(self, timestep): if isinstance(timestep, torch.Tensor): timestep = timestep.to(self.timesteps.device) index_candidates = (self.timesteps == timestep).nonzero() if len(index_candidates) == 0: step_index = len(self.timesteps) - 1 # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) elif len(index_candidates) > 1: step_index = index_candidates[1].item() else: step_index = index_candidates[0].item() self._step_index = step_index def step( self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor, generator=None, return_dict: bool = True,
# Copyright 2023 TSAIL Team and The HuggingFace Team. All rights reserved. # # 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. # DISCLAIMER: This file is strongly influenced by https://github.com/LuChengTHU/dpm-solver # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar def betas_for_alpha_bar( num_diffusion_timesteps, max_beta=0.999, alpha_transform_type="cosine", ): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up to that part of the diffusion process. Args: num_diffusion_timesteps (`int`): the number of betas to produce. max_beta (`float`): the maximum beta to use; use values lower than 1 to prevent singularities. alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar. Choose from `cosine` or `exp` Returns: betas (`np.ndarray`): the betas used by the scheduler to step the model outputs """ if alpha_transform_type == "cosine": def alpha_bar_fn(t): return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(t): return math.exp(t * -12.0) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}") betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta)) return torch.tensor(betas, dtype=torch.float32) class DPMSolverMultistepScheduler(SchedulerMixin, ConfigMixin): """ `DPMSolverMultistepScheduler` is a fast dedicated high-order solver for diffusion ODEs. This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic methods the library implements for all schedulers such as loading and saving. Args: num_train_timesteps (`int`, defaults to 1000): The number of diffusion steps to train the model. beta_start (`float`, defaults to 0.0001): The starting `beta` value of inference. beta_end (`float`, defaults to 0.02): The final `beta` value. beta_schedule (`str`, defaults to `"linear"`): The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from `linear`, `scaled_linear`, or `squaredcos_cap_v2`. trained_betas (`np.ndarray`, *optional*): Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`. solver_order (`int`, defaults to 2): The DPMSolver order which can be `1` or `2` or `3`. It is recommended to use `solver_order=2` for guided sampling, and `solver_order=3` for unconditional sampling. prediction_type (`str`, defaults to `epsilon`, *optional*): Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process), `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen Video](https://imagen.research.google/video/paper.pdf) paper). thresholding (`bool`, defaults to `False`): Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such as Stable Diffusion. dynamic_thresholding_ratio (`float`, defaults to 0.995): The ratio for the dynamic thresholding method. Valid only when `thresholding=True`. sample_max_value (`float`, defaults to 1.0): The threshold value for dynamic thresholding. Valid only when `thresholding=True` and `algorithm_type="dpmsolver++"`. algorithm_type (`str`, defaults to `dpmsolver++`): Algorithm type for the solver; can be `dpmsolver`, `dpmsolver++`, `sde-dpmsolver` or `sde-dpmsolver++`. The `dpmsolver` type implements the algorithms in the [DPMSolver](https://huggingface.co/papers/2206.00927) paper, and the `dpmsolver++` type implements the algorithms in the [DPMSolver++](https://huggingface.co/papers/2211.01095) paper. It is recommended to use `dpmsolver++` or `sde-dpmsolver++` with `solver_order=2` for guided sampling like in Stable Diffusion. solver_type (`str`, defaults to `midpoint`): Solver type for the second-order solver; can be `midpoint` or `heun`. The solver type slightly affects the sample quality, especially for a small number of steps. It is recommended to use `midpoint` solvers. lower_order_final (`bool`, defaults to `True`): Whether to use lower-order solvers in the final steps. Only valid for < 15 inference steps. This can stabilize the sampling of DPMSolver for steps < 15, especially for steps <= 10. euler_at_final (`bool`, defaults to `False`): Whether to use Euler's method in the final step. It is a trade-off between numerical stability and detail richness. This can stabilize the sampling of the SDE variant of DPMSolver for small number of inference steps, but sometimes may result in blurring. use_karras_sigmas (`bool`, *optional*, defaults to `False`): Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`, the sigmas are determined according to a sequence of noise levels {σi}. use_lu_lambdas (`bool`, *optional*, defaults to `False`): Whether to use the uniform-logSNR for step sizes proposed by Lu's DPM-Solver in the noise schedule during the sampling process. If `True`, the sigmas and time steps are determined according to a sequence of `lambda(t)`. lambda_min_clipped (`float`, defaults to `-inf`): Clipping threshold for the minimum value of `lambda(t)` for numerical stability. This is critical for the cosine (`squaredcos_cap_v2`) noise schedule. variance_type (`str`, *optional*): Set to "learned" or "learned_range" for diffusion models that predict variance. If set, the model's output contains the predicted Gaussian variance. timestep_spacing (`str`, defaults to `"linspace"`): The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information. steps_offset (`int`, defaults to 0): An offset added to the inference steps. You can use a combination of `offset=1` and `set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable Diffusion. """ _compatibles = [e.name for e in KarrasDiffusionSchedulers] order = 1 @register_to_config def __init__( self, num_train_timesteps: int = 1000, beta_start: float = 0.0001, beta_end: float = 0.02, beta_schedule: str = "linear", trained_betas: Optional[Union[np.ndarray, List[float]]] = None, solver_order: int = 2, prediction_type: str = "epsilon", thresholding: bool = False, dynamic_thresholding_ratio: float = 0.995, sample_max_value: float = 1.0, algorithm_type: str = "dpmsolver++", solver_type: str = "midpoint", lower_order_final: bool = True, euler_at_final: bool = False, use_karras_sigmas: Optional[bool] = False, use_lu_lambdas: Optional[bool] = False, lambda_min_clipped: float = -float("inf"), variance_type: Optional[str] = None, timestep_spacing: str = "linspace", steps_offset: int = 0, ): if trained_betas is not None: self.betas = torch.tensor(trained_betas, dtype=torch.float32) elif beta_schedule == "linear": self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2 elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule self.betas = betas_for_alpha_bar(num_train_timesteps) else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}") self.alphas = 1.0 - self.betas self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) # Currently we only support VP-type noise schedule self.alpha_t = torch.sqrt(self.alphas_cumprod) self.sigma_t = torch.sqrt(1 - self.alphas_cumprod) self.lambda_t = torch.log(self.alpha_t) - torch.log(self.sigma_t) # standard deviation of the initial noise distribution self.init_noise_sigma = 1.0 # settings for DPM-Solver if algorithm_type not in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]: if algorithm_type == "deis": self.register_to_config(algorithm_type="dpmsolver++") else: raise NotImplementedError(f"{algorithm_type} does is not implemented for {self.__class__}") if solver_type not in ["midpoint", "heun"]: if solver_type in ["logrho", "bh1", "bh2"]: self.register_to_config(solver_type="midpoint") else: raise NotImplementedError(f"{solver_type} does is not implemented for {self.__class__}") # setable values self.num_inference_steps = None timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=np.float32)[::-1].copy() self.timesteps = torch.from_numpy(timesteps) self.model_outputs = [None] * solver_order self.lower_order_nums = 0 self._step_index = None @property def step_index(self): """ The index counter for current timestep. It will increae 1 after each scheduler step. """ return self._step_index def set_timesteps(self, num_inference_steps: int = None, device: Union[str, torch.device] = None): """ Sets the discrete timesteps used for the diffusion chain (to be run before inference). Args: num_inference_steps (`int`): The number of diffusion steps used when generating samples with a pre-trained model. device (`str` or `torch.device`, *optional*): The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. """ # Clipping the minimum of all lambda(t) for numerical stability. # This is critical for cosine (squaredcos_cap_v2) noise schedule. clipped_idx = torch.searchsorted(torch.flip(self.lambda_t, [0]), self.config.lambda_min_clipped) last_timestep = ((self.config.num_train_timesteps - clipped_idx).numpy()).item() # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": timesteps = ( np.linspace(0, last_timestep - 1, num_inference_steps + 1).round()[::-1][:-1].copy().astype(np.int64) ) elif self.config.timestep_spacing == "leading": step_ratio = last_timestep // (num_inference_steps + 1) # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 timesteps = (np.arange(0, num_inference_steps + 1) * step_ratio).round()[::-1][:-1].copy().astype(np.int64) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": step_ratio = self.config.num_train_timesteps / num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 timesteps = np.arange(last_timestep, 0, -step_ratio).round().copy().astype(np.int64) timesteps -= 1 else: raise ValueError( f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." ) sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5) log_sigmas = np.log(sigmas) if self.config.use_karras_sigmas: sigmas = np.flip(sigmas).copy() sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps) timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round() sigmas = np.concatenate([sigmas, sigmas[-1:]]).astype(np.float32) elif self.config.use_lu_lambdas: lambdas = np.flip(log_sigmas.copy()) lambdas = self._convert_to_lu(in_lambdas=lambdas, num_inference_steps=num_inference_steps) sigmas = np.exp(lambdas) timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round() sigmas = np.concatenate([sigmas, sigmas[-1:]]).astype(np.float32) else: sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas) sigma_last = ((1 - self.alphas_cumprod[0]) / self.alphas_cumprod[0]) ** 0.5 sigmas = np.concatenate([sigmas, [sigma_last]]).astype(np.float32) self.sigmas = torch.from_numpy(sigmas) self.timesteps = torch.from_numpy(timesteps).to(device=device, dtype=torch.int64) self.num_inference_steps = len(timesteps) self.model_outputs = [ None, ] * self.config.solver_order self.lower_order_nums = 0 # add an index counter for schedulers that allow duplicated timesteps self._step_index = None # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample def _threshold_sample(self, sample: torch.FloatTensor) -> torch.FloatTensor: """ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing pixels from saturation at each step. We find that dynamic thresholding results in significantly better photorealism as well as better image-text alignment, especially when using very large guidance weights." https://arxiv.org/abs/2205.11487 """ dtype = sample.dtype batch_size, channels, *remaining_dims = sample.shape if dtype not in (torch.float32, torch.float64): sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half # Flatten sample for doing quantile calculation along each image sample = sample.reshape(batch_size, channels * np.prod(remaining_dims)) abs_sample = sample.abs() # "a certain percentile absolute pixel value" s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1) s = torch.clamp( s, min=1, max=self.config.sample_max_value ) # When clamped to min=1, equivalent to standard clipping to [-1, 1] s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0 sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s" sample = sample.reshape(batch_size, channels, *remaining_dims) sample = sample.to(dtype) return sample # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._sigma_to_t def _sigma_to_t(self, sigma, log_sigmas): # get log sigma log_sigma = np.log(np.maximum(sigma, 1e-10)) # get distribution dists = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2) high_idx = low_idx + 1 low = log_sigmas[low_idx] high = log_sigmas[high_idx] # interpolate sigmas w = (low - log_sigma) / (low - high) w = np.clip(w, 0, 1) # transform interpolation to time range t = (1 - w) * low_idx + w * high_idx t = t.reshape(sigma.shape) return t def _sigma_to_alpha_sigma_t(self, sigma): alpha_t = 1 / ((sigma**2 + 1) ** 0.5) sigma_t = sigma * alpha_t return alpha_t, sigma_t # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_karras def _convert_to_karras(self, in_sigmas: torch.FloatTensor, num_inference_steps) -> torch.FloatTensor: """Constructs the noise schedule of Karras et al. (2022).""" sigma_min: float = in_sigmas[-1].item() sigma_max: float = in_sigmas[0].item() rho = 7.0 # 7.0 is the value used in the paper ramp = np.linspace(0, 1, num_inference_steps) min_inv_rho = sigma_min ** (1 / rho) max_inv_rho = sigma_max ** (1 / rho) sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas def _convert_to_lu(self, in_lambdas: torch.FloatTensor, num_inference_steps) -> torch.FloatTensor: """Constructs the noise schedule of Lu et al. (2022).""" lambda_min: float = in_lambdas[-1].item() lambda_max: float = in_lambdas[0].item() rho = 1.0 # 1.0 is the value used in the paper ramp = np.linspace(0, 1, num_inference_steps) min_inv_rho = lambda_min ** (1 / rho) max_inv_rho = lambda_max ** (1 / rho) lambdas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return lambdas def convert_model_output( self, model_output: torch.FloatTensor, *args, sample: torch.FloatTensor = None, **kwargs, ) -> torch.FloatTensor: """ Convert the model output to the corresponding type the DPMSolver/DPMSolver++ algorithm needs. DPM-Solver is designed to discretize an integral of the noise prediction model, and DPM-Solver++ is designed to discretize an integral of the data prediction model. <Tip> The algorithm and model type are decoupled. You can use either DPMSolver or DPMSolver++ for both noise prediction and data prediction models. </Tip> Args: model_output (`torch.FloatTensor`): The direct output from the learned diffusion model. sample (`torch.FloatTensor`): A current instance of a sample created by the diffusion process. Returns: `torch.FloatTensor`: The converted model output. """ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None) if sample is None: if len(args) > 1: sample = args[1] else: raise ValueError("missing `sample` as a required keyward argument") if timestep is not None: deprecate( "timesteps", "1.0.0", "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) # DPM-Solver++ needs to solve an integral of the data prediction model. if self.config.algorithm_type in ["dpmsolver++", "sde-dpmsolver++"]: if self.config.prediction_type == "epsilon": # DPM-Solver and DPM-Solver++ only need the "mean" output. if self.config.variance_type in ["learned", "learned_range"]: model_output = model_output[:, :3] sigma = self.sigmas[self.step_index] alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) x0_pred = (sample - sigma_t * model_output) / alpha_t elif self.config.prediction_type == "sample": x0_pred = model_output elif self.config.prediction_type == "v_prediction": sigma = self.sigmas[self.step_index] alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) x0_pred = alpha_t * sample - sigma_t * model_output else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" " `v_prediction` for the DPMSolverMultistepScheduler." ) if self.config.thresholding: x0_pred = self._threshold_sample(x0_pred) return x0_pred # DPM-Solver needs to solve an integral of the noise prediction model. elif self.config.algorithm_type in ["dpmsolver", "sde-dpmsolver"]: if self.config.prediction_type == "epsilon": # DPM-Solver and DPM-Solver++ only need the "mean" output. if self.config.variance_type in ["learned", "learned_range"]: epsilon = model_output[:, :3] else: epsilon = model_output elif self.config.prediction_type == "sample": sigma = self.sigmas[self.step_index] alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) epsilon = (sample - alpha_t * model_output) / sigma_t elif self.config.prediction_type == "v_prediction": sigma = self.sigmas[self.step_index] alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) epsilon = alpha_t * model_output + sigma_t * sample else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" " `v_prediction` for the DPMSolverMultistepScheduler." ) if self.config.thresholding: sigma = self.sigmas[self.step_index] alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma) x0_pred = (sample - sigma_t * epsilon) / alpha_t x0_pred = self._threshold_sample(x0_pred) epsilon = (sample - alpha_t * x0_pred) / sigma_t return epsilon def dpm_solver_first_order_update( self, model_output: torch.FloatTensor, *args, sample: torch.FloatTensor = None, noise: Optional[torch.FloatTensor] = None, **kwargs, ) -> torch.FloatTensor: """ One step for the first-order DPMSolver (equivalent to DDIM). Args: model_output (`torch.FloatTensor`): The direct output from the learned diffusion model. sample (`torch.FloatTensor`): A current instance of a sample created by the diffusion process. Returns: `torch.FloatTensor`: The sample tensor at the previous timestep. """ timestep = args[0] if len(args) > 0 else kwargs.pop("timestep", None) prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None) if sample is None: if len(args) > 2: sample = args[2] else: raise ValueError(" missing `sample` as a required keyward argument") if timestep is not None: deprecate( "timesteps", "1.0.0", "Passing `timesteps` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) if prev_timestep is not None: deprecate( "prev_timestep", "1.0.0", "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) sigma_t, sigma_s = self.sigmas[self.step_index + 1], self.sigmas[self.step_index] alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) alpha_s, sigma_s = self._sigma_to_alpha_sigma_t(sigma_s) lambda_t = torch.log(alpha_t) - torch.log(sigma_t) lambda_s = torch.log(alpha_s) - torch.log(sigma_s) h = lambda_t - lambda_s if self.config.algorithm_type == "dpmsolver++": x_t = (sigma_t / sigma_s) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * model_output elif self.config.algorithm_type == "dpmsolver": x_t = (alpha_t / alpha_s) * sample - (sigma_t * (torch.exp(h) - 1.0)) * model_output elif self.config.algorithm_type == "sde-dpmsolver++": assert noise is not None x_t = ( (sigma_t / sigma_s * torch.exp(-h)) * sample + (alpha_t * (1 - torch.exp(-2.0 * h))) * model_output + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise ) elif self.config.algorithm_type == "sde-dpmsolver": assert noise is not None x_t = ( (alpha_t / alpha_s) * sample - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * model_output + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise ) return x_t def multistep_dpm_solver_second_order_update( self, model_output_list: List[torch.FloatTensor], *args, sample: torch.FloatTensor = None, noise: Optional[torch.FloatTensor] = None, **kwargs, ) -> torch.FloatTensor: """ One step for the second-order multistep DPMSolver. Args: model_output_list (`List[torch.FloatTensor]`): The direct outputs from learned diffusion model at current and latter timesteps. sample (`torch.FloatTensor`): A current instance of a sample created by the diffusion process. Returns: `torch.FloatTensor`: The sample tensor at the previous timestep. """ timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None) prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None) if sample is None: if len(args) > 2: sample = args[2] else: raise ValueError(" missing `sample` as a required keyward argument") if timestep_list is not None: deprecate( "timestep_list", "1.0.0", "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) if prev_timestep is not None: deprecate( "prev_timestep", "1.0.0", "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) sigma_t, sigma_s0, sigma_s1 = ( self.sigmas[self.step_index + 1], self.sigmas[self.step_index], self.sigmas[self.step_index - 1], ) alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1) lambda_t = torch.log(alpha_t) - torch.log(sigma_t) lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1) m0, m1 = model_output_list[-1], model_output_list[-2] h, h_0 = lambda_t - lambda_s0, lambda_s0 - lambda_s1 r0 = h_0 / h D0, D1 = m0, (1.0 / r0) * (m0 - m1) if self.config.algorithm_type == "dpmsolver++": # See https://arxiv.org/abs/2211.01095 for detailed derivations if self.config.solver_type == "midpoint": x_t = ( (sigma_t / sigma_s0) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * D0 - 0.5 * (alpha_t * (torch.exp(-h) - 1.0)) * D1 ) elif self.config.solver_type == "heun": x_t = ( (sigma_t / sigma_s0) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1 ) elif self.config.algorithm_type == "dpmsolver": # See https://arxiv.org/abs/2206.00927 for detailed derivations if self.config.solver_type == "midpoint": x_t = ( (alpha_t / alpha_s0) * sample - (sigma_t * (torch.exp(h) - 1.0)) * D0 - 0.5 * (sigma_t * (torch.exp(h) - 1.0)) * D1 ) elif self.config.solver_type == "heun": x_t = ( (alpha_t / alpha_s0) * sample - (sigma_t * (torch.exp(h) - 1.0)) * D0 - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 ) elif self.config.algorithm_type == "sde-dpmsolver++": assert noise is not None if self.config.solver_type == "midpoint": x_t = ( (sigma_t / sigma_s0 * torch.exp(-h)) * sample + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0 + 0.5 * (alpha_t * (1 - torch.exp(-2.0 * h))) * D1 + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise ) elif self.config.solver_type == "heun": x_t = ( (sigma_t / sigma_s0 * torch.exp(-h)) * sample + (alpha_t * (1 - torch.exp(-2.0 * h))) * D0 + (alpha_t * ((1.0 - torch.exp(-2.0 * h)) / (-2.0 * h) + 1.0)) * D1 + sigma_t * torch.sqrt(1.0 - torch.exp(-2 * h)) * noise ) elif self.config.algorithm_type == "sde-dpmsolver": assert noise is not None if self.config.solver_type == "midpoint": x_t = ( (alpha_t / alpha_s0) * sample - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0 - (sigma_t * (torch.exp(h) - 1.0)) * D1 + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise ) elif self.config.solver_type == "heun": x_t = ( (alpha_t / alpha_s0) * sample - 2.0 * (sigma_t * (torch.exp(h) - 1.0)) * D0 - 2.0 * (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 + sigma_t * torch.sqrt(torch.exp(2 * h) - 1.0) * noise ) return x_t def multistep_dpm_solver_third_order_update( self, model_output_list: List[torch.FloatTensor], *args, sample: torch.FloatTensor = None, **kwargs, ) -> torch.FloatTensor: """ One step for the third-order multistep DPMSolver. Args: model_output_list (`List[torch.FloatTensor]`): The direct outputs from learned diffusion model at current and latter timesteps. sample (`torch.FloatTensor`): A current instance of a sample created by diffusion process. Returns: `torch.FloatTensor`: The sample tensor at the previous timestep. """ timestep_list = args[0] if len(args) > 0 else kwargs.pop("timestep_list", None) prev_timestep = args[1] if len(args) > 1 else kwargs.pop("prev_timestep", None) if sample is None: if len(args) > 2: sample = args[2] else: raise ValueError(" missing`sample` as a required keyward argument") if timestep_list is not None: deprecate( "timestep_list", "1.0.0", "Passing `timestep_list` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) if prev_timestep is not None: deprecate( "prev_timestep", "1.0.0", "Passing `prev_timestep` is deprecated and has no effect as model output conversion is now handled via an internal counter `self.step_index`", ) sigma_t, sigma_s0, sigma_s1, sigma_s2 = ( self.sigmas[self.step_index + 1], self.sigmas[self.step_index], self.sigmas[self.step_index - 1], self.sigmas[self.step_index - 2], ) alpha_t, sigma_t = self._sigma_to_alpha_sigma_t(sigma_t) alpha_s0, sigma_s0 = self._sigma_to_alpha_sigma_t(sigma_s0) alpha_s1, sigma_s1 = self._sigma_to_alpha_sigma_t(sigma_s1) alpha_s2, sigma_s2 = self._sigma_to_alpha_sigma_t(sigma_s2) lambda_t = torch.log(alpha_t) - torch.log(sigma_t) lambda_s0 = torch.log(alpha_s0) - torch.log(sigma_s0) lambda_s1 = torch.log(alpha_s1) - torch.log(sigma_s1) lambda_s2 = torch.log(alpha_s2) - torch.log(sigma_s2) m0, m1, m2 = model_output_list[-1], model_output_list[-2], model_output_list[-3] h, h_0, h_1 = lambda_t - lambda_s0, lambda_s0 - lambda_s1, lambda_s1 - lambda_s2 r0, r1 = h_0 / h, h_1 / h D0 = m0 D1_0, D1_1 = (1.0 / r0) * (m0 - m1), (1.0 / r1) * (m1 - m2) D1 = D1_0 + (r0 / (r0 + r1)) * (D1_0 - D1_1) D2 = (1.0 / (r0 + r1)) * (D1_0 - D1_1) if self.config.algorithm_type == "dpmsolver++": # See https://arxiv.org/abs/2206.00927 for detailed derivations x_t = ( (sigma_t / sigma_s0) * sample - (alpha_t * (torch.exp(-h) - 1.0)) * D0 + (alpha_t * ((torch.exp(-h) - 1.0) / h + 1.0)) * D1 - (alpha_t * ((torch.exp(-h) - 1.0 + h) / h**2 - 0.5)) * D2 ) elif self.config.algorithm_type == "dpmsolver": # See https://arxiv.org/abs/2206.00927 for detailed derivations x_t = ( (alpha_t / alpha_s0) * sample - (sigma_t * (torch.exp(h) - 1.0)) * D0 - (sigma_t * ((torch.exp(h) - 1.0) / h - 1.0)) * D1 - (sigma_t * ((torch.exp(h) - 1.0 - h) / h**2 - 0.5)) * D2 ) return x_t def _init_step_index(self, timestep): if isinstance(timestep, torch.Tensor): timestep = timestep.to(self.timesteps.device) index_candidates = (self.timesteps == timestep).nonzero() if len(index_candidates) == 0: step_index = len(self.timesteps) - 1 # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) elif len(index_candidates) > 1: step_index = index_candidates[1].item() else: step_index = index_candidates[0].item() self._step_index = step_index def step( self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor, generator=None, return_dict: bool = True,
) -> Union[SchedulerOutput, Tuple]:
6
2023-11-18 01:40:55+00:00
16k
BAAI-DCAI/SegVol
inference_demo.py
[ { "identifier": "sam_model_registry", "path": "segment_anything_volumetric/build_sam.py", "snippet": "def build_sam_vit_3d(args, checkpoint=None):\ndef _build_sam(\n image_encoder_type,\n embed_dim,\n patch_size,\n checkpoint,\n image_size,\n):" }, { "identifier": "SegVol", "p...
import argparse import os import torch import torch.nn.functional as F import json import monai.transforms as transforms from segment_anything_volumetric import sam_model_registry from network.model import SegVol from data_process.demo_data_process import process_ct_gt from utils.monai_inferers_utils import sliding_window_inference, generate_box, select_points, build_binary_cube, build_binary_points, logits2roi_coor from utils.visualize import draw_result
10,965
parser.add_argument("--resume", type = str, default = '') parser.add_argument("-infer_overlap", default=0.5, type=float, help="sliding window inference overlap") parser.add_argument("-spatial_size", default=(32, 256, 256), type=tuple) parser.add_argument("-patch_size", default=(4, 16, 16), type=tuple) parser.add_argument('-work_dir', type=str, default='./work_dir') ### demo parser.add_argument('--demo_config', type=str, required=True) parser.add_argument("--clip_ckpt", type = str, default = './config/clip') args = parser.parse_args() return args def dice_score(preds, labels): # on GPU assert preds.shape[0] == labels.shape[0], "predict & target batch size don't match\n" + str(preds.shape) + str(labels.shape) predict = preds.view(1, -1) target = labels.view(1, -1) if target.shape[1] < 1e8: predict = predict.cuda() target = target.cuda() predict = torch.sigmoid(predict) predict = torch.where(predict > 0.5, 1., 0.) tp = torch.sum(torch.mul(predict, target)) den = torch.sum(predict) + torch.sum(target) + 1 dice = 2 * tp / den if target.shape[1] < 1e8: predict = predict.cpu() target = target.cpu() return dice def zoom_in_zoom_out(args, segvol_model, image, image_resize, gt3D, gt3D_resize, categories=None): logits_labels_record = {} image_single_resize = image_resize image_single = image[0,0] ori_shape = image_single.shape for item_idx in range(len(categories)): # get label to generate prompts label_single = gt3D[0][item_idx] label_single_resize = gt3D_resize[0][item_idx] # skip meaningless categories if torch.sum(label_single) == 0: print('No object, skip') continue # generate prompts text_single = categories[item_idx] if args.use_text_prompt else None if categories is not None: print(f'inference |{categories[item_idx]}| target...') points_single = None box_single = None if args.use_point_prompt: point, point_label = select_points(label_single_resize, num_positive_extra=3, num_negative_extra=3) points_single = (point.unsqueeze(0).float().cuda(), point_label.unsqueeze(0).float().cuda()) binary_points_resize = build_binary_points(point, point_label, label_single_resize.shape) if args.use_box_prompt: box_single = generate_box(label_single_resize).unsqueeze(0).float().cuda() binary_cube_resize = build_binary_cube(box_single, binary_cube_shape=label_single_resize.shape) #################### # zoom-out inference: print('--- zoom out inference ---') print(f'use text-prompt [{text_single!=None}], use box-prompt [{box_single!=None}], use point-prompt [{points_single!=None}]') with torch.no_grad(): logits_global_single = segvol_model(image_single_resize.cuda(), text=text_single, boxes=box_single, points=points_single) # resize back global logits logits_global_single = F.interpolate( logits_global_single.cpu(), size=ori_shape, mode='nearest')[0][0] # build prompt reflection for zoom-in if args.use_point_prompt: binary_points = F.interpolate( binary_points_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] if args.use_box_prompt: binary_cube = F.interpolate( binary_cube_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] zoom_out_dice = dice_score(logits_global_single.squeeze(), label_single.squeeze()) logits_labels_record[categories[item_idx]] = ( zoom_out_dice, image_single, points_single, box_single, logits_global_single, label_single) print(f'zoom out inference done with zoom_out_dice: {zoom_out_dice:.4f}') if not args.use_zoom_in: continue #################### # zoom-in inference: min_d, min_h, min_w, max_d, max_h, max_w = logits2roi_coor(args.spatial_size, logits_global_single) if min_d is None: print('Fail to detect foreground!') continue # Crop roi image_single_cropped = image_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1].unsqueeze(0).unsqueeze(0) global_preds = (torch.sigmoid(logits_global_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1])>0.5).long() assert not (args.use_box_prompt and args.use_point_prompt) prompt_reflection = None if args.use_box_prompt: binary_cube_cropped = binary_cube[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_cube_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) if args.use_point_prompt: binary_points_cropped = binary_points[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_points_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) ## inference with torch.no_grad():
def set_parse(): # %% set up parser parser = argparse.ArgumentParser() parser.add_argument("--test_mode", default=True, type=bool) parser.add_argument("--resume", type = str, default = '') parser.add_argument("-infer_overlap", default=0.5, type=float, help="sliding window inference overlap") parser.add_argument("-spatial_size", default=(32, 256, 256), type=tuple) parser.add_argument("-patch_size", default=(4, 16, 16), type=tuple) parser.add_argument('-work_dir', type=str, default='./work_dir') ### demo parser.add_argument('--demo_config', type=str, required=True) parser.add_argument("--clip_ckpt", type = str, default = './config/clip') args = parser.parse_args() return args def dice_score(preds, labels): # on GPU assert preds.shape[0] == labels.shape[0], "predict & target batch size don't match\n" + str(preds.shape) + str(labels.shape) predict = preds.view(1, -1) target = labels.view(1, -1) if target.shape[1] < 1e8: predict = predict.cuda() target = target.cuda() predict = torch.sigmoid(predict) predict = torch.where(predict > 0.5, 1., 0.) tp = torch.sum(torch.mul(predict, target)) den = torch.sum(predict) + torch.sum(target) + 1 dice = 2 * tp / den if target.shape[1] < 1e8: predict = predict.cpu() target = target.cpu() return dice def zoom_in_zoom_out(args, segvol_model, image, image_resize, gt3D, gt3D_resize, categories=None): logits_labels_record = {} image_single_resize = image_resize image_single = image[0,0] ori_shape = image_single.shape for item_idx in range(len(categories)): # get label to generate prompts label_single = gt3D[0][item_idx] label_single_resize = gt3D_resize[0][item_idx] # skip meaningless categories if torch.sum(label_single) == 0: print('No object, skip') continue # generate prompts text_single = categories[item_idx] if args.use_text_prompt else None if categories is not None: print(f'inference |{categories[item_idx]}| target...') points_single = None box_single = None if args.use_point_prompt: point, point_label = select_points(label_single_resize, num_positive_extra=3, num_negative_extra=3) points_single = (point.unsqueeze(0).float().cuda(), point_label.unsqueeze(0).float().cuda()) binary_points_resize = build_binary_points(point, point_label, label_single_resize.shape) if args.use_box_prompt: box_single = generate_box(label_single_resize).unsqueeze(0).float().cuda() binary_cube_resize = build_binary_cube(box_single, binary_cube_shape=label_single_resize.shape) #################### # zoom-out inference: print('--- zoom out inference ---') print(f'use text-prompt [{text_single!=None}], use box-prompt [{box_single!=None}], use point-prompt [{points_single!=None}]') with torch.no_grad(): logits_global_single = segvol_model(image_single_resize.cuda(), text=text_single, boxes=box_single, points=points_single) # resize back global logits logits_global_single = F.interpolate( logits_global_single.cpu(), size=ori_shape, mode='nearest')[0][0] # build prompt reflection for zoom-in if args.use_point_prompt: binary_points = F.interpolate( binary_points_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] if args.use_box_prompt: binary_cube = F.interpolate( binary_cube_resize.unsqueeze(0).unsqueeze(0).float(), size=ori_shape, mode='nearest')[0][0] zoom_out_dice = dice_score(logits_global_single.squeeze(), label_single.squeeze()) logits_labels_record[categories[item_idx]] = ( zoom_out_dice, image_single, points_single, box_single, logits_global_single, label_single) print(f'zoom out inference done with zoom_out_dice: {zoom_out_dice:.4f}') if not args.use_zoom_in: continue #################### # zoom-in inference: min_d, min_h, min_w, max_d, max_h, max_w = logits2roi_coor(args.spatial_size, logits_global_single) if min_d is None: print('Fail to detect foreground!') continue # Crop roi image_single_cropped = image_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1].unsqueeze(0).unsqueeze(0) global_preds = (torch.sigmoid(logits_global_single[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1])>0.5).long() assert not (args.use_box_prompt and args.use_point_prompt) prompt_reflection = None if args.use_box_prompt: binary_cube_cropped = binary_cube[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_cube_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) if args.use_point_prompt: binary_points_cropped = binary_points[min_d:max_d+1, min_h:max_h+1, min_w:max_w+1] prompt_reflection = ( binary_points_cropped.unsqueeze(0).unsqueeze(0), global_preds.unsqueeze(0).unsqueeze(0) ) ## inference with torch.no_grad():
logits_single_cropped = sliding_window_inference(
3
2023-11-10 08:25:37+00:00
16k
theroyallab/tabbyAPI
main.py
[ { "identifier": "convert_args_to_dict", "path": "args.py", "snippet": "def convert_args_to_dict(args: argparse.Namespace, parser: argparse.ArgumentParser):\n \"\"\"Broad conversion of surface level arg groups to dictionaries\"\"\"\n\n arg_groups = {}\n for group in parser._action_groups:\n ...
import pathlib import uvicorn import gen_logging from asyncio import CancelledError from typing import Optional from uuid import uuid4 from jinja2 import TemplateError from fastapi import FastAPI, Depends, HTTPException, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import StreamingResponse from functools import partial from progress.bar import IncrementalBar from args import convert_args_to_dict, init_argparser from auth import check_admin_key, check_api_key, load_auth_keys from config import ( override_config_from_args, read_config_from_file, get_gen_logging_config, get_model_config, get_draft_model_config, get_lora_config, get_network_config, ) from generators import call_with_semaphore, generate_with_semaphore from model import ModelContainer from OAI.types.completion import CompletionRequest from OAI.types.chat_completion import ChatCompletionRequest from OAI.types.lora import LoraCard, LoraList, LoraLoadRequest, LoraLoadResponse from OAI.types.model import ( ModelCard, ModelLoadRequest, ModelLoadResponse, ModelCardParameters, ) from OAI.types.template import TemplateList from OAI.types.token import ( TokenEncodeRequest, TokenEncodeResponse, TokenDecodeRequest, TokenDecodeResponse, ) from OAI.utils_oai import ( create_completion_response, get_model_list, get_lora_list, create_chat_completion_response, create_chat_completion_stream_chunk, ) from templating import get_all_templates, get_prompt_from_template from utils import get_generator_error, get_sse_packet, load_progress, unwrap from logger import init_logger
14,159
yield get_sse_packet("[DONE]") except CancelledError: logger.error("Completion request cancelled by user.") except Exception as exc: yield get_generator_error(str(exc)) return StreamingResponse( generate_with_semaphore(generator), media_type="text/event-stream" ) response_text, prompt_tokens, completion_tokens = await call_with_semaphore( partial(MODEL_CONTAINER.generate, data.prompt, **data.to_gen_params()) ) response = create_completion_response( response_text, prompt_tokens, completion_tokens, model_path.name ) return response # Chat completions endpoint @app.post( "/v1/chat/completions", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def generate_chat_completion(request: Request, data: ChatCompletionRequest): """Generates a chat completion from a prompt.""" if MODEL_CONTAINER.prompt_template is None: raise HTTPException( 422, "This endpoint is disabled because a prompt template is not set.", ) model_path = MODEL_CONTAINER.get_model_path() if isinstance(data.messages, str): prompt = data.messages else: try: special_tokens_dict = MODEL_CONTAINER.get_special_tokens( unwrap(data.add_bos_token, True), unwrap(data.ban_eos_token, False), ) prompt = get_prompt_from_template( data.messages, MODEL_CONTAINER.prompt_template, data.add_generation_prompt, special_tokens_dict, ) except KeyError as exc: raise HTTPException( 400, "Could not find a Conversation from prompt template " f"'{MODEL_CONTAINER.prompt_template.name}'. " "Check your spelling?", ) from exc except TemplateError as exc: raise HTTPException( 400, f"TemplateError: {str(exc)}", ) from exc if data.stream: const_id = f"chatcmpl-{uuid4().hex}" async def generator(): """Generator for the generation process.""" try: new_generation = MODEL_CONTAINER.generate_gen( prompt, **data.to_gen_params() ) for part, _, _ in new_generation: if await request.is_disconnected(): break response = create_chat_completion_stream_chunk( const_id, part, model_path.name ) yield get_sse_packet(response.model_dump_json()) # Yield a finish response on successful generation finish_response = create_chat_completion_stream_chunk( const_id, finish_reason="stop" ) yield get_sse_packet(finish_response.model_dump_json()) except CancelledError: logger.error("Chat completion cancelled by user.") except Exception as exc: yield get_generator_error(str(exc)) return StreamingResponse( generate_with_semaphore(generator), media_type="text/event-stream" ) response_text, prompt_tokens, completion_tokens = await call_with_semaphore( partial(MODEL_CONTAINER.generate, prompt, **data.to_gen_params()) ) response = create_chat_completion_response( response_text, prompt_tokens, completion_tokens, model_path.name ) return response def entrypoint(args: Optional[dict] = None): """Entry function for program startup""" global MODEL_CONTAINER # Load from YAML config read_config_from_file(pathlib.Path("config.yml")) # Parse and override config from args if args is None: parser = init_argparser() args = convert_args_to_dict(parser.parse_args(), parser)
"""The main tabbyAPI module. Contains the FastAPI server and endpoints.""" logger = init_logger(__name__) app = FastAPI( title="TabbyAPI", summary="An OAI compatible exllamav2 API that's both lightweight and fast", description=( "This docs page is not meant to send requests! Please use a service " "like Postman or a frontend UI." ), ) # Globally scoped variables. Undefined until initalized in main MODEL_CONTAINER: Optional[ModelContainer] = None def _check_model_container(): if MODEL_CONTAINER is None or MODEL_CONTAINER.model is None: raise HTTPException(400, "No models are loaded.") # ALlow CORS requests app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Model list endpoint @app.get("/v1/models", dependencies=[Depends(check_api_key)]) @app.get("/v1/model/list", dependencies=[Depends(check_api_key)]) async def list_models(): """Lists all models in the model directory.""" model_config = get_model_config() model_dir = unwrap(model_config.get("model_dir"), "models") model_path = pathlib.Path(model_dir) draft_model_dir = get_draft_model_config().get("draft_model_dir") models = get_model_list(model_path.resolve(), draft_model_dir) if unwrap(model_config.get("use_dummy_models"), False): models.data.insert(0, ModelCard(id="gpt-3.5-turbo")) return models # Currently loaded model endpoint @app.get( "/v1/model", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) @app.get( "/v1/internal/model/info", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def get_current_model(): """Returns the currently loaded model.""" model_name = MODEL_CONTAINER.get_model_path().name prompt_template = MODEL_CONTAINER.prompt_template model_card = ModelCard( id=model_name, parameters=ModelCardParameters( rope_scale=MODEL_CONTAINER.config.scale_pos_emb, rope_alpha=MODEL_CONTAINER.config.scale_alpha_value, max_seq_len=MODEL_CONTAINER.config.max_seq_len, cache_mode="FP8" if MODEL_CONTAINER.cache_fp8 else "FP16", prompt_template=prompt_template.name if prompt_template else None, num_experts_per_token=MODEL_CONTAINER.config.num_experts_per_token, use_cfg=MODEL_CONTAINER.use_cfg, ), logging=gen_logging.PREFERENCES, ) if MODEL_CONTAINER.draft_config: draft_card = ModelCard( id=MODEL_CONTAINER.get_model_path(True).name, parameters=ModelCardParameters( rope_scale=MODEL_CONTAINER.draft_config.scale_pos_emb, rope_alpha=MODEL_CONTAINER.draft_config.scale_alpha_value, max_seq_len=MODEL_CONTAINER.draft_config.max_seq_len, ), ) model_card.parameters.draft = draft_card return model_card @app.get("/v1/model/draft/list", dependencies=[Depends(check_api_key)]) async def list_draft_models(): """Lists all draft models in the model directory.""" draft_model_dir = unwrap(get_draft_model_config().get("draft_model_dir"), "models") draft_model_path = pathlib.Path(draft_model_dir) models = get_model_list(draft_model_path.resolve()) return models # Load model endpoint @app.post("/v1/model/load", dependencies=[Depends(check_admin_key)]) async def load_model(request: Request, data: ModelLoadRequest): """Loads a model into the model container.""" global MODEL_CONTAINER if MODEL_CONTAINER and MODEL_CONTAINER.model: raise HTTPException(400, "A model is already loaded! Please unload it first.") if not data.name: raise HTTPException(400, "model_name not found.") model_path = pathlib.Path(unwrap(get_model_config().get("model_dir"), "models")) model_path = model_path / data.name load_data = data.model_dump() if data.draft: if not data.draft.draft_model_name: raise HTTPException( 400, "draft_model_name was not found inside the draft object." ) load_data["draft"]["draft_model_dir"] = unwrap( get_draft_model_config().get("draft_model_dir"), "models" ) if not model_path.exists(): raise HTTPException(400, "model_path does not exist. Check model_name?") MODEL_CONTAINER = ModelContainer(model_path.resolve(), False, **load_data) async def generator(): """Generator for the loading process.""" model_type = "draft" if MODEL_CONTAINER.draft_config else "model" load_status = MODEL_CONTAINER.load_gen(load_progress) try: for module, modules in load_status: if await request.is_disconnected(): break if module == 0: loading_bar: IncrementalBar = IncrementalBar("Modules", max=modules) elif module == modules: loading_bar.next() loading_bar.finish() response = ModelLoadResponse( model_type=model_type, module=module, modules=modules, status="finished", ) yield get_sse_packet(response.model_dump_json()) # Switch to model progress if the draft model is loaded if MODEL_CONTAINER.draft_config: model_type = "model" else: loading_bar.next() response = ModelLoadResponse( model_type=model_type, module=module, modules=modules, status="processing", ) yield get_sse_packet(response.model_dump_json()) except CancelledError: logger.error( "Model load cancelled by user. " "Please make sure to run unload to free up resources." ) except Exception as exc: yield get_generator_error(str(exc)) return StreamingResponse(generator(), media_type="text/event-stream") # Unload model endpoint @app.post( "/v1/model/unload", dependencies=[Depends(check_admin_key), Depends(_check_model_container)], ) async def unload_model(): """Unloads the currently loaded model.""" global MODEL_CONTAINER MODEL_CONTAINER.unload() MODEL_CONTAINER = None @app.get("/v1/templates", dependencies=[Depends(check_api_key)]) @app.get("/v1/template/list", dependencies=[Depends(check_api_key)]) async def get_templates(): templates = get_all_templates() template_strings = list(map(lambda template: template.stem, templates)) return TemplateList(data=template_strings) # Lora list endpoint @app.get("/v1/loras", dependencies=[Depends(check_api_key)]) @app.get("/v1/lora/list", dependencies=[Depends(check_api_key)]) async def get_all_loras(): """Lists all LoRAs in the lora directory.""" lora_path = pathlib.Path(unwrap(get_lora_config().get("lora_dir"), "loras")) loras = get_lora_list(lora_path.resolve()) return loras # Currently loaded loras endpoint @app.get( "/v1/lora", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def get_active_loras(): """Returns the currently loaded loras.""" active_loras = LoraList( data=list( map( lambda lora: LoraCard( id=pathlib.Path(lora.lora_path).parent.name, scaling=lora.lora_scaling * lora.lora_r / lora.lora_alpha, ), MODEL_CONTAINER.active_loras, ) ) ) return active_loras # Load lora endpoint @app.post( "/v1/lora/load", dependencies=[Depends(check_admin_key), Depends(_check_model_container)], ) async def load_lora(data: LoraLoadRequest): """Loads a LoRA into the model container.""" if not data.loras: raise HTTPException(400, "List of loras to load is not found.") lora_dir = pathlib.Path(unwrap(get_lora_config().get("lora_dir"), "loras")) if not lora_dir.exists(): raise HTTPException( 400, "A parent lora directory does not exist. Check your config.yml?", ) # Clean-up existing loras if present if len(MODEL_CONTAINER.active_loras) > 0: MODEL_CONTAINER.unload(True) result = MODEL_CONTAINER.load_loras(lora_dir, **data.model_dump()) return LoraLoadResponse( success=unwrap(result.get("success"), []), failure=unwrap(result.get("failure"), []), ) # Unload lora endpoint @app.post( "/v1/lora/unload", dependencies=[Depends(check_admin_key), Depends(_check_model_container)], ) async def unload_loras(): """Unloads the currently loaded loras.""" MODEL_CONTAINER.unload(True) # Encode tokens endpoint @app.post( "/v1/token/encode", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def encode_tokens(data: TokenEncodeRequest): """Encodes a string into tokens.""" raw_tokens = MODEL_CONTAINER.get_tokens(data.text, None, **data.get_params()) # Have to use this if check otherwise Torch's tensors error out # with a boolean issue tokens = raw_tokens[0].tolist() if raw_tokens is not None else [] response = TokenEncodeResponse(tokens=tokens, length=len(tokens)) return response # Decode tokens endpoint @app.post( "/v1/token/decode", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def decode_tokens(data: TokenDecodeRequest): """Decodes tokens into a string.""" message = MODEL_CONTAINER.get_tokens(None, data.tokens, **data.get_params()) response = TokenDecodeResponse(text=unwrap(message, "")) return response # Completions endpoint @app.post( "/v1/completions", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def generate_completion(request: Request, data: CompletionRequest): """Generates a completion from a prompt.""" model_path = MODEL_CONTAINER.get_model_path() if isinstance(data.prompt, list): data.prompt = "\n".join(data.prompt) if data.stream: async def generator(): """Generator for the generation process.""" try: new_generation = MODEL_CONTAINER.generate_gen( data.prompt, **data.to_gen_params() ) for part, prompt_tokens, completion_tokens in new_generation: if await request.is_disconnected(): break response = create_completion_response( part, prompt_tokens, completion_tokens, model_path.name ) yield get_sse_packet(response.model_dump_json()) # Yield a finish response on successful generation yield get_sse_packet("[DONE]") except CancelledError: logger.error("Completion request cancelled by user.") except Exception as exc: yield get_generator_error(str(exc)) return StreamingResponse( generate_with_semaphore(generator), media_type="text/event-stream" ) response_text, prompt_tokens, completion_tokens = await call_with_semaphore( partial(MODEL_CONTAINER.generate, data.prompt, **data.to_gen_params()) ) response = create_completion_response( response_text, prompt_tokens, completion_tokens, model_path.name ) return response # Chat completions endpoint @app.post( "/v1/chat/completions", dependencies=[Depends(check_api_key), Depends(_check_model_container)], ) async def generate_chat_completion(request: Request, data: ChatCompletionRequest): """Generates a chat completion from a prompt.""" if MODEL_CONTAINER.prompt_template is None: raise HTTPException( 422, "This endpoint is disabled because a prompt template is not set.", ) model_path = MODEL_CONTAINER.get_model_path() if isinstance(data.messages, str): prompt = data.messages else: try: special_tokens_dict = MODEL_CONTAINER.get_special_tokens( unwrap(data.add_bos_token, True), unwrap(data.ban_eos_token, False), ) prompt = get_prompt_from_template( data.messages, MODEL_CONTAINER.prompt_template, data.add_generation_prompt, special_tokens_dict, ) except KeyError as exc: raise HTTPException( 400, "Could not find a Conversation from prompt template " f"'{MODEL_CONTAINER.prompt_template.name}'. " "Check your spelling?", ) from exc except TemplateError as exc: raise HTTPException( 400, f"TemplateError: {str(exc)}", ) from exc if data.stream: const_id = f"chatcmpl-{uuid4().hex}" async def generator(): """Generator for the generation process.""" try: new_generation = MODEL_CONTAINER.generate_gen( prompt, **data.to_gen_params() ) for part, _, _ in new_generation: if await request.is_disconnected(): break response = create_chat_completion_stream_chunk( const_id, part, model_path.name ) yield get_sse_packet(response.model_dump_json()) # Yield a finish response on successful generation finish_response = create_chat_completion_stream_chunk( const_id, finish_reason="stop" ) yield get_sse_packet(finish_response.model_dump_json()) except CancelledError: logger.error("Chat completion cancelled by user.") except Exception as exc: yield get_generator_error(str(exc)) return StreamingResponse( generate_with_semaphore(generator), media_type="text/event-stream" ) response_text, prompt_tokens, completion_tokens = await call_with_semaphore( partial(MODEL_CONTAINER.generate, prompt, **data.to_gen_params()) ) response = create_chat_completion_response( response_text, prompt_tokens, completion_tokens, model_path.name ) return response def entrypoint(args: Optional[dict] = None): """Entry function for program startup""" global MODEL_CONTAINER # Load from YAML config read_config_from_file(pathlib.Path("config.yml")) # Parse and override config from args if args is None: parser = init_argparser() args = convert_args_to_dict(parser.parse_args(), parser)
override_config_from_args(args)
5
2023-11-10 05:54:02+00:00
16k
ShipBit/wingman-ai
services/tower.py
[ { "identifier": "MissingApiKeyException", "path": "exceptions.py", "snippet": "class MissingApiKeyException(Exception):\n pass" }, { "identifier": "OpenAiWingman", "path": "wingmen/open_ai_wingman.py", "snippet": "class OpenAiWingman(Wingman):\n \"\"\"Our OpenAI Wingman base gives ...
import copy from exceptions import MissingApiKeyException from wingmen.open_ai_wingman import OpenAiWingman from wingmen.wingman import Wingman from services.printr import Printr from services.secret_keeper import SecretKeeper
12,282
printr = Printr() class Tower: def __init__(self, config: dict[str, any], secret_keeper: SecretKeeper, app_root_dir: str): # type: ignore self.config = config self.app_root_dir = app_root_dir self.secret_keeper = secret_keeper
printr = Printr() class Tower: def __init__(self, config: dict[str, any], secret_keeper: SecretKeeper, app_root_dir: str): # type: ignore self.config = config self.app_root_dir = app_root_dir self.secret_keeper = secret_keeper
self.key_wingman_dict: dict[str, Wingman] = {}
2
2023-11-15 09:36:06+00:00
16k
wjun0830/CGDETR
cg_detr/inference.py
[ { "identifier": "AverageMeter", "path": "utils/basic_utils.py", "snippet": "class AverageMeter(object):\n \"\"\"Computes and stores the average and current/max/min value\"\"\"\n def __init__(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n s...
import pprint import numpy as np import os import torch import torch.nn.functional as F import torch.backends.cudnn as cudnn import logging from tqdm import tqdm, trange from collections import OrderedDict, defaultdict from utils.basic_utils import AverageMeter from torch.utils.data import DataLoader from cg_detr.config import TestOptions from cg_detr.model import build_model from cg_detr.span_utils import span_cxw_to_xx from cg_detr.start_end_dataset import StartEndDataset, start_end_collate, prepare_batch_inputs from cg_detr.postprocessing_cg_detr import PostProcessorDETR from standalone_eval.eval import eval_submission from utils.basic_utils import save_jsonl, save_json from utils.temporal_nms import temporal_nms from collections import OrderedDict from sys import argv
13,511
min_w_l=12, max_w_l=360, move_window_method="left", process_func_names=("clip_ts", "round_multiple") ) else: post_processor = PostProcessorDETR( clip_length=opt.clip_length, min_ts_val=0, max_ts_val=150, min_w_l=2, max_w_l=60, move_window_method="left", process_func_names=("clip_ts", "round_multiple") ) else: post_processor = PostProcessorDETR( clip_length=opt.clip_length, min_ts_val=0, max_ts_val=50000, min_w_l=0, max_w_l=50000, move_window_method="left", process_func_names=(["round_multiple"]) ) mr_res = post_processor(mr_res) return mr_res, loss_meters def get_eval_res(model, eval_loader, opt, epoch_i, criterion, tb_writer): """compute and save query and video proposal embeddings""" eval_res, eval_loss_meters = compute_mr_results(model, eval_loader, opt, epoch_i, criterion, tb_writer) # list(dict) return eval_res, eval_loss_meters def eval_epoch(model, eval_dataset, opt, save_submission_filename, epoch_i=None, criterion=None, tb_writer=None): logger.info("Generate submissions") model.eval() if criterion is not None and eval_dataset.load_labels: criterion.eval() else: criterion = None if opt.dset_name == 'tacos': shuffle = True else: shuffle = False eval_loader = DataLoader( eval_dataset, collate_fn=start_end_collate, batch_size=opt.eval_bsz, num_workers=opt.num_workers, shuffle=shuffle, pin_memory=opt.pin_memory ) # tvsum if opt.dset_name in ['tvsum', 'youtube_uni']: metrics, eval_loss_meters = compute_hl_results(model, eval_loader, opt, epoch_i, criterion, tb_writer) # to match original save format submission = [ {"brief": metrics} ] submission_path = os.path.join(opt.results_dir, "latest_metric.jsonl") save_jsonl(submission, submission_path) return submission[0], submission[0], eval_loss_meters, [submission_path] else: submission, eval_loss_meters = get_eval_res(model, eval_loader, opt, epoch_i, criterion, tb_writer) if opt.dset_name in ['charadesSTA', 'tacos', 'nlq']: new_submission = [] for s in submission: s.pop('pred_saliency_scores', None) new_submission.append(s) submission = new_submission if opt.no_sort_results: save_submission_filename = save_submission_filename.replace(".jsonl", "_unsorted.jsonl") metrics, metrics_nms, latest_file_paths = eval_epoch_post_processing( submission, opt, eval_dataset.data, save_submission_filename) return metrics, metrics_nms, eval_loss_meters, latest_file_paths def setup_model(opt): """setup model/optimizer/scheduler and load checkpoints when needed""" logger.info("setup model/optimizer/scheduler") model, criterion = build_model(opt) if opt.device.type == "cuda": logger.info("CUDA enabled.") model.to(opt.device) criterion.to(opt.device) param_dicts = [{"params": [p for n, p in model.named_parameters() if p.requires_grad]}] optimizer = torch.optim.AdamW(param_dicts, lr=opt.lr, weight_decay=opt.wd) lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, opt.lr_drop) if opt.resume is not None: logger.info(f"Load checkpoint from {opt.resume}") checkpoint = torch.load(opt.resume, map_location="cpu") new_state_dict = OrderedDict() if 'pt' in opt.resume[:-4]: if 'asr' in opt.resume[:25]: model.load_state_dict(checkpoint["model"]) else: for k, v in checkpoint["model"].items(): name = k[7:] # remove `module.` new_state_dict[name] = v # model.load_state_dict(checkpoint["model"]) model.load_state_dict(new_state_dict) else: model.load_state_dict(checkpoint["model"]) if opt.resume_all: optimizer.load_state_dict(checkpoint['optimizer']) lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) opt.start_epoch = checkpoint['epoch'] + 1 logger.info(f"Loaded model saved at epoch {checkpoint['epoch']} from checkpoint: {opt.resume}") else: logger.warning("If you intend to evaluate the model, please specify --resume with ckpt path") return model, criterion, optimizer, lr_scheduler def start_inference(train_opt=None, split=None, splitfile=None): if train_opt is not None:
logger = logging.getLogger(__name__) logging.basicConfig(format="%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=logging.INFO) def post_processing_mr_nms(mr_res, nms_thd, max_before_nms, max_after_nms): mr_res_after_nms = [] for e in mr_res: e["pred_relevant_windows"] = temporal_nms( e["pred_relevant_windows"][:max_before_nms], nms_thd=nms_thd, max_after_nms=max_after_nms ) mr_res_after_nms.append(e) return mr_res_after_nms def eval_epoch_post_processing(submission, opt, gt_data, save_submission_filename): # IOU_THDS = (0.5, 0.7) logger.info("Saving/Evaluating before nms results") submission_path = os.path.join(opt.results_dir, save_submission_filename) save_jsonl(submission, submission_path) if opt.eval_split_name in ["val"]: # since test_public has no GT metrics = eval_submission( submission, gt_data, verbose=opt.debug, match_number=not opt.debug ) save_metrics_path = submission_path.replace(".jsonl", "_metrics.json") save_json(metrics, save_metrics_path, save_pretty=True, sort_keys=False) latest_file_paths = [submission_path, save_metrics_path] else: metrics = None latest_file_paths = [submission_path, ] if opt.nms_thd != -1: logger.info("[MR] Performing nms with nms_thd {}".format(opt.nms_thd)) submission_after_nms = post_processing_mr_nms( submission, nms_thd=opt.nms_thd, max_before_nms=opt.max_before_nms, max_after_nms=opt.max_after_nms ) logger.info("Saving/Evaluating nms results") submission_nms_path = submission_path.replace(".jsonl", "_nms_thd_{}.jsonl".format(opt.nms_thd)) save_jsonl(submission_after_nms, submission_nms_path) if opt.eval_split_name == "val": metrics_nms = eval_submission( submission_after_nms, gt_data, verbose=opt.debug, match_number=not opt.debug ) save_metrics_nms_path = submission_nms_path.replace(".jsonl", "_metrics.json") save_json(metrics_nms, save_metrics_nms_path, save_pretty=True, sort_keys=False) latest_file_paths += [submission_nms_path, save_metrics_nms_path] else: metrics_nms = None latest_file_paths = [submission_nms_path, ] else: metrics_nms = None return metrics, metrics_nms, latest_file_paths # for HL @torch.no_grad() def compute_hl_results(model, eval_loader, opt, epoch_i=None, criterion=None, tb_writer=None): model.eval() if criterion: assert eval_loader.dataset.load_labels criterion.eval() loss_meters = defaultdict(AverageMeter) write_tb = tb_writer is not None and epoch_i is not None mr_res = [] topk = 5 # top-5 map video_ap_collected = [] for batch in tqdm(eval_loader, desc="compute st ed scores"): query_meta = batch[0] model_inputs, targets = prepare_batch_inputs(batch[1], opt.device, non_blocking=opt.pin_memory) outputs = model(**model_inputs) # loss meters # if criterion: # loss_dict = criterion(outputs, targets) # weight_dict = criterion.weight_dict # print(loss_dict) # print(weight_dict) # print('#######') # {'loss_saliency': tensor(18.1374, device='cuda:0')} # {'loss_span': 10, 'loss_giou': 1, 'loss_label': 4, 'loss_saliency': 1.0, 'loss_ms_align': 1.0, # 'loss_distill': 1.0, 'loss_span_0': 10, 'loss_giou_0': 1, 'loss_label_0': 4, 'loss_ms_align_0': 1.0, # 'loss_distill_0': 1.0} # losses=0. # print(loss_dict.keys(), weight_dict.keys()) # losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) # loss_dict["loss_overall"] = float(losses) # for logging only # print(loss_dict.items()) # # print(weight_dict.items()) # for k, v in loss_dict.items(): # loss_meters[k].update(float(v) * weight_dict[k] if k in weight_dict else float(v)) preds = outputs['saliency_scores'].clone().detach() for meta, pred in zip(query_meta, preds): pred = pred label = meta['label'] # raw label video_ap = [] # Follow the UMT code "https://github.com/TencentARC/UMT/blob/main/datasets/tvsum.py" if opt.dset_name in ["tvsum"]: for i in range(20): pred=pred.cpu() cur_pred = pred[:len(label)] inds = torch.argsort(cur_pred, descending=True, dim=-1) # video_id = self.get_video_id(idx) cur_label = torch.Tensor(label)[:, i] cur_label = torch.where(cur_label > cur_label.median(), 1.0, .0) cur_label = cur_label[inds].tolist()[:topk] # if (num_gt := sum(cur_label)) == 0: num_gt = sum(cur_label) if num_gt == 0: video_ap.append(0) continue hits = ap = rec = 0 prc = 1 for j, gt in enumerate(cur_label): hits += gt _rec = hits / num_gt _prc = hits / (j + 1) ap += (_rec - rec) * (prc + _prc) / 2 rec, prc = _rec, _prc video_ap.append(ap) elif opt.dset_name in ["youtube_uni"]: cur_pred = pred[:len(label)] # if opt.dset_name == "tvsum_sfc": cur_pred = cur_pred.cpu() inds = torch.argsort(cur_pred, descending=True, dim=-1) cur_label = torch.Tensor(label).squeeze()[inds].tolist() num_gt = sum(cur_label) if num_gt == 0: video_ap.append(0) continue hits = ap = rec = 0 prc = 1 for j, gt in enumerate(cur_label): hits += gt _rec = hits / num_gt _prc = hits / (j + 1) ap += (_rec - rec) * (prc + _prc) / 2 rec, prc = _rec, _prc video_ap.append(float(ap)) else: print("No such dataset") exit(-1) video_ap_collected.append(video_ap) mean_ap = np.mean(video_ap_collected) submmission = dict(mAP=round(mean_ap, 5)) # tensorboard writer if write_tb and criterion: for k, v in loss_meters.items(): tb_writer.add_scalar("Eval/{}".format(k), v.avg, epoch_i + 1) return submmission, loss_meters @torch.no_grad() def compute_mr_results(model, eval_loader, opt, epoch_i=None, criterion=None, tb_writer=None): model.eval() if criterion: assert eval_loader.dataset.load_labels criterion.eval() loss_meters = defaultdict(AverageMeter) write_tb = tb_writer is not None and epoch_i is not None mr_res = [] for batch in tqdm(eval_loader, desc="compute st ed scores"): query_meta = batch[0] model_inputs, targets = prepare_batch_inputs(batch[1], opt.device, non_blocking=opt.pin_memory) outputs = model(**model_inputs) prob = F.softmax(outputs["pred_logits"], -1) # (batch_size, #queries, #classes=2) if opt.span_loss_type == "l1": scores = prob[..., 0] # * (batch_size, #queries) foreground label is 0, we directly take it pred_spans = outputs["pred_spans"] # (bsz, #queries, 2) _saliency_scores = outputs["saliency_scores"].half() # (bsz, L) saliency_scores = [] valid_vid_lengths = model_inputs["src_vid_mask"].sum(1).cpu().tolist() for j in range(len(valid_vid_lengths)): saliency_scores.append(_saliency_scores[j, :int(valid_vid_lengths[j])].tolist()) else: bsz, n_queries = outputs["pred_spans"].shape[:2] # # (bsz, #queries, max_v_l *2) pred_spans_logits = outputs["pred_spans"].view(bsz, n_queries, 2, opt.max_v_l) pred_span_scores, pred_spans = F.softmax(pred_spans_logits, dim=-1).max(-1) # 2 * (bsz, #queries, 2) scores = torch.prod(pred_span_scores, 2) # (bsz, #queries) pred_spans[:, 1] += 1 pred_spans *= opt.clip_length # compose predictions for idx, (meta, spans, score) in enumerate(zip(query_meta, pred_spans.cpu(), scores.cpu())): if opt.span_loss_type == "l1": spans = span_cxw_to_xx(spans) * meta["duration"] spans = torch.clamp(spans, 0, meta["duration"]) # # (#queries, 3), [st(float), ed(float), score(float)] cur_ranked_preds = torch.cat([spans, score[:, None]], dim=1).tolist() if not opt.no_sort_results: cur_ranked_preds = sorted(cur_ranked_preds, key=lambda x: x[2], reverse=True) cur_ranked_preds = [[float(f"{e:.4f}") for e in row] for row in cur_ranked_preds] cur_query_pred = dict( qid=meta["qid"], query=meta["query"], vid=meta["vid"], pred_relevant_windows=cur_ranked_preds, pred_saliency_scores=saliency_scores[idx] ) mr_res.append(cur_query_pred) if criterion: loss_dict = criterion(outputs, targets) weight_dict = criterion.weight_dict losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) loss_dict["loss_overall"] = float(losses) # for logging only for k, v in loss_dict.items(): loss_meters[k].update(float(v) * weight_dict[k] if k in weight_dict else float(v)) if opt.debug: break if write_tb and criterion: for k, v in loss_meters.items(): tb_writer.add_scalar("Eval/{}".format(k), v.avg, epoch_i + 1) if opt.dset_name in ['hl']: post_processor = PostProcessorDETR( clip_length=opt.clip_length, min_ts_val=0, max_ts_val=150, min_w_l=2, max_w_l=150, move_window_method="left", process_func_names=("clip_ts", "round_multiple") ) elif opt.dset_name in ['charadesSTA']: if opt.v_feat_dim == 4096: # vgg post_processor = PostProcessorDETR( clip_length=opt.clip_length, min_ts_val=0, max_ts_val=360, min_w_l=12, max_w_l=360, move_window_method="left", process_func_names=("clip_ts", "round_multiple") ) else: post_processor = PostProcessorDETR( clip_length=opt.clip_length, min_ts_val=0, max_ts_val=150, min_w_l=2, max_w_l=60, move_window_method="left", process_func_names=("clip_ts", "round_multiple") ) else: post_processor = PostProcessorDETR( clip_length=opt.clip_length, min_ts_val=0, max_ts_val=50000, min_w_l=0, max_w_l=50000, move_window_method="left", process_func_names=(["round_multiple"]) ) mr_res = post_processor(mr_res) return mr_res, loss_meters def get_eval_res(model, eval_loader, opt, epoch_i, criterion, tb_writer): """compute and save query and video proposal embeddings""" eval_res, eval_loss_meters = compute_mr_results(model, eval_loader, opt, epoch_i, criterion, tb_writer) # list(dict) return eval_res, eval_loss_meters def eval_epoch(model, eval_dataset, opt, save_submission_filename, epoch_i=None, criterion=None, tb_writer=None): logger.info("Generate submissions") model.eval() if criterion is not None and eval_dataset.load_labels: criterion.eval() else: criterion = None if opt.dset_name == 'tacos': shuffle = True else: shuffle = False eval_loader = DataLoader( eval_dataset, collate_fn=start_end_collate, batch_size=opt.eval_bsz, num_workers=opt.num_workers, shuffle=shuffle, pin_memory=opt.pin_memory ) # tvsum if opt.dset_name in ['tvsum', 'youtube_uni']: metrics, eval_loss_meters = compute_hl_results(model, eval_loader, opt, epoch_i, criterion, tb_writer) # to match original save format submission = [ {"brief": metrics} ] submission_path = os.path.join(opt.results_dir, "latest_metric.jsonl") save_jsonl(submission, submission_path) return submission[0], submission[0], eval_loss_meters, [submission_path] else: submission, eval_loss_meters = get_eval_res(model, eval_loader, opt, epoch_i, criterion, tb_writer) if opt.dset_name in ['charadesSTA', 'tacos', 'nlq']: new_submission = [] for s in submission: s.pop('pred_saliency_scores', None) new_submission.append(s) submission = new_submission if opt.no_sort_results: save_submission_filename = save_submission_filename.replace(".jsonl", "_unsorted.jsonl") metrics, metrics_nms, latest_file_paths = eval_epoch_post_processing( submission, opt, eval_dataset.data, save_submission_filename) return metrics, metrics_nms, eval_loss_meters, latest_file_paths def setup_model(opt): """setup model/optimizer/scheduler and load checkpoints when needed""" logger.info("setup model/optimizer/scheduler") model, criterion = build_model(opt) if opt.device.type == "cuda": logger.info("CUDA enabled.") model.to(opt.device) criterion.to(opt.device) param_dicts = [{"params": [p for n, p in model.named_parameters() if p.requires_grad]}] optimizer = torch.optim.AdamW(param_dicts, lr=opt.lr, weight_decay=opt.wd) lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, opt.lr_drop) if opt.resume is not None: logger.info(f"Load checkpoint from {opt.resume}") checkpoint = torch.load(opt.resume, map_location="cpu") new_state_dict = OrderedDict() if 'pt' in opt.resume[:-4]: if 'asr' in opt.resume[:25]: model.load_state_dict(checkpoint["model"]) else: for k, v in checkpoint["model"].items(): name = k[7:] # remove `module.` new_state_dict[name] = v # model.load_state_dict(checkpoint["model"]) model.load_state_dict(new_state_dict) else: model.load_state_dict(checkpoint["model"]) if opt.resume_all: optimizer.load_state_dict(checkpoint['optimizer']) lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) opt.start_epoch = checkpoint['epoch'] + 1 logger.info(f"Loaded model saved at epoch {checkpoint['epoch']} from checkpoint: {opt.resume}") else: logger.warning("If you intend to evaluate the model, please specify --resume with ckpt path") return model, criterion, optimizer, lr_scheduler def start_inference(train_opt=None, split=None, splitfile=None): if train_opt is not None:
opt = TestOptions().parse(train_opt.a_feat_dir)
1
2023-11-10 12:45:25+00:00
16k
dazhangyu123/ACMIL
Step1_create_patches_fp.py
[ { "identifier": "WholeSlideImage", "path": "wsi_core/WholeSlideImage.py", "snippet": "class WholeSlideImage(object):\n def __init__(self, path):\n\n \"\"\"\n Args:\n path (str): fullpath to WSI file\n \"\"\"\n\n# self.name = \".\".join(path.split(\"/\")[-1].spl...
from wsi_core.WholeSlideImage import WholeSlideImage from wsi_core.wsi_utils import StitchCoords from wsi_core.batch_process_utils import initialize_df from glob import glob import os import numpy as np import time import argparse import pdb import pandas as pd
12,265
# internal imports # other imports def stitching(file_path, wsi_object, downscale=64): start = time.time() heatmap = StitchCoords(file_path, wsi_object, downscale=downscale, bg_color=(0, 0, 0), alpha=-1, draw_grid=False) total_time = time.time() - start return heatmap, total_time def segment(WSI_object, seg_params, filter_params): ### Start Seg Timer start_time = time.time() # Segment WSI_object.segmentTissue(**seg_params, filter_params=filter_params) ### Stop Seg Timers seg_time_elapsed = time.time() - start_time return WSI_object, seg_time_elapsed def patching(WSI_object, **kwargs): ### Start Patch Timer start_time = time.time() # Patch file_path = WSI_object.process_contours(**kwargs) ### Stop Patch Timer patch_time_elapsed = time.time() - start_time return file_path, patch_time_elapsed def walk_dir(data_dir, file_types=['.kfb', '.tif', '.svs', '.ndpi', '.mrxs', '.hdx', '.sdpc', '.mdsx', '.tiff', '.tmap']): path_list = [] for dirpath, dirnames, files in os.walk(data_dir): for f in files: for this_type in file_types: if f.lower().endswith(this_type): path_list.append(os.path.join(dirpath, f)) break return path_list def seg_and_patch(source, save_dir, patch_save_dir, mask_save_dir, stitch_save_dir, patch_size=256, step_size=256, seg_params={'seg_level': -1, 'sthresh': 8, 'mthresh': 7, 'close': 4, 'use_otsu': False, 'keep_ids': 'none', 'exclude_ids': 'none'}, filter_params={'a_t': 100, 'a_h': 16, 'max_n_holes': 8}, vis_params={'vis_level': -1, 'line_thickness': 500}, patch_params={'use_padding': True, 'contour_fn': 'four_pt'}, patch_level=1, use_default_params=False, seg=False, save_mask=True, stitch=False, patch=False, auto_skip=True, process_list=None): slides = glob(source + '/*/*/*/*.svs') # slides = sorted(os.listdir(source), reverse=True) # slides = # pdb.set_trace() # slides = slides[-10:] slides = [slide for slide in slides if os.path.isfile(os.path.join(source, slide))] if process_list is None: df = initialize_df(slides, seg_params, filter_params, vis_params, patch_params) else: df = pd.read_csv(process_list) df = initialize_df(df, seg_params, filter_params, vis_params, patch_params) mask = df['process'] == 1 process_stack = df[mask] total = len(process_stack) legacy_support = 'a' in df.keys() if legacy_support: print('detected legacy segmentation csv file, legacy support enabled') df = df.assign(**{'a_t': np.full((len(df)), int(filter_params['a_t']), dtype=np.uint32), 'a_h': np.full((len(df)), int(filter_params['a_h']), dtype=np.uint32), 'max_n_holes': np.full((len(df)), int(filter_params['max_n_holes']), dtype=np.uint32), 'line_thickness': np.full((len(df)), int(vis_params['line_thickness']), dtype=np.uint32), 'contour_fn': np.full((len(df)), patch_params['contour_fn'])}) seg_times = 0. patch_times = 0. stitch_times = 0. for i in range(total): df.to_csv(os.path.join(save_dir, 'process_list_autogen.csv'), index=False) idx = process_stack.index[i] slide = process_stack.loc[idx, 'slide_id'] print("\n\nprogress: {:.2f}, {}/{}".format(i / total, i, total)) print('processing {}'.format(slide)) df.loc[idx, 'process'] = 0 slide_id, _ = os.path.splitext(slide.split('/')[-1]) if auto_skip and os.path.isfile(os.path.join(patch_save_dir, slide_id + '.h5')): print('{} already exist in destination location, skipped'.format(slide_id)) df.loc[idx, 'status'] = 'already_exist' continue # Inialize WSI full_path = slide try:
# internal imports # other imports def stitching(file_path, wsi_object, downscale=64): start = time.time() heatmap = StitchCoords(file_path, wsi_object, downscale=downscale, bg_color=(0, 0, 0), alpha=-1, draw_grid=False) total_time = time.time() - start return heatmap, total_time def segment(WSI_object, seg_params, filter_params): ### Start Seg Timer start_time = time.time() # Segment WSI_object.segmentTissue(**seg_params, filter_params=filter_params) ### Stop Seg Timers seg_time_elapsed = time.time() - start_time return WSI_object, seg_time_elapsed def patching(WSI_object, **kwargs): ### Start Patch Timer start_time = time.time() # Patch file_path = WSI_object.process_contours(**kwargs) ### Stop Patch Timer patch_time_elapsed = time.time() - start_time return file_path, patch_time_elapsed def walk_dir(data_dir, file_types=['.kfb', '.tif', '.svs', '.ndpi', '.mrxs', '.hdx', '.sdpc', '.mdsx', '.tiff', '.tmap']): path_list = [] for dirpath, dirnames, files in os.walk(data_dir): for f in files: for this_type in file_types: if f.lower().endswith(this_type): path_list.append(os.path.join(dirpath, f)) break return path_list def seg_and_patch(source, save_dir, patch_save_dir, mask_save_dir, stitch_save_dir, patch_size=256, step_size=256, seg_params={'seg_level': -1, 'sthresh': 8, 'mthresh': 7, 'close': 4, 'use_otsu': False, 'keep_ids': 'none', 'exclude_ids': 'none'}, filter_params={'a_t': 100, 'a_h': 16, 'max_n_holes': 8}, vis_params={'vis_level': -1, 'line_thickness': 500}, patch_params={'use_padding': True, 'contour_fn': 'four_pt'}, patch_level=1, use_default_params=False, seg=False, save_mask=True, stitch=False, patch=False, auto_skip=True, process_list=None): slides = glob(source + '/*/*/*/*.svs') # slides = sorted(os.listdir(source), reverse=True) # slides = # pdb.set_trace() # slides = slides[-10:] slides = [slide for slide in slides if os.path.isfile(os.path.join(source, slide))] if process_list is None: df = initialize_df(slides, seg_params, filter_params, vis_params, patch_params) else: df = pd.read_csv(process_list) df = initialize_df(df, seg_params, filter_params, vis_params, patch_params) mask = df['process'] == 1 process_stack = df[mask] total = len(process_stack) legacy_support = 'a' in df.keys() if legacy_support: print('detected legacy segmentation csv file, legacy support enabled') df = df.assign(**{'a_t': np.full((len(df)), int(filter_params['a_t']), dtype=np.uint32), 'a_h': np.full((len(df)), int(filter_params['a_h']), dtype=np.uint32), 'max_n_holes': np.full((len(df)), int(filter_params['max_n_holes']), dtype=np.uint32), 'line_thickness': np.full((len(df)), int(vis_params['line_thickness']), dtype=np.uint32), 'contour_fn': np.full((len(df)), patch_params['contour_fn'])}) seg_times = 0. patch_times = 0. stitch_times = 0. for i in range(total): df.to_csv(os.path.join(save_dir, 'process_list_autogen.csv'), index=False) idx = process_stack.index[i] slide = process_stack.loc[idx, 'slide_id'] print("\n\nprogress: {:.2f}, {}/{}".format(i / total, i, total)) print('processing {}'.format(slide)) df.loc[idx, 'process'] = 0 slide_id, _ = os.path.splitext(slide.split('/')[-1]) if auto_skip and os.path.isfile(os.path.join(patch_save_dir, slide_id + '.h5')): print('{} already exist in destination location, skipped'.format(slide_id)) df.loc[idx, 'status'] = 'already_exist' continue # Inialize WSI full_path = slide try:
WSI_object = WholeSlideImage(full_path)
0
2023-11-12 14:07:34+00:00
16k
zhang-tao-whu/DVIS_Plus
dvis_Plus/meta_architecture.py
[ { "identifier": "VideoSetCriterion", "path": "mask2former_video/modeling/criterion.py", "snippet": "class VideoSetCriterion(nn.Module):\n \"\"\"This class computes the loss for DETR.\n The process happens in two steps:\n 1) we compute hungarian assignment between ground truth boxes and the ...
from typing import Tuple from torch import nn from torch.nn import functional as F from detectron2.config import configurable from detectron2.data import MetadataCatalog from detectron2.modeling import META_ARCH_REGISTRY, build_backbone, build_sem_seg_head from detectron2.modeling.backbone import Backbone from detectron2.structures import Boxes, ImageList, Instances, BitMasks from mask2former_video.modeling.criterion import VideoSetCriterion from mask2former_video.modeling.matcher import VideoHungarianMatcher, VideoHungarianMatcher_Consistent from mask2former_video.utils.memory import retry_if_cuda_oom from scipy.optimize import linear_sum_assignment from .tracker import ReferringTracker_noiser from .refiner import TemporalRefiner from .utils import loss_reid, Outputs_Memory_PerClasses import einops import torch
14,238
out_ids.append(cur_ids[k]) return { "image_size": (output_height, output_width), "pred_masks": panoptic_seg.cpu(), "segments_infos": segments_infos, "pred_ids": out_ids, "task": "vps", } def inference_video_vss( self, pred_cls, pred_masks, img_size, output_height, output_width, first_resize_size, pred_id, aux_pred_cls=None, ): mask_cls = F.softmax(pred_cls, dim=-1)[..., :-1] if aux_pred_cls is not None: aux_pred_cls = F.softmax(aux_pred_cls, dim=-1)[..., :-1] mask_cls = torch.maximum(mask_cls, aux_pred_cls.to(mask_cls)) mask_pred = pred_masks # interpolation to original image size cur_masks = F.interpolate( mask_pred, size=first_resize_size, mode="bilinear", align_corners=False ) cur_masks = cur_masks[:, :, :img_size[0], :img_size[1]].sigmoid() cur_masks = F.interpolate( cur_masks, size=(output_height, output_width), mode="bilinear", align_corners=False ) semseg = torch.einsum("qc,qthw->cthw", mask_cls, cur_masks) sem_score, sem_mask = semseg.max(0) sem_mask = sem_mask return { "image_size": (output_height, output_width), "pred_masks": sem_mask.cpu(), "task": "vss", } def get_cl_loss_ref(self, outputs, referecne_match_result): references = outputs['pred_references'] # t q c # per frame contrastive_items = [] for i in range(references.size(0)): if i == 0: continue frame_reference = references[i] # (q, c) frame_reference_ = references[i - 1] # (q, c) if i != references.size(0) - 1: frame_reference_next = references[i + 1] else: frame_reference_next = None frame_ref_gt_indices = referecne_match_result[i] gt2ref = {} for i_ref, i_gt in zip(frame_ref_gt_indices[0], frame_ref_gt_indices[1]): gt2ref[i_gt.item()] = i_ref.item() # per instance for i_gt in gt2ref.keys(): i_ref = gt2ref[i_gt] anchor_embeds = frame_reference[[i_ref]] pos_embeds = frame_reference_[[i_ref]] neg_range = list(range(0, i_ref)) + list(range(i_ref + 1, frame_reference.size(0))) neg_embeds = frame_reference_[neg_range] num_positive = pos_embeds.shape[0] # concate pos and neg to get whole constractive samples pos_neg_embedding = torch.cat( [pos_embeds, neg_embeds], dim=0) # generate label, pos is 1, neg is 0 pos_neg_label = pos_neg_embedding.new_zeros((pos_neg_embedding.shape[0],), dtype=torch.int64) # noqa pos_neg_label[:num_positive] = 1. # dot product dot_product = torch.einsum( 'ac,kc->ak', [pos_neg_embedding, anchor_embeds]) aux_normalize_pos_neg_embedding = nn.functional.normalize( pos_neg_embedding, dim=1) aux_normalize_anchor_embedding = nn.functional.normalize( anchor_embeds, dim=1) aux_cosine_similarity = torch.einsum('ac,kc->ak', [aux_normalize_pos_neg_embedding, aux_normalize_anchor_embedding]) contrastive_items.append({ 'dot_product': dot_product, 'cosine_similarity': aux_cosine_similarity, 'label': pos_neg_label}) if frame_reference_next is not None: pos_embeds = frame_reference_next[[i_ref]] neg_range = list(range(0, i_ref)) + list(range(i_ref + 1, frame_reference.size(0))) neg_embeds = frame_reference_next[neg_range] num_positive = pos_embeds.shape[0] # concate pos and neg to get whole constractive samples pos_neg_embedding = torch.cat( [pos_embeds, neg_embeds], dim=0) # generate label, pos is 1, neg is 0 pos_neg_label = pos_neg_embedding.new_zeros((pos_neg_embedding.shape[0],), dtype=torch.int64) # noqa pos_neg_label[:num_positive] = 1. # dot product dot_product = torch.einsum( 'ac,kc->ak', [pos_neg_embedding, anchor_embeds]) aux_normalize_pos_neg_embedding = nn.functional.normalize( pos_neg_embedding, dim=1) aux_normalize_anchor_embedding = nn.functional.normalize( anchor_embeds, dim=1) aux_cosine_similarity = torch.einsum('ac,kc->ak', [aux_normalize_pos_neg_embedding, aux_normalize_anchor_embedding]) contrastive_items.append({ 'dot_product': dot_product, 'cosine_similarity': aux_cosine_similarity, 'label': pos_neg_label})
@META_ARCH_REGISTRY.register() class MinVIS(nn.Module): """ Copied from "https://github.com/NVlabs/MinVIS". """ @configurable def __init__( self, *, backbone: Backbone, sem_seg_head: nn.Module, criterion: nn.Module, num_queries: int, object_mask_threshold: float, overlap_threshold: float, metadata, size_divisibility: int, sem_seg_postprocess_before_inference: bool, pixel_mean: Tuple[float], pixel_std: Tuple[float], # video num_frames, window_inference, ): """ Args: backbone: a backbone module, must follow detectron2's backbone interface sem_seg_head: a module that predicts semantic segmentation from backbone features criterion: a module that defines the loss num_queries: int, number of queries object_mask_threshold: float, threshold to filter query based on classification score for panoptic segmentation inference overlap_threshold: overlap threshold used in general inference for panoptic segmentation metadata: dataset meta, get `thing` and `stuff` category names for panoptic segmentation inference size_divisibility: Some backbones require the input height and width to be divisible by a specific integer. We can use this to override such requirement. sem_seg_postprocess_before_inference: whether to resize the prediction back to original input size before semantic segmentation inference or after. For high-resolution dataset like Mapillary, resizing predictions before inference will cause OOM error. pixel_mean, pixel_std: list or tuple with #channels element, representing the per-channel mean and std to be used to normalize the input image semantic_on: bool, whether to output semantic segmentation prediction instance_on: bool, whether to output instance segmentation prediction panoptic_on: bool, whether to output panoptic segmentation prediction test_topk_per_image: int, instance segmentation parameter, keep topk instances per image """ super().__init__() self.backbone = backbone self.sem_seg_head = sem_seg_head self.criterion = criterion self.num_queries = num_queries self.overlap_threshold = overlap_threshold self.object_mask_threshold = object_mask_threshold self.metadata = metadata if size_divisibility < 0: # use backbone size_divisibility if not set size_divisibility = self.backbone.size_divisibility self.size_divisibility = size_divisibility self.sem_seg_postprocess_before_inference = sem_seg_postprocess_before_inference self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) self.num_frames = num_frames self.window_inference = window_inference @classmethod def from_config(cls, cfg): backbone = build_backbone(cfg) sem_seg_head = build_sem_seg_head(cfg, backbone.output_shape()) # Loss parameters: deep_supervision = cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION no_object_weight = cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT # loss weights class_weight = cfg.MODEL.MASK_FORMER.CLASS_WEIGHT dice_weight = cfg.MODEL.MASK_FORMER.DICE_WEIGHT mask_weight = cfg.MODEL.MASK_FORMER.MASK_WEIGHT # building criterion matcher = VideoHungarianMatcher( cost_class=class_weight, cost_mask=mask_weight, cost_dice=dice_weight, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, ) weight_dict = {"loss_ce": class_weight, "loss_mask": mask_weight, "loss_dice": dice_weight} if deep_supervision: dec_layers = cfg.MODEL.MASK_FORMER.DEC_LAYERS aux_weight_dict = {} for i in range(dec_layers - 1): aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()}) weight_dict.update(aux_weight_dict) losses = ["labels", "masks"] criterion = VideoSetCriterion( sem_seg_head.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=no_object_weight, losses=losses, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, oversample_ratio=cfg.MODEL.MASK_FORMER.OVERSAMPLE_RATIO, importance_sample_ratio=cfg.MODEL.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO, ) return { "backbone": backbone, "sem_seg_head": sem_seg_head, "criterion": criterion, "num_queries": cfg.MODEL.MASK_FORMER.NUM_OBJECT_QUERIES, "object_mask_threshold": cfg.MODEL.MASK_FORMER.TEST.OBJECT_MASK_THRESHOLD, "overlap_threshold": cfg.MODEL.MASK_FORMER.TEST.OVERLAP_THRESHOLD, "metadata": MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), "size_divisibility": cfg.MODEL.MASK_FORMER.SIZE_DIVISIBILITY, "sem_seg_postprocess_before_inference": True, "pixel_mean": cfg.MODEL.PIXEL_MEAN, "pixel_std": cfg.MODEL.PIXEL_STD, # video "num_frames": cfg.INPUT.SAMPLING_FRAME_NUM, "window_inference": cfg.MODEL.MASK_FORMER.TEST.WINDOW_INFERENCE, } @property def device(self): return self.pixel_mean.device def forward(self, batched_inputs): """ Args: batched_inputs: a list, batched outputs of :class:`DatasetMapper`. Each item in the list contains the inputs for one image. For now, each item in the list is a dict that contains: * "image": Tensor, image in (C, H, W) format. * "instances": per-region ground truth * Other information that's included in the original dicts, such as: "height", "width" (int): the output resolution of the model (may be different from input resolution), used in inference. Returns: list[dict]: each dict has the results for one image. The dict contains the following keys: * "sem_seg": A Tensor that represents the per-pixel segmentation prediced by the head. The prediction has shape KxHxW that represents the logits of each class for each pixel. * "panoptic_seg": A tuple that represent panoptic output panoptic_seg (Tensor): of shape (height, width) where the values are ids for each segment. segments_info (list[dict]): Describe each segment in `panoptic_seg`. Each dict contains keys "id", "category_id", "isthing". """ images = [] for video in batched_inputs: for frame in video["image"]: images.append(frame.to(self.device)) images = [(x - self.pixel_mean) / self.pixel_std for x in images] images = ImageList.from_tensors(images, self.size_divisibility) if not self.training and self.window_inference: outputs = self.run_window_inference(images.tensor, window_size=3) else: features = self.backbone(images.tensor) outputs = self.sem_seg_head(features) if self.training: # mask classification target targets = self.prepare_targets(batched_inputs, images) outputs, targets = self.frame_decoder_loss_reshape(outputs, targets) # bipartite matching-based loss losses = self.criterion(outputs, targets) for k in list(losses.keys()): if k in self.criterion.weight_dict: losses[k] *= self.criterion.weight_dict[k] else: # remove this loss if not specified in `weight_dict` losses.pop(k) return losses else: outputs = self.post_processing(outputs) mask_cls_results = outputs["pred_logits"] mask_pred_results = outputs["pred_masks"] mask_cls_result = mask_cls_results[0] mask_pred_result = mask_pred_results[0] first_resize_size = (images.tensor.shape[-2], images.tensor.shape[-1]) input_per_image = batched_inputs[0] image_size = images.image_sizes[0] # image size without padding after data augmentation height = input_per_image.get("height", image_size[0]) # raw image size before data augmentation width = input_per_image.get("width", image_size[1]) return retry_if_cuda_oom(self.inference_video)( mask_cls_result, mask_pred_result, image_size, height, width, first_resize_size) def frame_decoder_loss_reshape(self, outputs, targets): outputs['pred_masks'] = einops.rearrange(outputs['pred_masks'], 'b q t h w -> (b t) q () h w') outputs['pred_logits'] = einops.rearrange(outputs['pred_logits'], 'b t q c -> (b t) q c') if 'aux_outputs' in outputs: for i in range(len(outputs['aux_outputs'])): outputs['aux_outputs'][i]['pred_masks'] = einops.rearrange( outputs['aux_outputs'][i]['pred_masks'], 'b q t h w -> (b t) q () h w' ) outputs['aux_outputs'][i]['pred_logits'] = einops.rearrange( outputs['aux_outputs'][i]['pred_logits'], 'b t q c -> (b t) q c' ) gt_instances = [] for targets_per_video in targets: num_labeled_frames = targets_per_video['ids'].shape[1] for f in range(num_labeled_frames): labels = targets_per_video['labels'] ids = targets_per_video['ids'][:, [f]] masks = targets_per_video['masks'][:, [f], :, :] gt_instances.append({"labels": labels, "ids": ids, "masks": masks}) return outputs, gt_instances def match_from_embds(self, tgt_embds, cur_embds): cur_embds = cur_embds / cur_embds.norm(dim=1)[:, None] tgt_embds = tgt_embds / tgt_embds.norm(dim=1)[:, None] cos_sim = torch.mm(cur_embds, tgt_embds.transpose(0, 1)) cost_embd = 1 - cos_sim C = 1.0 * cost_embd C = C.cpu() indices = linear_sum_assignment(C.transpose(0, 1)) # target x current indices = indices[1] # permutation that makes current aligns to target return indices def post_processing(self, outputs): pred_logits, pred_masks, pred_embds = outputs['pred_logits'], outputs['pred_masks'], outputs['pred_embds'] pred_logits = pred_logits[0] pred_masks = einops.rearrange(pred_masks[0], 'q t h w -> t q h w') pred_embds = einops.rearrange(pred_embds[0], 'c t q -> t q c') pred_logits = list(torch.unbind(pred_logits)) pred_masks = list(torch.unbind(pred_masks)) pred_embds = list(torch.unbind(pred_embds)) out_logits = [] out_masks = [] out_embds = [] out_logits.append(pred_logits[0]) out_masks.append(pred_masks[0]) out_embds.append(pred_embds[0]) # match the instances frame by frame for i in range(1, len(pred_logits)): indices = self.match_from_embds(out_embds[-1], pred_embds[i]) out_logits.append(pred_logits[i][indices, :]) out_masks.append(pred_masks[i][indices, :, :]) out_embds.append(pred_embds[i][indices, :]) out_logits = sum(out_logits)/len(out_logits) out_masks = torch.stack(out_masks, dim=1) # q h w -> q t h w out_logits = out_logits.unsqueeze(0) out_masks = out_masks.unsqueeze(0) outputs['pred_logits'] = out_logits outputs['pred_masks'] = out_masks return outputs def run_window_inference(self, images_tensor, window_size=30): iters = len(images_tensor) // window_size if len(images_tensor) % window_size != 0: iters += 1 out_list = [] for i in range(iters): start_idx = i * window_size end_idx = (i+1) * window_size features = self.backbone(images_tensor[start_idx:end_idx]) out = self.sem_seg_head(features) del features['res2'], features['res3'], features['res4'], features['res5'] for j in range(len(out['aux_outputs'])): del out['aux_outputs'][j]['pred_masks'], out['aux_outputs'][j]['pred_logits'] out['pred_masks'] = out['pred_masks'].detach().cpu().to(torch.float32) out_list.append(out) # merge outputs outputs = {} outputs['pred_logits'] = torch.cat([x['pred_logits'] for x in out_list], dim=1).detach() outputs['pred_masks'] = torch.cat([x['pred_masks'] for x in out_list], dim=2).detach() outputs['pred_embds'] = torch.cat([x['pred_embds'] for x in out_list], dim=2).detach() return outputs def prepare_targets(self, targets, images): h_pad, w_pad = images.tensor.shape[-2:] gt_instances = [] for targets_per_video in targets: _num_instance = len(targets_per_video["instances"][0]) mask_shape = [_num_instance, self.num_frames, h_pad, w_pad] gt_masks_per_video = torch.zeros(mask_shape, dtype=torch.bool, device=self.device) gt_ids_per_video = [] gt_classes_per_video = [] for f_i, targets_per_frame in enumerate(targets_per_video["instances"]): targets_per_frame = targets_per_frame.to(self.device) h, w = targets_per_frame.image_size gt_ids_per_video.append(targets_per_frame.gt_ids[:, None]) gt_classes_per_video.append(targets_per_frame.gt_classes[:, None]) if isinstance(targets_per_frame.gt_masks, BitMasks): gt_masks_per_video[:, f_i, :h, :w] = targets_per_frame.gt_masks.tensor else: # polygon gt_masks_per_video[:, f_i, :h, :w] = targets_per_frame.gt_masks gt_ids_per_video = torch.cat(gt_ids_per_video, dim=1) gt_classes_per_video = torch.cat(gt_classes_per_video, dim=1).max(dim=1)[0] valid_idx = (gt_ids_per_video != -1).any(dim=-1) gt_classes_per_video = gt_classes_per_video[valid_idx] # N, gt_ids_per_video = gt_ids_per_video[valid_idx] # N, num_frames gt_instances.append({"labels": gt_classes_per_video, "ids": gt_ids_per_video}) gt_masks_per_video = gt_masks_per_video[valid_idx].float() # N, num_frames, H, W gt_instances[-1].update({"masks": gt_masks_per_video}) return gt_instances def inference_video(self, pred_cls, pred_masks, img_size, output_height, output_width, first_resize_size): if len(pred_cls) > 0: scores = F.softmax(pred_cls, dim=-1)[:, :-1] labels = torch.arange( self.sem_seg_head.num_classes, device=self.device ).unsqueeze(0).repeat(self.num_queries, 1).flatten(0, 1) # keep top-10 predictions scores_per_image, topk_indices = scores.flatten(0, 1).topk(10, sorted=False) labels_per_image = labels[topk_indices] topk_indices = topk_indices // self.sem_seg_head.num_classes pred_masks = pred_masks[topk_indices] pred_masks = F.interpolate( pred_masks, size=first_resize_size, mode="bilinear", align_corners=False ) pred_masks = pred_masks[:, :, : img_size[0], : img_size[1]] pred_masks = F.interpolate( pred_masks, size=(output_height, output_width), mode="bilinear", align_corners=False ) masks = pred_masks > 0. out_scores = scores_per_image.tolist() out_labels = labels_per_image.tolist() out_masks = [m for m in masks.cpu()] else: out_scores = [] out_labels = [] out_masks = [] video_output = { "image_size": (output_height, output_width), "pred_scores": out_scores, "pred_labels": out_labels, "pred_masks": out_masks, } return video_output @META_ARCH_REGISTRY.register() class DVIS_Plus_online(MinVIS): """ Online version of DVIS, including a segmenter and a referring tracker. """ @configurable def __init__( self, *, backbone: Backbone, sem_seg_head: nn.Module, criterion: nn.Module, num_queries: int, object_mask_threshold: float, overlap_threshold: float, metadata, size_divisibility: int, sem_seg_postprocess_before_inference: bool, pixel_mean: Tuple[float], pixel_std: Tuple[float], # video tracker, num_frames, window_inference, max_num, max_iter_num, window_size, task, # use_cl use_cl, ): """ Args: backbone: a backbone module, must follow detectron2's backbone interface sem_seg_head: a module that predicts semantic segmentation from backbone features criterion: a module that defines the loss num_queries: int, number of queries object_mask_threshold: float, threshold to filter query based on classification score for panoptic segmentation inference overlap_threshold: overlap threshold used in general inference for panoptic segmentation metadata: dataset meta, get `thing` and `stuff` category names for panoptic segmentation inference size_divisibility: Some backbones require the input height and width to be divisible by a specific integer. We can use this to override such requirement. sem_seg_postprocess_before_inference: whether to resize the prediction back to original input size before semantic segmentation inference or after. For high-resolution dataset like Mapillary, resizing predictions before inference will cause OOM error. pixel_mean, pixel_std: list or tuple with #channels element, representing the per-channel mean and std to be used to normalize the input image # video tracker: a tracker module, e.g. ReferringTracker num_frames: number of frames sampled during training window_inference: if the GPU memory is insufficient to predict the entire video at once, inference needs to be performed clip by clip num_class: the categories number of the dataset max_num: the maximum number of instances retained for a video, only used in VIS max_iter_num: the iter nums window_size: the number of images processed by the segmenter at a time task: VIS, VSS or VPS """ super().__init__( backbone=backbone, sem_seg_head=sem_seg_head, criterion=criterion, num_queries=num_queries, object_mask_threshold=object_mask_threshold, overlap_threshold=overlap_threshold, metadata=metadata, size_divisibility=size_divisibility, sem_seg_postprocess_before_inference=sem_seg_postprocess_before_inference, pixel_mean=pixel_mean, pixel_std=pixel_std, # video num_frames=num_frames, window_inference=window_inference, ) # frozen the segmenter for p in self.backbone.parameters(): p.requires_grad_(False) for p in self.sem_seg_head.parameters(): p.requires_grad_(False) self.tracker = tracker self.max_num = max_num self.iter = 0 self.max_iter_num = max_iter_num self.window_size = window_size self.task = task assert self.task in ['vis', 'vss', 'vps'], "Only support vis, vss and vps !" inference_dict = { 'vis': self.inference_video_vis, 'vss': self.inference_video_vss, 'vps': self.inference_video_vps, } self.inference_video_task = inference_dict[self.task] self.use_cl = use_cl @classmethod def from_config(cls, cfg): backbone = build_backbone(cfg) sem_seg_head = build_sem_seg_head(cfg, backbone.output_shape()) # Loss parameters: deep_supervision = cfg.MODEL.MASK_FORMER.DEEP_SUPERVISION no_object_weight = cfg.MODEL.MASK_FORMER.NO_OBJECT_WEIGHT # loss weights class_weight = cfg.MODEL.MASK_FORMER.CLASS_WEIGHT dice_weight = cfg.MODEL.MASK_FORMER.DICE_WEIGHT mask_weight = cfg.MODEL.MASK_FORMER.MASK_WEIGHT # building criterion matcher = VideoHungarianMatcher_Consistent( cost_class=class_weight, cost_mask=mask_weight, cost_dice=dice_weight, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, frames=cfg.INPUT.SAMPLING_FRAME_NUM ) weight_dict = {"loss_ce": class_weight, "loss_mask": mask_weight, "loss_dice": dice_weight} if deep_supervision: dec_layers = cfg.MODEL.MASK_FORMER.DEC_LAYERS aux_weight_dict = {} for i in range(dec_layers - 1): aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()}) weight_dict.update(aux_weight_dict) if cfg.MODEL.TRACKER.USE_CL: weight_dict.update({'loss_reid': 2}) losses = ["labels", "masks"] criterion = VideoSetCriterion( sem_seg_head.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=no_object_weight, losses=losses, num_points=cfg.MODEL.MASK_FORMER.TRAIN_NUM_POINTS, oversample_ratio=cfg.MODEL.MASK_FORMER.OVERSAMPLE_RATIO, importance_sample_ratio=cfg.MODEL.MASK_FORMER.IMPORTANCE_SAMPLE_RATIO, ) if cfg.MODEL.MASK_FORMER.REID_BRANCH: hidden_channel = cfg.MODEL.MASK_FORMER.HIDDEN_DIM * 2 else: hidden_channel = cfg.MODEL.MASK_FORMER.HIDDEN_DIM tracker = ReferringTracker_noiser( hidden_channel=hidden_channel, feedforward_channel=cfg.MODEL.MASK_FORMER.DIM_FEEDFORWARD, num_head=cfg.MODEL.MASK_FORMER.NHEADS, decoder_layer_num=cfg.MODEL.TRACKER.DECODER_LAYERS, noise_mode=cfg.MODEL.TRACKER.NOISE_MODE, noise_ratio=cfg.MODEL.TRACKER.NOISE_RATIO, mask_dim=cfg.MODEL.MASK_FORMER.HIDDEN_DIM, class_num=cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES, ) max_iter_num = cfg.SOLVER.MAX_ITER return { "backbone": backbone, "sem_seg_head": sem_seg_head, "criterion": criterion, "num_queries": cfg.MODEL.MASK_FORMER.NUM_OBJECT_QUERIES, "object_mask_threshold": cfg.MODEL.MASK_FORMER.TEST.OBJECT_MASK_THRESHOLD, "overlap_threshold": cfg.MODEL.MASK_FORMER.TEST.OVERLAP_THRESHOLD, "metadata": MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), "size_divisibility": cfg.MODEL.MASK_FORMER.SIZE_DIVISIBILITY, "sem_seg_postprocess_before_inference": True, "pixel_mean": cfg.MODEL.PIXEL_MEAN, "pixel_std": cfg.MODEL.PIXEL_STD, # video "tracker": tracker, "num_frames": cfg.INPUT.SAMPLING_FRAME_NUM, "window_inference": cfg.MODEL.MASK_FORMER.TEST.WINDOW_INFERENCE, "max_num": cfg.MODEL.MASK_FORMER.TEST.MAX_NUM, "max_iter_num": max_iter_num, "window_size": cfg.MODEL.MASK_FORMER.TEST.WINDOW_SIZE, "task": cfg.MODEL.MASK_FORMER.TEST.TASK, "use_cl": cfg.MODEL.REFINER.USE_CL, } def forward(self, batched_inputs): """ Args: batched_inputs: a list, batched outputs of :class:`DatasetMapper`. Each item in the list contains the inputs for one image. For now, each item in the list is a dict that contains: * "image": Tensor, image in (C, H, W) format. * "instances": per-region ground truth * Other information that's included in the original dicts, such as: "height", "width" (int): the output resolution of the model (may be different from input resolution), used in inference. Returns: dict: For specific task, the dict contains the following keys: * For VIS: "image_size": (output_height, output_width). "pred_scores": score for per instance. "pred_labels": class for per instance. "pred_masks": list[Tensor], bit-masks for per instance, Tensor shape is (t, h, w). "pred_ids": list, query ids for per instance, list length is N. "task": "vis", * For VSS: "image_size": (output_height, output_width). "pred_masks": A Tensor that represents the per-pixel segmentation prediced by the head. The prediction has shape (t, h, w) that represents the category ID for each pixel. "task": "vss". * For VPS: "image_size": (output_height, output_width). "pred_masks": Tensor, shape is (t, h, w), that represents the unique ID for the object which each pixel belong to. "segments_infos": list[dict], info dicts for per object. Info dict including unique ID, category ID and isthing. "pred_ids": list, query ids for per thing and stuff, list length is N. "task": "vps". """ # for running demo on very long videos if 'keep' in batched_inputs[0].keys(): self.keep = batched_inputs[0]['keep'] else: self.keep = False images = [] for video in batched_inputs: for frame in video["image"]: images.append(frame.to(self.device)) images = [(x - self.pixel_mean) / self.pixel_std for x in images] images = ImageList.from_tensors(images, self.size_divisibility) if not self.training and self.window_inference: outputs = self.run_window_inference(images.tensor, window_size=self.window_size) else: self.backbone.eval() self.sem_seg_head.eval() with torch.no_grad(): features = self.backbone(images.tensor) image_outputs = self.sem_seg_head(features) object_labels = self._get_instance_labels(image_outputs['pred_logits']) frame_embds = image_outputs['pred_embds'].clone().detach() # (b, c, t, q) frame_embds_no_norm = image_outputs['pred_embds_without_norm'].clone().detach() # (b, c, t, q) mask_features = image_outputs['mask_features'].clone().detach().unsqueeze(0) del image_outputs['mask_features'] torch.cuda.empty_cache() outputs, indices = self.tracker(frame_embds, mask_features, return_indices=True, resume=self.keep, frame_classes=object_labels, frame_embeds_no_norm=frame_embds_no_norm) image_outputs = self.reset_image_output_order(image_outputs, indices) if self.training: targets = self.prepare_targets(batched_inputs, images) # use the segmenter prediction results to guide the matching process during early training phase image_outputs, outputs, targets = self.frame_decoder_loss_reshape( outputs, targets, image_outputs=image_outputs ) if self.iter < self.max_iter_num // 2: losses, reference_match_result = self.criterion(outputs, targets, matcher_outputs=image_outputs, ret_match_result=True) else: losses, reference_match_result = self.criterion(outputs, targets, matcher_outputs=None, ret_match_result=True) if self.use_cl: losses_cl = self.get_cl_loss_ref(outputs, reference_match_result) losses.update(losses_cl) self.iter += 1 for k in list(losses.keys()): if k in self.criterion.weight_dict: losses[k] *= self.criterion.weight_dict[k] else: # remove this loss if not specified in `weight_dict` losses.pop(k) return losses else: outputs = self.post_processing(outputs) mask_cls_results = outputs["pred_logits"] mask_pred_results = outputs["pred_masks"] pred_ids = outputs["ids"] mask_cls_result = mask_cls_results[0] mask_pred_result = mask_pred_results[0] pred_id = pred_ids[0] first_resize_size = (images.tensor.shape[-2], images.tensor.shape[-1]) input_per_image = batched_inputs[0] image_size = images.image_sizes[0] # image size without padding after data augmentation height = input_per_image.get("height", image_size[0]) # raw image size before data augmentation width = input_per_image.get("width", image_size[1]) return retry_if_cuda_oom(self.inference_video_task)( mask_cls_result, mask_pred_result, image_size, height, width, first_resize_size, pred_id ) def _get_instance_labels(self, pred_logits): # b, t, q, c pred_logits = pred_logits[0] # (t, q, c) scores = F.softmax(pred_logits, dim=-1) labels = torch.argmax(scores, dim=2) # (t, q) labels[labels == pred_logits.size(2) - 1] = -1 return labels def frame_decoder_loss_reshape(self, outputs, targets, image_outputs=None): outputs['pred_masks'] = einops.rearrange(outputs['pred_masks'], 'b q t h w -> (b t) q () h w') outputs['pred_logits'] = einops.rearrange(outputs['pred_logits'], 'b t q c -> (b t) q c') outputs['pred_references'] = einops.rearrange(outputs['pred_references'], 'b c t q -> (b t) q c') if image_outputs is not None: image_outputs['pred_masks'] = einops.rearrange(image_outputs['pred_masks'], 'b q t h w -> (b t) q () h w') image_outputs['pred_logits'] = einops.rearrange(image_outputs['pred_logits'], 'b t q c -> (b t) q c') if 'aux_outputs' in outputs: for i in range(len(outputs['aux_outputs'])): outputs['aux_outputs'][i]['pred_masks'] = einops.rearrange( outputs['aux_outputs'][i]['pred_masks'], 'b q t h w -> (b t) q () h w' ) outputs['aux_outputs'][i]['pred_logits'] = einops.rearrange( outputs['aux_outputs'][i]['pred_logits'], 'b t q c -> (b t) q c' ) gt_instances = [] for targets_per_video in targets: num_labeled_frames = targets_per_video['ids'].shape[1] for f in range(num_labeled_frames): labels = targets_per_video['labels'] ids = targets_per_video['ids'][:, [f]] masks = targets_per_video['masks'][:, [f], :, :] gt_instances.append({"labels": labels, "ids": ids, "masks": masks}) return image_outputs, outputs, gt_instances def reset_image_output_order(self, output, indices): """ in order to maintain consistency between the initial query and the guided results (segmenter prediction) :param output: segmenter prediction results (image-level segmentation results) :param indices: matched indicates :return: reordered outputs """ # pred_keys, (b, c, t, q) indices = torch.Tensor(indices).to(torch.int64) # (t, q) frame_indices = torch.range(0, indices.shape[0] - 1).to(indices).unsqueeze(1).repeat(1, indices.shape[1]) # pred_masks, shape is (b, q, t, h, w) output['pred_masks'][0] = output['pred_masks'][0][indices, frame_indices].transpose(0, 1) # pred logits, shape is (b, t, q, c) output['pred_logits'][0] = output['pred_logits'][0][frame_indices, indices] return output def post_processing(self, outputs, aux_logits=None): """ average the class logits and append query ids """ pred_logits = outputs['pred_logits'] pred_logits = pred_logits[0] # (t, q, c) out_logits = torch.mean(pred_logits, dim=0).unsqueeze(0) if aux_logits is not None: aux_logits = aux_logits[0] aux_logits = torch.mean(aux_logits, dim=0) # (q, c) outputs['pred_logits'] = out_logits outputs['ids'] = [torch.arange(0, outputs['pred_masks'].size(1))] if aux_logits is not None: return outputs, aux_logits return outputs def run_window_inference(self, images_tensor, window_size=30): iters = len(images_tensor) // window_size if len(images_tensor) % window_size != 0: iters += 1 out_list = [] for i in range(iters): start_idx = i * window_size end_idx = (i+1) * window_size # segmeter inference features = self.backbone(images_tensor[start_idx:end_idx]) out = self.sem_seg_head(features) # remove unnecessary variables to save GPU memory del features['res2'], features['res3'], features['res4'], features['res5'] for j in range(len(out['aux_outputs'])): del out['aux_outputs'][j]['pred_masks'], out['aux_outputs'][j]['pred_logits'] # referring tracker inference frame_embds = out['pred_embds'] # (b, c, t, q) frame_embds_no_norm = out['pred_embds_without_norm'] mask_features = out['mask_features'].unsqueeze(0) if i != 0 or self.keep: track_out = self.tracker(frame_embds, mask_features, resume=True, frame_embeds_no_norm=frame_embds_no_norm) else: track_out = self.tracker(frame_embds, mask_features, frame_embeds_no_norm=frame_embds_no_norm) # remove unnecessary variables to save GPU memory del mask_features for j in range(len(track_out['aux_outputs'])): del track_out['aux_outputs'][j]['pred_masks'], track_out['aux_outputs'][j]['pred_logits'] track_out['pred_logits'] = track_out['pred_logits'].to(torch.float32).detach().cpu() track_out['pred_masks'] = track_out['pred_masks'].to(torch.float32).detach().cpu() track_out['pred_embds'] = track_out['pred_embds'].to(torch.float32).detach().cpu() # track_out['pred_logits'] = track_out['pred_logits'].detach() # track_out['pred_masks'] = track_out['pred_masks'].detach() # track_out['pred_embds'] = track_out['pred_embds'].detach() out_list.append(track_out) # merge outputs outputs = {} outputs['pred_logits'] = torch.cat([x['pred_logits'] for x in out_list], dim=1) outputs['pred_masks'] = torch.cat([x['pred_masks'] for x in out_list], dim=2) outputs['pred_embds'] = torch.cat([x['pred_embds'] for x in out_list], dim=2) return outputs def inference_video_vis( self, pred_cls, pred_masks, img_size, output_height, output_width, first_resize_size, pred_id, aux_pred_cls=None, ): if len(pred_cls) > 0: scores = F.softmax(pred_cls, dim=-1)[:, :-1] if aux_pred_cls is not None: aux_pred_cls = F.softmax(aux_pred_cls, dim=-1)[:, :-1] scores = torch.maximum(scores, aux_pred_cls.to(scores)) labels = torch.arange( self.sem_seg_head.num_classes, device=self.device ).unsqueeze(0).repeat(self.num_queries, 1).flatten(0, 1) # keep top-K predictions scores_per_image, topk_indices = scores.flatten(0, 1).topk(self.max_num, sorted=False) labels_per_image = labels[topk_indices] topk_indices = topk_indices // self.sem_seg_head.num_classes pred_masks = pred_masks[topk_indices] pred_ids = pred_id[topk_indices] # interpolation to original image size pred_masks = F.interpolate( pred_masks, size=first_resize_size, mode="bilinear", align_corners=False ) pred_masks = pred_masks[:, :, : img_size[0], : img_size[1]] pred_masks = F.interpolate( pred_masks, size=(output_height, output_width), mode="bilinear", align_corners=False ) masks = pred_masks > 0. del pred_masks out_scores = scores_per_image.tolist() out_labels = labels_per_image.tolist() out_ids = pred_ids.tolist() out_masks = [m for m in masks.cpu()] else: out_scores = [] out_labels = [] out_masks = [] out_ids = [] video_output = { "image_size": (output_height, output_width), "pred_scores": out_scores, "pred_labels": out_labels, "pred_masks": out_masks, "pred_ids": out_ids, "task": "vis", } return video_output def inference_video_vps( self, pred_cls, pred_masks, img_size, output_height, output_width, first_resize_size, pred_id, aux_pred_cls=None, ): pred_cls = F.softmax(pred_cls, dim=-1) if aux_pred_cls is not None: aux_pred_cls = F.softmax(aux_pred_cls, dim=-1)[:, :-1] pred_cls[:, :-1] = torch.maximum(pred_cls[:, :-1], aux_pred_cls.to(pred_cls)) mask_pred = pred_masks scores, labels = pred_cls.max(-1) # filter out the background prediction keep = labels.ne(self.sem_seg_head.num_classes) & (scores > self.object_mask_threshold) cur_scores = scores[keep] cur_classes = labels[keep] cur_ids = pred_id[keep] cur_masks = mask_pred[keep] # interpolation to original image size cur_masks = F.interpolate( cur_masks, size=first_resize_size, mode="bilinear", align_corners=False ) cur_masks = cur_masks[:, :, :img_size[0], :img_size[1]].sigmoid() cur_masks = F.interpolate( cur_masks, size=(output_height, output_width), mode="bilinear", align_corners=False ) cur_prob_masks = cur_scores.view(-1, 1, 1, 1).to(cur_masks.device) * cur_masks # initial panoptic_seg and segments infos h, w = cur_masks.shape[-2:] panoptic_seg = torch.zeros((cur_masks.size(1), h, w), dtype=torch.int32, device=cur_masks.device) segments_infos = [] out_ids = [] current_segment_id = 0 if cur_masks.shape[0] == 0: # We didn't detect any mask return { "image_size": (output_height, output_width), "pred_masks": panoptic_seg.cpu(), "segments_infos": segments_infos, "pred_ids": out_ids, "task": "vps", } else: # take argmax cur_mask_ids = cur_prob_masks.argmax(0) # (t, h, w) stuff_memory_list = {} for k in range(cur_classes.shape[0]): pred_class = cur_classes[k].item() isthing = pred_class < len(self.metadata.thing_dataset_id_to_contiguous_id) # filter out the unstable segmentation results mask_area = (cur_mask_ids == k).sum().item() original_area = (cur_masks[k] >= 0.5).sum().item() mask = (cur_mask_ids == k) & (cur_masks[k] >= 0.5) if mask_area > 0 and original_area > 0 and mask.sum().item() > 0: if mask_area / original_area < self.overlap_threshold: continue # merge stuff regions if not isthing: if int(pred_class) in stuff_memory_list.keys(): panoptic_seg[mask] = stuff_memory_list[int(pred_class)] continue else: stuff_memory_list[int(pred_class)] = current_segment_id + 1 current_segment_id += 1 panoptic_seg[mask] = current_segment_id segments_infos.append( { "id": current_segment_id, "isthing": bool(isthing), "category_id": int(pred_class), } ) out_ids.append(cur_ids[k]) return { "image_size": (output_height, output_width), "pred_masks": panoptic_seg.cpu(), "segments_infos": segments_infos, "pred_ids": out_ids, "task": "vps", } def inference_video_vss( self, pred_cls, pred_masks, img_size, output_height, output_width, first_resize_size, pred_id, aux_pred_cls=None, ): mask_cls = F.softmax(pred_cls, dim=-1)[..., :-1] if aux_pred_cls is not None: aux_pred_cls = F.softmax(aux_pred_cls, dim=-1)[..., :-1] mask_cls = torch.maximum(mask_cls, aux_pred_cls.to(mask_cls)) mask_pred = pred_masks # interpolation to original image size cur_masks = F.interpolate( mask_pred, size=first_resize_size, mode="bilinear", align_corners=False ) cur_masks = cur_masks[:, :, :img_size[0], :img_size[1]].sigmoid() cur_masks = F.interpolate( cur_masks, size=(output_height, output_width), mode="bilinear", align_corners=False ) semseg = torch.einsum("qc,qthw->cthw", mask_cls, cur_masks) sem_score, sem_mask = semseg.max(0) sem_mask = sem_mask return { "image_size": (output_height, output_width), "pred_masks": sem_mask.cpu(), "task": "vss", } def get_cl_loss_ref(self, outputs, referecne_match_result): references = outputs['pred_references'] # t q c # per frame contrastive_items = [] for i in range(references.size(0)): if i == 0: continue frame_reference = references[i] # (q, c) frame_reference_ = references[i - 1] # (q, c) if i != references.size(0) - 1: frame_reference_next = references[i + 1] else: frame_reference_next = None frame_ref_gt_indices = referecne_match_result[i] gt2ref = {} for i_ref, i_gt in zip(frame_ref_gt_indices[0], frame_ref_gt_indices[1]): gt2ref[i_gt.item()] = i_ref.item() # per instance for i_gt in gt2ref.keys(): i_ref = gt2ref[i_gt] anchor_embeds = frame_reference[[i_ref]] pos_embeds = frame_reference_[[i_ref]] neg_range = list(range(0, i_ref)) + list(range(i_ref + 1, frame_reference.size(0))) neg_embeds = frame_reference_[neg_range] num_positive = pos_embeds.shape[0] # concate pos and neg to get whole constractive samples pos_neg_embedding = torch.cat( [pos_embeds, neg_embeds], dim=0) # generate label, pos is 1, neg is 0 pos_neg_label = pos_neg_embedding.new_zeros((pos_neg_embedding.shape[0],), dtype=torch.int64) # noqa pos_neg_label[:num_positive] = 1. # dot product dot_product = torch.einsum( 'ac,kc->ak', [pos_neg_embedding, anchor_embeds]) aux_normalize_pos_neg_embedding = nn.functional.normalize( pos_neg_embedding, dim=1) aux_normalize_anchor_embedding = nn.functional.normalize( anchor_embeds, dim=1) aux_cosine_similarity = torch.einsum('ac,kc->ak', [aux_normalize_pos_neg_embedding, aux_normalize_anchor_embedding]) contrastive_items.append({ 'dot_product': dot_product, 'cosine_similarity': aux_cosine_similarity, 'label': pos_neg_label}) if frame_reference_next is not None: pos_embeds = frame_reference_next[[i_ref]] neg_range = list(range(0, i_ref)) + list(range(i_ref + 1, frame_reference.size(0))) neg_embeds = frame_reference_next[neg_range] num_positive = pos_embeds.shape[0] # concate pos and neg to get whole constractive samples pos_neg_embedding = torch.cat( [pos_embeds, neg_embeds], dim=0) # generate label, pos is 1, neg is 0 pos_neg_label = pos_neg_embedding.new_zeros((pos_neg_embedding.shape[0],), dtype=torch.int64) # noqa pos_neg_label[:num_positive] = 1. # dot product dot_product = torch.einsum( 'ac,kc->ak', [pos_neg_embedding, anchor_embeds]) aux_normalize_pos_neg_embedding = nn.functional.normalize( pos_neg_embedding, dim=1) aux_normalize_anchor_embedding = nn.functional.normalize( anchor_embeds, dim=1) aux_cosine_similarity = torch.einsum('ac,kc->ak', [aux_normalize_pos_neg_embedding, aux_normalize_anchor_embedding]) contrastive_items.append({ 'dot_product': dot_product, 'cosine_similarity': aux_cosine_similarity, 'label': pos_neg_label})
losses = loss_reid(contrastive_items, outputs)
6
2023-11-14 10:55:11+00:00
16k
ej0cl6/TextEE
TextEE/models/Ampere/model_copyutils.py
[ { "identifier": "PrefixGenBartForConditionalGeneration", "path": "TextEE/models/Ampere/prefix_gen_bart.py", "snippet": "class PrefixGenBartForConditionalGeneration(BartPretrainedModel):\n base_model_prefix = \"model\"\n _keys_to_ignore_on_load_missing = [r\"final_logits_bias\", r\"lm_head\\.weight...
import torch import torch.nn as nn import ipdb, logging, re from .prefix_gen_bart import PrefixGenBartForConditionalGeneration from transformers.models.bart.modeling_bart import shift_tokens_right from transformers import T5ForConditionalGeneration, T5Tokenizer from transformers import BartForConditionalGeneration, AutoConfig, AutoModel from .AMRBART.AMRBartTokenizer import AMRBartTokenizer, AMRRobertaTokenizer from torch.nn import NLLLoss from transformers.modeling_outputs import Seq2SeqLMOutput
13,838
# lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias # batch x dec_sequence_length x vocab_size if input_ids is None: input_ids = self._cache_input_ids # batch x sequence_length try: assert input_ids.size(0) == outputs.encoder_last_hidden_state.size(0) # batch size except: ipdb.set_trace() cross_attentions = outputs.cross_attentions # This is in tuple format, and each of them is of shape (batch_size, num_heads, dec_sequence_length, enc_sequence_length). # This are the attentions weights of the decoder’s cross-attention layer, after the attention softmax. # This is for investigating why regularizer works. cross_attentions = torch.stack(cross_attentions[-1:], dim=1) # TODO: we can change the used layer here. cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate layers cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate heads # Now, "cross attentions" is of shape (batch_size, dec_sequence_length, enc_sequence_length) # For cases on using cross_prefix, we need to remove the prefix attention length if self.config.use_cross_prefix: cross_attentions = cross_attentions[:, :, self.config.prefix_length:] copy_words = input_ids.unsqueeze(1).repeat(1, cross_attentions.size(1), 1) #(batch, dec_sequence_length, enc_sequence_length) lm_logits = torch.scatter_add(outputs[0].new_zeros(outputs[0].size(0), outputs[0].size(1), self.config.vocab_size), 2, copy_words, cross_attentions) eps = 1e-7 lm_logits = torch.log(lm_logits+eps) masked_lm_loss = None if labels is not None: loss_fct = NLLLoss(ignore_index=-100) masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (lm_logits,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return Seq2SeqLMOutput( loss=masked_lm_loss, logits=lm_logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) #### # For AMR Integration #### class AMRT5(nn.Module): def __init__(self, config): super().__init__() self.config = config self.model = (T5ForConditionalGeneration.from_pretrained(config.AMR_model_path)).encoder.cuda() self.max_graph_len = 512 # self.max_sent_len = 90 self.tokenizer = T5Tokenizer.from_pretrained('t5-base') def get_encoder_output(self, stripped_graphs): # Form encodings and tokenize input_text = ['%s' % graph for graph in stripped_graphs] input_encodings = self.tokenizer.batch_encode_plus(input_text, padding=True, truncation=True, max_length=self.max_graph_len, return_overflowing_tokens=True) # # Check if any graphs were truncated (requires return_overflowing_tokens=True) clip = [l > 0 for l in input_encodings['num_truncated_tokens']] if any(clip): print("overlength") # Convert to tensors input_ids = torch.LongTensor(input_encodings['input_ids']).cuda() attention_mask = torch.LongTensor(input_encodings['attention_mask']).cuda() # Get encoder outputs [batch_size, max_graph_length, 768] encoder_output = self.model(input_ids=input_ids, attention_mask=attention_mask) return encoder_output['last_hidden_state'], attention_mask class AMRBart(nn.Module): def __init__(self, config): super().__init__() self.config = config self.model_config = AutoConfig.from_pretrained(config.AMR_model_path) self.tokenizer = AMRBartTokenizer.from_pretrained(config.AMR_model_path) self.model = BartForConditionalGeneration.from_pretrained(config.AMR_model_path).cuda() self.max_graph_len = 512 self.model.resize_token_embeddings(len(self.tokenizer)) self.model = self.model.model.encoder def get_encoder_output(self, stripped_graphs): input_text = ['%s' % graph for graph in stripped_graphs] input_encodings = [ [self.tokenizer.bos_token_id, self.tokenizer.mask_token_id, self.tokenizer.eos_token_id] + [self.tokenizer.amr_bos_token_id] + self.tokenizer.tokenize_amr(itm.split())[:self.max_graph_len -5] + [self.tokenizer.amr_eos_token_id] for itm in input_text] # padding max_batch_length = max(len(x) for x in input_encodings) attention_mask = [[1]*len(x) + [0]*(max_batch_length - len(x)) for x in input_encodings] input_ids = [x + [self.tokenizer.pad_token_id]*(max_batch_length - len(x)) for x in input_encodings] # truncation if max_batch_length > self.max_graph_len: input_ids = [x[:self.max_graph_len] for x in input_ids] attention_mask = [x[:self.max_graph_len] for x in attention_mask] print("overlength") # Convert to tensors input_ids = torch.LongTensor(input_ids).cuda() attention_mask = torch.LongTensor(attention_mask).cuda() # Get encoder outputs [batch_size, max_graph_length, 1024] encoder_output = self.model(input_ids=input_ids, attention_mask=attention_mask) return encoder_output['last_hidden_state'], attention_mask class AMRRoberta(nn.Module): def __init__(self, config): super().__init__() self.config = config self.model_config = AutoConfig.from_pretrained(config.AMR_model_path)
# from transformers import BartForConditionalGeneration class CopyBartWithReg(PrefixGenBartForConditionalGeneration): def __init__(self, config): super().__init__(config) # If extra model/module, we need to initialize the module here. self.linear_copy = nn.Linear(self.config.d_model, 1) def forward( self, input_ids=None, prefix=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: if use_cache: logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.") use_cache = False if decoder_input_ids is None and decoder_inputs_embeds is None: print('decoder_input_shifting') decoder_input_ids = shift_tokens_right( labels, self.config.pad_token_id, self.config.decoder_start_token_id ) outputs = self.model( input_ids, prefix=prefix, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, encoder_outputs=encoder_outputs, decoder_attention_mask=decoder_attention_mask, head_mask=head_mask, decoder_head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias # batch x dec_sequence_length x vocab_size if input_ids is None: input_ids = self._cache_input_ids # batch x sequence_length try: assert input_ids.size(0) == outputs.encoder_last_hidden_state.size(0) # batch size except: ipdb.set_trace() cross_attentions = outputs.cross_attentions # This is in tuple format, and each of them is of shape (batch_size, num_heads, dec_sequence_length, enc_sequence_length). # This are the attentions weights of the decoder’s cross-attention layer, after the attention softmax. cross_attentions = torch.stack(cross_attentions[-1:], dim=1) # TODO: we can change the used layer here. cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate layers cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate heads # Now, "cross attentions" is of shape (batch_size, dec_sequence_length, enc_sequence_length) # For cases on using cross_prefix, we need to remove the prefix attention length if self.config.use_cross_prefix: cross_attentions = cross_attentions[:, :, self.config.prefix_length:] # Probability of copying p_ori = torch.sigmoid(self.linear_copy(outputs[0])) # Merge distribution original_word_pro = torch.softmax(lm_logits, dim=-1) * p_ori #[batch, dec_sequence_length, vocab_size] copy_words = input_ids.unsqueeze(1).repeat(1, cross_attentions.size(1), 1) #(batch, dec_sequence_length, enc_sequence_length) input_len = input_ids.size(1) lm_logits = torch.scatter_add(original_word_pro, 2, copy_words, cross_attentions[:,:,:input_len]*(1-p_ori)) eps = 1e-7 lm_logits = torch.log(lm_logits+eps) masked_lm_loss = None if labels is not None: # loss_fct = CrossEntropyLoss() # # masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) # masked_lm_loss = loss_fct(torch.flatten(cross_attentions, start_dim=0, end_dim=1), labels.view(-1)) loss_fct = NLLLoss(ignore_index=-100) masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) # add regularizer to p_ori masked_lm_loss += torch.mean(p_ori) if not return_dict: output = (lm_logits,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return Seq2SeqLMOutput( loss=masked_lm_loss, logits=lm_logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) class CopyBart(PrefixGenBartForConditionalGeneration): def __init__(self, config): super().__init__(config) # If extra model/module, we need to initialize the module here. self.linear_copy = nn.Linear(self.config.d_model, 1) def forward( self, input_ids=None, prefix=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: if use_cache: logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.") use_cache = False if decoder_input_ids is None and decoder_inputs_embeds is None: print('decoder_input_shifting') decoder_input_ids = shift_tokens_right( labels, self.config.pad_token_id, self.config.decoder_start_token_id ) outputs = self.model( input_ids, prefix=prefix, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, encoder_outputs=encoder_outputs, decoder_attention_mask=decoder_attention_mask, head_mask=head_mask, decoder_head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias # batch x dec_sequence_length x vocab_size if input_ids is None: input_ids = self._cache_input_ids # batch x sequence_length try: assert input_ids.size(0) == outputs.encoder_last_hidden_state.size(0) # batch size except: ipdb.set_trace() cross_attentions = outputs.cross_attentions # This is in tuple format, and each of them is of shape (batch_size, num_heads, dec_sequence_length, enc_sequence_length). # This are the attentions weights of the decoder’s cross-attention layer, after the attention softmax. cross_attentions = torch.stack(cross_attentions[-1:], dim=1) # TODO: we can change the used layer here. cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate layers cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate heads # Now, "cross attentions" is of shape (batch_size, dec_sequence_length, enc_sequence_length) # For cases on using cross_prefix, we need to remove the prefix attention length if self.config.use_cross_prefix: cross_attentions = cross_attentions[:, :, self.config.prefix_length:] # Probability of copying p_ori = torch.sigmoid(self.linear_copy(outputs[0])) # Merge distribution original_word_pro = torch.softmax(lm_logits, dim=-1) * p_ori #[batch, dec_sequence_length, vocab_size] copy_words = input_ids.unsqueeze(1).repeat(1, cross_attentions.size(1), 1) #(batch, dec_sequence_length, enc_sequence_length) input_len = input_ids.size(1) lm_logits = torch.scatter_add(original_word_pro, 2, copy_words, cross_attentions[:,:,:input_len]*(1-p_ori)) eps = 1e-7 lm_logits = torch.log(lm_logits+eps) masked_lm_loss = None if labels is not None: # loss_fct = CrossEntropyLoss() # # masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) # masked_lm_loss = loss_fct(torch.flatten(cross_attentions, start_dim=0, end_dim=1), labels.view(-1)) loss_fct = NLLLoss(ignore_index=-100) masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (lm_logits,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return Seq2SeqLMOutput( loss=masked_lm_loss, logits=lm_logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) class PureCopyBart(PrefixGenBartForConditionalGeneration): def __init__(self, config): super().__init__(config) def forward( self, input_ids=None, prefix=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): return_dict = return_dict if return_dict is not None else self.config.use_return_dict if labels is not None: if use_cache: logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.") use_cache = False if decoder_input_ids is None and decoder_inputs_embeds is None: print('decoder_input_shifting') decoder_input_ids = shift_tokens_right( labels, self.config.pad_token_id, self.config.decoder_start_token_id ) outputs = self.model( input_ids, prefix=prefix, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, encoder_outputs=encoder_outputs, decoder_attention_mask=decoder_attention_mask, head_mask=head_mask, decoder_head_mask=decoder_head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) # lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias # batch x dec_sequence_length x vocab_size if input_ids is None: input_ids = self._cache_input_ids # batch x sequence_length try: assert input_ids.size(0) == outputs.encoder_last_hidden_state.size(0) # batch size except: ipdb.set_trace() cross_attentions = outputs.cross_attentions # This is in tuple format, and each of them is of shape (batch_size, num_heads, dec_sequence_length, enc_sequence_length). # This are the attentions weights of the decoder’s cross-attention layer, after the attention softmax. # This is for investigating why regularizer works. cross_attentions = torch.stack(cross_attentions[-1:], dim=1) # TODO: we can change the used layer here. cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate layers cross_attentions = torch.mean(cross_attentions, dim=1) # aggregate heads # Now, "cross attentions" is of shape (batch_size, dec_sequence_length, enc_sequence_length) # For cases on using cross_prefix, we need to remove the prefix attention length if self.config.use_cross_prefix: cross_attentions = cross_attentions[:, :, self.config.prefix_length:] copy_words = input_ids.unsqueeze(1).repeat(1, cross_attentions.size(1), 1) #(batch, dec_sequence_length, enc_sequence_length) lm_logits = torch.scatter_add(outputs[0].new_zeros(outputs[0].size(0), outputs[0].size(1), self.config.vocab_size), 2, copy_words, cross_attentions) eps = 1e-7 lm_logits = torch.log(lm_logits+eps) masked_lm_loss = None if labels is not None: loss_fct = NLLLoss(ignore_index=-100) masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1)) if not return_dict: output = (lm_logits,) + outputs[1:] return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output return Seq2SeqLMOutput( loss=masked_lm_loss, logits=lm_logits, past_key_values=outputs.past_key_values, decoder_hidden_states=outputs.decoder_hidden_states, decoder_attentions=outputs.decoder_attentions, cross_attentions=outputs.cross_attentions, encoder_last_hidden_state=outputs.encoder_last_hidden_state, encoder_hidden_states=outputs.encoder_hidden_states, encoder_attentions=outputs.encoder_attentions, ) #### # For AMR Integration #### class AMRT5(nn.Module): def __init__(self, config): super().__init__() self.config = config self.model = (T5ForConditionalGeneration.from_pretrained(config.AMR_model_path)).encoder.cuda() self.max_graph_len = 512 # self.max_sent_len = 90 self.tokenizer = T5Tokenizer.from_pretrained('t5-base') def get_encoder_output(self, stripped_graphs): # Form encodings and tokenize input_text = ['%s' % graph for graph in stripped_graphs] input_encodings = self.tokenizer.batch_encode_plus(input_text, padding=True, truncation=True, max_length=self.max_graph_len, return_overflowing_tokens=True) # # Check if any graphs were truncated (requires return_overflowing_tokens=True) clip = [l > 0 for l in input_encodings['num_truncated_tokens']] if any(clip): print("overlength") # Convert to tensors input_ids = torch.LongTensor(input_encodings['input_ids']).cuda() attention_mask = torch.LongTensor(input_encodings['attention_mask']).cuda() # Get encoder outputs [batch_size, max_graph_length, 768] encoder_output = self.model(input_ids=input_ids, attention_mask=attention_mask) return encoder_output['last_hidden_state'], attention_mask class AMRBart(nn.Module): def __init__(self, config): super().__init__() self.config = config self.model_config = AutoConfig.from_pretrained(config.AMR_model_path) self.tokenizer = AMRBartTokenizer.from_pretrained(config.AMR_model_path) self.model = BartForConditionalGeneration.from_pretrained(config.AMR_model_path).cuda() self.max_graph_len = 512 self.model.resize_token_embeddings(len(self.tokenizer)) self.model = self.model.model.encoder def get_encoder_output(self, stripped_graphs): input_text = ['%s' % graph for graph in stripped_graphs] input_encodings = [ [self.tokenizer.bos_token_id, self.tokenizer.mask_token_id, self.tokenizer.eos_token_id] + [self.tokenizer.amr_bos_token_id] + self.tokenizer.tokenize_amr(itm.split())[:self.max_graph_len -5] + [self.tokenizer.amr_eos_token_id] for itm in input_text] # padding max_batch_length = max(len(x) for x in input_encodings) attention_mask = [[1]*len(x) + [0]*(max_batch_length - len(x)) for x in input_encodings] input_ids = [x + [self.tokenizer.pad_token_id]*(max_batch_length - len(x)) for x in input_encodings] # truncation if max_batch_length > self.max_graph_len: input_ids = [x[:self.max_graph_len] for x in input_ids] attention_mask = [x[:self.max_graph_len] for x in attention_mask] print("overlength") # Convert to tensors input_ids = torch.LongTensor(input_ids).cuda() attention_mask = torch.LongTensor(attention_mask).cuda() # Get encoder outputs [batch_size, max_graph_length, 1024] encoder_output = self.model(input_ids=input_ids, attention_mask=attention_mask) return encoder_output['last_hidden_state'], attention_mask class AMRRoberta(nn.Module): def __init__(self, config): super().__init__() self.config = config self.model_config = AutoConfig.from_pretrained(config.AMR_model_path)
self.tokenizer = AMRRobertaTokenizer.from_pretrained(config.AMR_model_path)
2
2023-11-15 21:32:56+00:00
16k
ahayler/s4c
scripts/images/gen_img_custom.py
[ { "identifier": "BTSNet", "path": "models/bts/model/models_bts.py", "snippet": "class BTSNet(torch.nn.Module):\n def __init__(self, conf):\n super().__init__()\n\n self.d_min = conf.get(\"z_near\")\n self.d_max = conf.get(\"z_far\")\n\n self.learn_empty = conf.get(\"learn_...
import sys import matplotlib.pyplot as plt import torch from argparse import ArgumentParser from scripts.inference_setup import * from hydra import compose, initialize from omegaconf import OmegaConf from models.bts.model import BTSNet, ImageRaySampler from models.common.render import NeRFRenderer from utils.array_operations import map_fn, unsqueezer from utils.plotting import color_tensor, color_segmentation_tensor
13,253
dtype=torch.float32).view(1, 4, 4) proj = torch.tensor([ [ 0.7849, 0.0000, -0.0312, 0], [ 0.0000, 2.9391, 0.2701, 0], [ 0.0000, 0.0000, 1.0000, 0], [ 0.0000, 0.0000, 0.0000, 1], ], dtype=torch.float32).view(1, 4, 4) elif model == "KITTI-Raw": resolution = (192, 640) config_path = "exp_kitti_raw" cp_path = Path(f"out/kitti_raw/pretrained") cp_name = cp_path.name cp_path = next(cp_path.glob("training*.pt")) out_path = Path(f"media/img_custom/kitti-raw_{cp_name}") cam_incl_adjust = None proj = torch.tensor([ [ 1.1619, 0.0000, -0.0184, 0], [ 0.0000, 3.8482, -0.0781, 0], [ 0.0000, 0.0000, 1.0000, 0], [ 0.0000, 0.0000, 0.0000, 1] ], dtype=torch.float32).view(1, 4, 4) elif model == "RealEstate10K": resolution = (256, 384) config_path = "exp_re10k" cp_path = Path(f"out/re10k/pretrained") cp_name = cp_path.name cp_path = next(cp_path.glob("training*.pt")) out_path = Path(f"media/img_custom/re10k_{cp_name}") cam_incl_adjust = None proj = torch.tensor([ [1.0056, 0.0000, 0.0000, 0], [0.0000, 1.7877, 0.0000, 0], [0.0000, 0.0000, 1.0000, 0], [0.0000, 0.0000, 0.0000, 1], ], dtype=torch.float32).view(1, 4, 4) else: raise ValueError(f"Invalid model: {model}") initialize(version_base=None, config_path="../../configs", job_name="gen_imgs") config = compose(config_name=config_path, overrides=[]) print("Setup folders") out_path.mkdir(exist_ok=True, parents=True) print('Loading checkpoint') cp = torch.load(cp_path, map_location=device) config = dict(config) if "segmentation_mode" in config.keys(): config["model_conf"] = dict(config["model_conf"]) config["model_conf"]["segmentation_mode"] = config["segmentation_mode"] net = BTSNet(config["model_conf"]) renderer = NeRFRenderer.from_conf(config["renderer"]) renderer = renderer.bind_parallel(net, gpus=None).eval() renderer.renderer.n_coarse = 64 renderer.renderer.lindisp = True class _Wrapper(nn.Module): def __init__(self): super().__init__() self.renderer = renderer _wrapper = _Wrapper() _wrapper.load_state_dict(cp["model"], strict=True) renderer.to(device) renderer.eval() ray_sampler = ImageRaySampler(config["model_conf"]["z_near"], config["model_conf"]["z_far"], *resolution, norm_dir=False) print("Load input image") assert os.path.exists(args.img) img = cv2.cvtColor(cv2.imread(args.img), cv2.COLOR_BGR2RGB).astype(np.float32) / 255. img = cv2.resize(img, (resolution[1], resolution[0])) img = torch.tensor(img).permute(2, 0, 1).unsqueeze(0).unsqueeze(0).to(device) * 2 - 1 img_name = os.path.basename(args.img).split(".")[0] with torch.no_grad(): poses = torch.eye(4).view(1, 1, 4, 4).to(device) projs = proj.view(1, 1, 4, 4).to(device)[:, :, :3, :3] net.encode(img, projs, poses, ids_encoder=[0], ids_render=[0]) net.set_scale(0) img_save = img[0, 0].permute(1, 2, 0).cpu() * .5 + .5 _, depth = render_poses(renderer, ray_sampler, poses[:, :1], projs[:, :1]) if s_profile: profile = render_profile(net, cam_incl_adjust) else: profile = None if s_profile_seg: profile_seg = render_segmentation_profile(net, cam_incl_adjust) else: profile_seg = None if s_profile_depth: profile_depth = render_depth_profile(net, cam_incl_adjust) else: None depth = ((1 / depth - 1 / config["model_conf"]["z_far"]) / (1 / config["model_conf"]["z_near"] - 1 / config["model_conf"]["z_far"])).clamp(0, 1) print(f"Generated " + str(out_path / f"{img_name}")) if s_img: save_plot(img_save.numpy(), str(out_path / f"{img_name}_in.png"), dry_run=dry_run) if s_depth:
sys.path.append(".") def main(): parser = ArgumentParser("Generate density field from single image.") parser.add_argument("--img", "-i", required=True, help="Path to the image.") parser.add_argument("--plot", "-p", action="store_true", help="Plot rather than save images.") parser.add_argument("--model", "-m", help="Path to the model you want to use.", required=True) args = parser.parse_args() s_img = True s_depth = True s_profile = True s_seg = True s_profile_seg = True s_profile_depth = True dry_run = args.plot cp_path = Path(args.model) model = "KITTI-360" if model == "KITTI-360": resolution = (192, 640) config_path = "exp_kitti_360" cp_name = cp_path.name cp_path = next(cp_path.glob("training*.pt")) out_path = Path(f"media/img_custom/kitti-360_{cp_name}") cam_incl_adjust = torch.tensor( [[1.0000000, 0.0000000, 0.0000000, 0], [0.0000000, 0.9961947, -0.0871557, 0], [0.0000000, 0.0871557, 0.9961947, 0], [0.0000000, 000000000, 0.0000000, 1] ], dtype=torch.float32).view(1, 4, 4) proj = torch.tensor([ [ 0.7849, 0.0000, -0.0312, 0], [ 0.0000, 2.9391, 0.2701, 0], [ 0.0000, 0.0000, 1.0000, 0], [ 0.0000, 0.0000, 0.0000, 1], ], dtype=torch.float32).view(1, 4, 4) elif model == "KITTI-Raw": resolution = (192, 640) config_path = "exp_kitti_raw" cp_path = Path(f"out/kitti_raw/pretrained") cp_name = cp_path.name cp_path = next(cp_path.glob("training*.pt")) out_path = Path(f"media/img_custom/kitti-raw_{cp_name}") cam_incl_adjust = None proj = torch.tensor([ [ 1.1619, 0.0000, -0.0184, 0], [ 0.0000, 3.8482, -0.0781, 0], [ 0.0000, 0.0000, 1.0000, 0], [ 0.0000, 0.0000, 0.0000, 1] ], dtype=torch.float32).view(1, 4, 4) elif model == "RealEstate10K": resolution = (256, 384) config_path = "exp_re10k" cp_path = Path(f"out/re10k/pretrained") cp_name = cp_path.name cp_path = next(cp_path.glob("training*.pt")) out_path = Path(f"media/img_custom/re10k_{cp_name}") cam_incl_adjust = None proj = torch.tensor([ [1.0056, 0.0000, 0.0000, 0], [0.0000, 1.7877, 0.0000, 0], [0.0000, 0.0000, 1.0000, 0], [0.0000, 0.0000, 0.0000, 1], ], dtype=torch.float32).view(1, 4, 4) else: raise ValueError(f"Invalid model: {model}") initialize(version_base=None, config_path="../../configs", job_name="gen_imgs") config = compose(config_name=config_path, overrides=[]) print("Setup folders") out_path.mkdir(exist_ok=True, parents=True) print('Loading checkpoint') cp = torch.load(cp_path, map_location=device) config = dict(config) if "segmentation_mode" in config.keys(): config["model_conf"] = dict(config["model_conf"]) config["model_conf"]["segmentation_mode"] = config["segmentation_mode"] net = BTSNet(config["model_conf"]) renderer = NeRFRenderer.from_conf(config["renderer"]) renderer = renderer.bind_parallel(net, gpus=None).eval() renderer.renderer.n_coarse = 64 renderer.renderer.lindisp = True class _Wrapper(nn.Module): def __init__(self): super().__init__() self.renderer = renderer _wrapper = _Wrapper() _wrapper.load_state_dict(cp["model"], strict=True) renderer.to(device) renderer.eval() ray_sampler = ImageRaySampler(config["model_conf"]["z_near"], config["model_conf"]["z_far"], *resolution, norm_dir=False) print("Load input image") assert os.path.exists(args.img) img = cv2.cvtColor(cv2.imread(args.img), cv2.COLOR_BGR2RGB).astype(np.float32) / 255. img = cv2.resize(img, (resolution[1], resolution[0])) img = torch.tensor(img).permute(2, 0, 1).unsqueeze(0).unsqueeze(0).to(device) * 2 - 1 img_name = os.path.basename(args.img).split(".")[0] with torch.no_grad(): poses = torch.eye(4).view(1, 1, 4, 4).to(device) projs = proj.view(1, 1, 4, 4).to(device)[:, :, :3, :3] net.encode(img, projs, poses, ids_encoder=[0], ids_render=[0]) net.set_scale(0) img_save = img[0, 0].permute(1, 2, 0).cpu() * .5 + .5 _, depth = render_poses(renderer, ray_sampler, poses[:, :1], projs[:, :1]) if s_profile: profile = render_profile(net, cam_incl_adjust) else: profile = None if s_profile_seg: profile_seg = render_segmentation_profile(net, cam_incl_adjust) else: profile_seg = None if s_profile_depth: profile_depth = render_depth_profile(net, cam_incl_adjust) else: None depth = ((1 / depth - 1 / config["model_conf"]["z_far"]) / (1 / config["model_conf"]["z_near"] - 1 / config["model_conf"]["z_far"])).clamp(0, 1) print(f"Generated " + str(out_path / f"{img_name}")) if s_img: save_plot(img_save.numpy(), str(out_path / f"{img_name}_in.png"), dry_run=dry_run) if s_depth:
save_plot(color_tensor(depth, "magma", norm=True).numpy(), str(out_path / f"{img_name}_depth.png"), dry_run=dry_run)
4
2023-11-12 21:53:27+00:00
16k
TCLResearchEurope/torch-dag
torch_dag_algorithms/pruning/module_multipliers.py
[ { "identifier": "structured_modules", "path": "torch_dag/structured_modules.py", "snippet": "ACTIVATION_MODULES_T = Union[\n nn.ReLU,\n nn.ReLU6,\n nn.SiLU,\n nn.Softmax,\n nn.Sigmoid,\n nn.Hardswish,\n nn.Hardsigmoid,\n nn.GELU,\n nn.LeakyReLU,\n nn.ELU,\n nn.Tanh,\n ...
import logging import torch from typing import List, Tuple, Dict, Union from torch_dag import structured_modules as smodules from torch_dag.core.dag_module import DagModule from torch_dag.core.dag_module import InputVertex, InnerVertex, Vertex from torch_dag_algorithms.pruning.commons import PASS_THROUGH_CHANNELS_CLASSES from torch_dag_algorithms.pruning.commons import is_source, get_orbits_dict, is_linear_source, is_depthwise_conv from torch_dag_algorithms.pruning.modules import OrbitModule from torch_dag_timm_plugin.module_multipliers import compute_timm_average_num_channels, \ CUSTOM_AVERAGE_CHANNELS_TIMM_CLASSES
11,830
# # Copyright © TCL Research Europe. All rights reserved. # logger = logging.getLogger(__name__) PASS_THROUGH_MULTIPLIER_CLASSES = PASS_THROUGH_CHANNELS_CLASSES def shape_to_float(shape, device, dim=1): return torch.tensor(shape[dim], device=device).to(torch.float32) def compute_elementwise_op_average_channels(average_number_input_channels: List[List[torch.Tensor]], ): average_number_input_channels = [e for e in average_number_input_channels if e is not None] if len(average_number_input_channels) == 0: return None return [torch.max(torch.stack([e[0] for e in average_number_input_channels]))] def compute_average_num_channels( vertex: InnerVertex, average_number_input_channels: List[List[torch.Tensor]], orbits_dict: Dict[str, OrbitModule], forward_dict: Dict[Vertex, Union[torch.Tensor, List[torch.Tensor]]] ) -> Union[List[torch.Tensor], None]: device = forward_dict[vertex.dag_module.input_vertices[0]].device if isinstance(vertex.module, PASS_THROUGH_MULTIPLIER_CLASSES): return [average_number_input_channels[0][0]] if is_source(vertex.module): if vertex.orbit is not None: orbit_module = orbits_dict[vertex.orbit] return [orbit_module.compute_average_number_of_output_channels()] else: if is_linear_source(vertex.module): return [shape_to_float(forward_dict[vertex].shape, dim=-1, device=device)] else: return [shape_to_float(forward_dict[vertex].shape, device=device)]
# # Copyright © TCL Research Europe. All rights reserved. # logger = logging.getLogger(__name__) PASS_THROUGH_MULTIPLIER_CLASSES = PASS_THROUGH_CHANNELS_CLASSES def shape_to_float(shape, device, dim=1): return torch.tensor(shape[dim], device=device).to(torch.float32) def compute_elementwise_op_average_channels(average_number_input_channels: List[List[torch.Tensor]], ): average_number_input_channels = [e for e in average_number_input_channels if e is not None] if len(average_number_input_channels) == 0: return None return [torch.max(torch.stack([e[0] for e in average_number_input_channels]))] def compute_average_num_channels( vertex: InnerVertex, average_number_input_channels: List[List[torch.Tensor]], orbits_dict: Dict[str, OrbitModule], forward_dict: Dict[Vertex, Union[torch.Tensor, List[torch.Tensor]]] ) -> Union[List[torch.Tensor], None]: device = forward_dict[vertex.dag_module.input_vertices[0]].device if isinstance(vertex.module, PASS_THROUGH_MULTIPLIER_CLASSES): return [average_number_input_channels[0][0]] if is_source(vertex.module): if vertex.orbit is not None: orbit_module = orbits_dict[vertex.orbit] return [orbit_module.compute_average_number_of_output_channels()] else: if is_linear_source(vertex.module): return [shape_to_float(forward_dict[vertex].shape, dim=-1, device=device)] else: return [shape_to_float(forward_dict[vertex].shape, device=device)]
elif is_depthwise_conv(vertex.module):
9
2023-11-17 15:36:44+00:00
16k
newcastleuniversity/DISPEL
dispel/providers/generic/preprocessing.py
[ { "identifier": "Level", "path": "dispel/data/levels.py", "snippet": "class Level(Epoch):\n \"\"\"An entity to separate sub-task inside each test (Levels).\n\n FIXME: DOC\n\n Attributes\n ----------\n context\n Contextual information about the level\n measure_set\n A :cla...
from typing import Iterable, List, Optional, Set, Tuple from dispel.data.levels import Level from dispel.data.raw import DEFAULT_COLUMNS, GRAVITY_COLUMNS from dispel.processing import ProcessingStep from dispel.processing.level import ( DefaultLevelFilter, LevelFilter, LevelFilterType, LevelIdFilter, ProcessingStepGroup, ) from dispel.processing.modalities import LimbModality, SensorModality from dispel.processing.transform import Apply from dispel.providers.generic.sensor import ( ComputeGravityRotationMatrices, Resample, RotateSensorWithGravityRotationMatrices, SetTimestampIndex, TransformGyroscope, TransformUserAcceleration, ) from dispel.signal.filter import butterworth_high_pass_filter, savgol_filter from dispel.signal.sensor import check_amplitude, detrend_signal
12,329
max_amplitude: float, min_amplitude: float, columns: Optional[List[str]] = None, ): self.data_set_id = data_set_id self.columns = columns self.max_amplitude = max_amplitude self.min_amplitude = min_amplitude def repr(self): """Get representation of the filter.""" return f"only {self.data_set_id} signal with acceptable amplitude>" def filter(self, levels: Iterable[Level]) -> Set[Level]: """Filter levels with acceptable signal amplitude.""" def _amplitude_filter(level: Level): if level.has_raw_data_set(self.data_set_id): data = level.get_raw_data_set(self.data_set_id).data if self.columns: data = data[self.columns] return check_amplitude(data, self.min_amplitude, self.max_amplitude) return True return set(filter(_amplitude_filter, levels)) class RotateFrame(ProcessingStepGroup): r"""A changing referential preprocessing step according a given data set. Parameters ---------- data_set_id The data set id on which the transformation is to be performed. gravity_data_set_id The dataset id containing the gravity components. frame The new desired frame. columns The columns onto which the resampling steps have to be applied. kwargs Additional arguments that are passed to the :meth:`~dispel.processing.core.ProcessingStep.process` function of each step. This allows to provide additional values, such as placeholder values in value definitions to the actual processing function. """ def __init__( self, data_set_id: str, gravity_data_set_id: str, frame: Tuple[int, int, int], columns: Optional[List[str]] = None, **kwargs, ): columns = columns or DEFAULT_COLUMNS steps: List[ProcessingStep] = [ ComputeGravityRotationMatrices( gravity_data_set_id, frame, storage_error="ignore" ), RotateSensorWithGravityRotationMatrices( data_set_id, columns, ), ] super().__init__( steps, **kwargs, ) class PreprocessingSteps(ProcessingStepGroup): r"""A changing referential preprocessing step according a given data set. Parameters ---------- data_set_id The data set id on which the transformation is to be performed. limb The modality regarding if the exercise is upper or lower limb. sensor The modality regarding the type of sensor either accelerometer or gyroscope. resample_freq Optionally, the frequency to which resample the data during the resample step. columns Optionally, the columns on which the preprocessing steps need to be applied. level_filter An optional :class:`~dispel.processing.level.LevelFilter` to determine the levels to be transformed. If no filter is provided, all levels will be transformed. The ``level_filter`` also accepts :class:`str`, :class:`~dispel.data.core.LevelId`\ s and lists of either and passes them to a :class:`~dispel.processing.level.LevelIdFilter` for convenience. """ def __init__( self, data_set_id: str, limb: LimbModality, sensor: SensorModality, resample_freq: Optional[float] = None, columns: Optional[List[str]] = None, level_filter: LevelFilterType = DefaultLevelFilter(), ): columns = columns or DEFAULT_COLUMNS extra_columns = [] if not isinstance(level_filter, LevelFilter): level_filter = LevelIdFilter(level_filter) # Need to be computed even if only gyroscope signals are preprocessed to make # sure `acc` data set is available to compute gravity rotation matrices steps: List[ProcessingStep] = [ TransformUserAcceleration(storage_error="ignore"), TransformGyroscope(storage_error="overwrite"), ] if sensor == SensorModality.ACCELEROMETER: data_set_id = "acc"
"""Core functionalities to preprocess signal data.""" class FilterSensorNoise(Apply): r"""Apply a filter that will remove any sensor noise into a given dataset. This filter is a Savitzky-Golay one. Parameters ---------- data_set_id The data set id on which the transformation is to be performed ('accelerometer', 'gyroscope'). columns The columns onto which the filtering step has to be applied. kwargs Additional arguments that are passed to the :meth:`~dispel.processing.core.ProcessingStep.process` function of each step. This allows to provide additional values, such as placeholder values in value definitions to the actual processing function. Notes ----- The Savitzky-Golay is tuned as in [Martinez et. al. 2012]_ to remove sensor noise and to smooth the signal. The windows size is thus set up to 41 points and the filter is of order-3. """ def __init__(self, data_set_id: str, columns: Optional[List[str]] = None, **kwargs): columns = columns or DEFAULT_COLUMNS super().__init__( data_set_id=data_set_id, method=savgol_filter, method_kwargs=dict(window=41, order=3), columns=columns, new_data_set_id=f"{data_set_id}_svgf", drop_nan=True, **kwargs, ) class FilterPhysiologicalNoise(Apply): r"""Apply a filter that will remove any physiological noise into a dataset. This filter is a butterworth high-pass one. Parameters ---------- data_set_id The data set id on which the transformation is to be performed ('accelerometer', 'gyroscope'). columns The columns onto which the filtering step has to be applied. sampling_frequency Optional the initial sampling frequency. kwargs Additional arguments that are passed to the :meth:`~dispel.processing.core.ProcessingStep.process` function of each step. This allows to provide additional values, such as placeholder values in value definitions to the actual processing function. Notes ----- The Butterwoth highpass filter is tuned as in [Martinez et. al. 2012]_ to remove physiological noise. The cut-off of is of 0.2HZ which is the standard breath frequency. .. [Martinez et. al. 2012] MARTINEZ-MENDEZ, Rigoberto, SEKINE, Masaki, et TAMURA, Toshiyo. Postural sway parameters using a triaxial accelerometer: comparing elderly and young healthy adults. Computer methods in biomechanics and biomedical engineering, 2012, vol. 15, no 9, p. 899-910. """ def __init__( self, data_set_id: str, columns: Optional[List[str]] = None, sampling_frequency: Optional[float] = None, **kwargs, ): columns = columns or DEFAULT_COLUMNS super().__init__( data_set_id=data_set_id, method=butterworth_high_pass_filter, method_kwargs=dict( order=2, cutoff=0.3, freq=sampling_frequency, zero_phase=True ), columns=columns, new_data_set_id=f"{data_set_id}_bhpf", drop_nan=True, **kwargs, ) class Detrend(Apply): r"""A detrending preprocessing step according a given data set. Parameters ---------- data_set_id The data set id on which the transformation is to be performed ('accelerometer', 'gyroscope'). columns The columns onto which the detrending steps have to be applied. kwargs Additional arguments that are passed to the :meth:`~dispel.processing.core.ProcessingStep.process` function of each step. This allows to provide additional values, such as placeholder values in value definitions to the actual processing function. """ def __init__(self, data_set_id: str, columns: Optional[List[str]] = None, **kwargs): columns = columns or DEFAULT_COLUMNS super().__init__( data_set_id=data_set_id, method=detrend_signal, columns=columns, new_data_set_id=f"{data_set_id}_detrend", drop_nan=True, **kwargs, ) class AmplitudeRangeFilter(LevelFilter): r"""Filter aberrant signal amplitude. Parameters ---------- data_set_id The data set id on which the transformation is to be performed ('accelerometer', 'gyroscope'). max_amplitude A float which is the maximum expected amplitude values. min_amplitude A float which is the minimum expected amplitude values. columns The columns onto which the detrending steps have to be applied. """ def __init__( self, data_set_id: str, max_amplitude: float, min_amplitude: float, columns: Optional[List[str]] = None, ): self.data_set_id = data_set_id self.columns = columns self.max_amplitude = max_amplitude self.min_amplitude = min_amplitude def repr(self): """Get representation of the filter.""" return f"only {self.data_set_id} signal with acceptable amplitude>" def filter(self, levels: Iterable[Level]) -> Set[Level]: """Filter levels with acceptable signal amplitude.""" def _amplitude_filter(level: Level): if level.has_raw_data_set(self.data_set_id): data = level.get_raw_data_set(self.data_set_id).data if self.columns: data = data[self.columns] return check_amplitude(data, self.min_amplitude, self.max_amplitude) return True return set(filter(_amplitude_filter, levels)) class RotateFrame(ProcessingStepGroup): r"""A changing referential preprocessing step according a given data set. Parameters ---------- data_set_id The data set id on which the transformation is to be performed. gravity_data_set_id The dataset id containing the gravity components. frame The new desired frame. columns The columns onto which the resampling steps have to be applied. kwargs Additional arguments that are passed to the :meth:`~dispel.processing.core.ProcessingStep.process` function of each step. This allows to provide additional values, such as placeholder values in value definitions to the actual processing function. """ def __init__( self, data_set_id: str, gravity_data_set_id: str, frame: Tuple[int, int, int], columns: Optional[List[str]] = None, **kwargs, ): columns = columns or DEFAULT_COLUMNS steps: List[ProcessingStep] = [ ComputeGravityRotationMatrices( gravity_data_set_id, frame, storage_error="ignore" ), RotateSensorWithGravityRotationMatrices( data_set_id, columns, ), ] super().__init__( steps, **kwargs, ) class PreprocessingSteps(ProcessingStepGroup): r"""A changing referential preprocessing step according a given data set. Parameters ---------- data_set_id The data set id on which the transformation is to be performed. limb The modality regarding if the exercise is upper or lower limb. sensor The modality regarding the type of sensor either accelerometer or gyroscope. resample_freq Optionally, the frequency to which resample the data during the resample step. columns Optionally, the columns on which the preprocessing steps need to be applied. level_filter An optional :class:`~dispel.processing.level.LevelFilter` to determine the levels to be transformed. If no filter is provided, all levels will be transformed. The ``level_filter`` also accepts :class:`str`, :class:`~dispel.data.core.LevelId`\ s and lists of either and passes them to a :class:`~dispel.processing.level.LevelIdFilter` for convenience. """ def __init__( self, data_set_id: str, limb: LimbModality, sensor: SensorModality, resample_freq: Optional[float] = None, columns: Optional[List[str]] = None, level_filter: LevelFilterType = DefaultLevelFilter(), ): columns = columns or DEFAULT_COLUMNS extra_columns = [] if not isinstance(level_filter, LevelFilter): level_filter = LevelIdFilter(level_filter) # Need to be computed even if only gyroscope signals are preprocessed to make # sure `acc` data set is available to compute gravity rotation matrices steps: List[ProcessingStep] = [ TransformUserAcceleration(storage_error="ignore"), TransformGyroscope(storage_error="overwrite"), ] if sensor == SensorModality.ACCELEROMETER: data_set_id = "acc"
extra_columns = GRAVITY_COLUMNS
2
2023-11-14 10:06:46+00:00
16k
believethehype/nostrdvm
nostr_dvm/dvm.py
[ { "identifier": "EventDefinitions", "path": "nostr_dvm/utils/definitions.py", "snippet": "class EventDefinitions:\n KIND_DM = 4\n KIND_ZAP = 9735\n KIND_ANNOUNCEMENT = 31990\n KIND_NIP94_METADATA = 1063\n KIND_FEEDBACK = 7000\n KIND_NIP90_EXTRACT_TEXT = 5000\n KIND_NIP90_RESULT_EXTR...
import json import os import subprocess import time from datetime import timedelta from sys import platform from nostr_sdk import PublicKey, Keys, Client, Tag, Event, EventBuilder, Filter, HandleNotification, Timestamp, \ init_logger, LogLevel, Options, nip04_encrypt, ClientSigner from nostr_dvm.utils.definitions import EventDefinitions, RequiredJobToWatch, JobToWatch from nostr_dvm.utils.dvmconfig import DVMConfig from nostr_dvm.utils.admin_utils import admin_make_database_updates, AdminConfig from nostr_dvm.utils.backend_utils import get_amount_per_task, check_task_is_supported, get_task from nostr_dvm.utils.database_utils import create_sql_table, get_or_add_user, update_user_balance, update_sql_table from nostr_dvm.utils.mediasource_utils import input_data_file_duration from nostr_dvm.utils.nostr_utils import get_event_by_id, get_referenced_event_by_id, send_event, check_and_decrypt_tags from nostr_dvm.utils.output_utils import build_status_reaction from nostr_dvm.utils.zap_utils import check_bolt11_ln_bits_is_paid, create_bolt11_ln_bits, parse_zap_event_tags, \ parse_amount_from_bolt11_invoice, zaprequest, pay_bolt11_ln_bits, create_bolt11_lud16 from nostr_dvm.utils.cashu_utils import redeem_cashu
12,633
except Exception as e: print(e) bolt11 = None elif dvm_config.LN_ADDRESS != "": try: bolt11, payment_hash = create_bolt11_lud16(dvm_config.LN_ADDRESS, amount) except Exception as e: print(e) bolt11 = None if not any(x.event == original_event for x in self.job_list): self.job_list.append( JobToWatch(event=original_event, timestamp=original_event.created_at().as_secs(), amount=amount, is_paid=is_paid, status=status, result="", is_processed=False, bolt11=bolt11, payment_hash=payment_hash, expires=expires)) # print(str(self.job_list)) if (status == "payment-required" or status == "payment-rejected" or ( status == "processing" and not is_paid) or (status == "success" and not is_paid)): if dvm_config.LNBITS_INVOICE_KEY != "": amount_tag = Tag.parse(["amount", str(amount * 1000), bolt11]) else: amount_tag = Tag.parse(["amount", str(amount * 1000)]) # to millisats reply_tags.append(amount_tag) if encrypted: content_tag = Tag.parse(["content", reaction]) reply_tags.append(content_tag) str_tags = [] for element in reply_tags: str_tags.append(element.as_vec()) content = json.dumps(str_tags) content = nip04_encrypt(self.keys.secret_key(), PublicKey.from_hex(original_event.pubkey().to_hex()), content) reply_tags = encryption_tags else: content = reaction keys = Keys.from_sk_str(dvm_config.PRIVATE_KEY) reaction_event = EventBuilder(EventDefinitions.KIND_FEEDBACK, str(content), reply_tags).to_event(keys) send_event(reaction_event, client=self.client, dvm_config=self.dvm_config) print("[" + self.dvm_config.NIP89.NAME + "]" + ": Sent Kind " + str( EventDefinitions.KIND_FEEDBACK) + " Reaction: " + status + " " + reaction_event.as_json()) return reaction_event.as_json() def do_work(job_event, amount): if ((EventDefinitions.KIND_NIP90_EXTRACT_TEXT <= job_event.kind() <= EventDefinitions.KIND_NIP90_GENERIC) or job_event.kind() == EventDefinitions.KIND_DM): task = get_task(job_event, client=self.client, dvm_config=self.dvm_config) for dvm in self.dvm_config.SUPPORTED_DVMS: result = "" try: if task == dvm.TASK: request_form = dvm.create_request_from_nostr_event(job_event, self.client, self.dvm_config) if dvm_config.USE_OWN_VENV: python_location = "/bin/python" if platform == "win32": python_location = "/Scripts/python" python_bin = (r'cache/venvs/' + os.path.basename(dvm_config.SCRIPT).split(".py")[0] + python_location) retcode = subprocess.call([python_bin, dvm_config.SCRIPT, '--request', json.dumps(request_form), '--identifier', dvm_config.IDENTIFIER, '--output', 'output.txt']) print("Finished processing, loading data..") with open(os.path.abspath('output.txt')) as f: resultall = f.readlines() for line in resultall: if line != '\n': result += line os.remove(os.path.abspath('output.txt')) assert not result.startswith("Error:") print(result) else: # Some components might have issues with running code in otuside venv. # We install locally in these cases for now result = dvm.process(request_form) try: post_processed = dvm.post_process(str(result), job_event) send_nostr_reply_event(post_processed, job_event.as_json()) except Exception as e: send_job_status_reaction(job_event, "error", content=str(e), dvm_config=self.dvm_config) except Exception as e: # we could send the exception here to the user, but maybe that's not a good idea after all. send_job_status_reaction(job_event, "error", content=result, dvm_config=self.dvm_config) # Zapping back the user on error if amount > 0 and self.dvm_config.LNBITS_ADMIN_KEY != "": user = get_or_add_user(self.dvm_config.DB, job_event.pubkey().to_hex(), client=self.client, config=self.dvm_config) print(user.lud16 + " " + str(amount)) bolt11 = zaprequest(user.lud16, amount, "Couldn't finish job, returning sats", job_event, user.npub, self.keys, self.dvm_config.RELAY_LIST, zaptype="private") if bolt11 is None: print("Receiver has no Lightning address, can't zap back.") return try: payment_hash = pay_bolt11_ln_bits(bolt11, self.dvm_config) except Exception as e: print(e) return self.client.handle_notifications(NotificationHandler()) while True: for job in self.job_list: if job.bolt11 != "" and job.payment_hash != "" and not job.is_paid:
use_logger = False if use_logger: init_logger(LogLevel.DEBUG) class DVM: dvm_config: DVMConfig admin_config: AdminConfig keys: Keys client: Client job_list: list jobs_on_hold_list: list def __init__(self, dvm_config, admin_config=None): self.dvm_config = dvm_config self.admin_config = admin_config self.keys = Keys.from_sk_str(dvm_config.PRIVATE_KEY) wait_for_send = True skip_disconnected_relays = True opts = (Options().wait_for_send(wait_for_send).send_timeout(timedelta(seconds=self.dvm_config.RELAY_TIMEOUT)) .skip_disconnected_relays(skip_disconnected_relays)) signer = ClientSigner.keys(self.keys) self.client = Client.with_opts(signer,opts) self.job_list = [] self.jobs_on_hold_list = [] pk = self.keys.public_key() print("Nostr DVM public key: " + str(pk.to_bech32()) + " Hex: " + str(pk.to_hex()) + " Supported DVM tasks: " + ', '.join(p.NAME + ":" + p.TASK for p in self.dvm_config.SUPPORTED_DVMS) + "\n") for relay in self.dvm_config.RELAY_LIST: self.client.add_relay(relay) self.client.connect() zap_filter = Filter().pubkey(pk).kinds([EventDefinitions.KIND_ZAP]).since(Timestamp.now()) kinds = [EventDefinitions.KIND_NIP90_GENERIC] for dvm in self.dvm_config.SUPPORTED_DVMS: if dvm.KIND not in kinds: kinds.append(dvm.KIND) dvm_filter = (Filter().kinds(kinds).since(Timestamp.now())) self.client.subscribe([dvm_filter, zap_filter]) create_sql_table(self.dvm_config.DB) admin_make_database_updates(adminconfig=self.admin_config, dvmconfig=self.dvm_config, client=self.client) class NotificationHandler(HandleNotification): client = self.client dvm_config = self.dvm_config keys = self.keys def handle(self, relay_url, nostr_event): if EventDefinitions.KIND_NIP90_EXTRACT_TEXT <= nostr_event.kind() <= EventDefinitions.KIND_NIP90_GENERIC: handle_nip90_job_event(nostr_event) elif nostr_event.kind() == EventDefinitions.KIND_ZAP: handle_zap(nostr_event) def handle_msg(self, relay_url, msg): return def handle_nip90_job_event(nip90_event): nip90_event = check_and_decrypt_tags(nip90_event, self.dvm_config) if nip90_event is None: return user = get_or_add_user(self.dvm_config.DB, nip90_event.pubkey().to_hex(), client=self.client, config=self.dvm_config) cashu = "" p_tag_str = "" for tag in nip90_event.tags(): if tag.as_vec()[0] == "cashu": cashu = tag.as_vec()[1] elif tag.as_vec()[0] == "p": p_tag_str = tag.as_vec()[1] task_supported, task = check_task_is_supported(nip90_event, client=self.client, config=self.dvm_config) if user.isblacklisted: send_job_status_reaction(nip90_event, "error", client=self.client, dvm_config=self.dvm_config) print("[" + self.dvm_config.NIP89.NAME + "] Request by blacklisted user, skipped") elif task_supported: print("[" + self.dvm_config.NIP89.NAME + "] Received new Request: " + task + " from " + user.name) duration = input_data_file_duration(nip90_event, dvm_config=self.dvm_config, client=self.client) amount = get_amount_per_task(task, self.dvm_config, duration) if amount is None: return task_is_free = False for dvm in self.dvm_config.SUPPORTED_DVMS: if dvm.TASK == task and dvm.FIX_COST == 0 and dvm.PER_UNIT_COST == 0: task_is_free = True cashu_redeemed = False if cashu != "": print(cashu) cashu_redeemed, cashu_message, redeem_amount, fees = redeem_cashu(cashu, self.dvm_config, self.client, int(amount)) print(cashu_message) if cashu_message != "success": send_job_status_reaction(nip90_event, "error", False, amount, self.client, cashu_message, self.dvm_config) return # if user is whitelisted or task is free, just do the job if (user.iswhitelisted or task_is_free or cashu_redeemed) and (p_tag_str == "" or p_tag_str == self.dvm_config.PUBLIC_KEY): print( "[" + self.dvm_config.NIP89.NAME + "] Free task or Whitelisted for task " + task + ". Starting processing..") send_job_status_reaction(nip90_event, "processing", True, 0, client=self.client, dvm_config=self.dvm_config) # when we reimburse users on error make sure to not send anything if it was free if user.iswhitelisted or task_is_free: amount = 0 do_work(nip90_event, amount) # if task is directed to us via p tag and user has balance, do the job and update balance elif p_tag_str == self.dvm_config.PUBLIC_KEY and user.balance >= int(amount): balance = max(user.balance - int(amount), 0) update_sql_table(db=self.dvm_config.DB, npub=user.npub, balance=balance, iswhitelisted=user.iswhitelisted, isblacklisted=user.isblacklisted, nip05=user.nip05, lud16=user.lud16, name=user.name, lastactive=Timestamp.now().as_secs()) print( "[" + self.dvm_config.NIP89.NAME + "] Using user's balance for task: " + task + ". Starting processing.. New balance is: " + str(balance)) send_job_status_reaction(nip90_event, "processing", True, 0, client=self.client, dvm_config=self.dvm_config) do_work(nip90_event, amount) # else send a payment required event to user elif p_tag_str == "" or p_tag_str == self.dvm_config.PUBLIC_KEY: bid = 0 for tag in nip90_event.tags(): if tag.as_vec()[0] == 'bid': bid = int(tag.as_vec()[1]) print( "[" + self.dvm_config.NIP89.NAME + "] Payment required: New Nostr " + task + " Job event: " + nip90_event.as_json()) if bid > 0: bid_offer = int(bid / 1000) if bid_offer >= int(amount): send_job_status_reaction(nip90_event, "payment-required", False, int(amount), # bid_offer client=self.client, dvm_config=self.dvm_config) else: # If there is no bid, just request server rate from user print( "[" + self.dvm_config.NIP89.NAME + "] Requesting payment for Event: " + nip90_event.id().to_hex()) send_job_status_reaction(nip90_event, "payment-required", False, int(amount), client=self.client, dvm_config=self.dvm_config) else: print("[" + self.dvm_config.NIP89.NAME + "] Job addressed to someone else, skipping..") # else: # print("[" + self.dvm_config.NIP89.NAME + "] Task " + task + " not supported on this DVM, skipping..") def handle_zap(zap_event): try: invoice_amount, zapped_event, sender, message, anon = parse_zap_event_tags(zap_event, self.keys, self.dvm_config.NIP89.NAME, self.client, self.dvm_config) user = get_or_add_user(db=self.dvm_config.DB, npub=sender, client=self.client, config=self.dvm_config) if zapped_event is not None: if zapped_event.kind() == EventDefinitions.KIND_FEEDBACK: amount = 0 job_event = None p_tag_str = "" for tag in zapped_event.tags(): if tag.as_vec()[0] == 'amount': amount = int(float(tag.as_vec()[1]) / 1000) elif tag.as_vec()[0] == 'e': job_event = get_event_by_id(tag.as_vec()[1], client=self.client, config=self.dvm_config) if job_event is not None: job_event = check_and_decrypt_tags(job_event, self.dvm_config) if job_event is None: return else: return # if a reaction by us got zapped task_supported, task = check_task_is_supported(job_event, client=self.client, config=self.dvm_config) if job_event is not None and task_supported: print("Zap received for NIP90 task: " + str(invoice_amount) + " Sats from " + str( user.name)) if amount <= invoice_amount: print("[" + self.dvm_config.NIP89.NAME + "] Payment-request fulfilled...") send_job_status_reaction(job_event, "processing", client=self.client, dvm_config=self.dvm_config) indices = [i for i, x in enumerate(self.job_list) if x.event == job_event] index = -1 if len(indices) > 0: index = indices[0] if index > -1: if self.job_list[index].is_processed: # If payment-required appears a processing self.job_list[index].is_paid = True check_and_return_event(self.job_list[index].result, job_event) elif not (self.job_list[index]).is_processed: # If payment-required appears before processing self.job_list.pop(index) print("Starting work...") do_work(job_event, invoice_amount) else: print("Job not in List, but starting work...") do_work(job_event, invoice_amount) else: send_job_status_reaction(job_event, "payment-rejected", False, invoice_amount, client=self.client, dvm_config=self.dvm_config) print("[" + self.dvm_config.NIP89.NAME + "] Invoice was not paid sufficiently") elif zapped_event.kind() in EventDefinitions.ANY_RESULT: print("[" + self.dvm_config.NIP89.NAME + "] " "Someone zapped the result of an exisiting Task. Nice") elif not anon: print("[" + self.dvm_config.NIP89.NAME + "] Note Zap received for DVM balance: " + str(invoice_amount) + " Sats from " + str(user.name)) update_user_balance(self.dvm_config.DB, sender, invoice_amount, client=self.client, config=self.dvm_config) # a regular note elif not anon: print("[" + self.dvm_config.NIP89.NAME + "] Profile Zap received for DVM balance: " + str(invoice_amount) + " Sats from " + str(user.name)) update_user_balance(self.dvm_config.DB, sender, invoice_amount, client=self.client, config=self.dvm_config) except Exception as e: print("[" + self.dvm_config.NIP89.NAME + "] Error during content decryption: " + str(e)) def check_event_has_not_unfinished_job_input(nevent, append, client, dvmconfig): task_supported, task = check_task_is_supported(nevent, client, config=dvmconfig) if not task_supported: return False for tag in nevent.tags(): if tag.as_vec()[0] == 'i': if len(tag.as_vec()) < 3: print("Job Event missing/malformed i tag, skipping..") return False else: input = tag.as_vec()[1] input_type = tag.as_vec()[2] if input_type == "job": evt = get_referenced_event_by_id(event_id=input, client=client, kinds=EventDefinitions.ANY_RESULT, dvm_config=dvmconfig) if evt is None: if append: job_ = RequiredJobToWatch(event=nevent, timestamp=Timestamp.now().as_secs()) self.jobs_on_hold_list.append(job_) send_job_status_reaction(nevent, "chain-scheduled", True, 0, client=client, dvm_config=dvmconfig) return False else: return True def check_and_return_event(data, original_event: Event): amount = 0 for x in self.job_list: if x.event == original_event: is_paid = x.is_paid amount = x.amount x.result = data x.is_processed = True if self.dvm_config.SHOW_RESULT_BEFORE_PAYMENT and not is_paid: send_nostr_reply_event(data, original_event.as_json()) send_job_status_reaction(original_event, "success", amount, dvm_config=self.dvm_config, ) # or payment-required, or both? elif not self.dvm_config.SHOW_RESULT_BEFORE_PAYMENT and not is_paid: send_job_status_reaction(original_event, "success", amount, dvm_config=self.dvm_config, ) # or payment-required, or both? if self.dvm_config.SHOW_RESULT_BEFORE_PAYMENT and is_paid: self.job_list.remove(x) elif not self.dvm_config.SHOW_RESULT_BEFORE_PAYMENT and is_paid: self.job_list.remove(x) send_nostr_reply_event(data, original_event.as_json()) break task = get_task(original_event, self.client, self.dvm_config) for dvm in self.dvm_config.SUPPORTED_DVMS: if task == dvm.TASK: try: post_processed = dvm.post_process(data, original_event) send_nostr_reply_event(post_processed, original_event.as_json()) except Exception as e: # Zapping back by error in post-processing is a risk for the DVM because work has been done, # but maybe something with parsing/uploading failed. Try to avoid errors here as good as possible send_job_status_reaction(original_event, "error", content="Error in Post-processing: " + str(e), dvm_config=self.dvm_config, ) if amount > 0 and self.dvm_config.LNBITS_ADMIN_KEY != "": user = get_or_add_user(self.dvm_config.DB, original_event.pubkey().to_hex(), client=self.client, config=self.dvm_config) print(user.lud16 + " " + str(amount)) bolt11 = zaprequest(user.lud16, amount, "Couldn't finish job, returning sats", original_event, self.keys, self.dvm_config, zaptype="private") if bolt11 is None: print("Receiver has no Lightning address, can't zap back.") return try: payment_hash = pay_bolt11_ln_bits(bolt11, self.dvm_config) except Exception as e: print(e) def send_nostr_reply_event(content, original_event_as_str): original_event = Event.from_json(original_event_as_str) request_tag = Tag.parse(["request", original_event_as_str]) e_tag = Tag.parse(["e", original_event.id().to_hex()]) p_tag = Tag.parse(["p", original_event.pubkey().to_hex()]) alt_tag = Tag.parse(["alt", "This is the result of a NIP90 DVM AI task with kind " + str( original_event.kind()) + ". The task was: " + original_event.content()]) status_tag = Tag.parse(["status", "success"]) reply_tags = [request_tag, e_tag, p_tag, alt_tag, status_tag] encrypted = False for tag in original_event.tags(): if tag.as_vec()[0] == "encrypted": encrypted = True encrypted_tag = Tag.parse(["encrypted"]) reply_tags.append(encrypted_tag) for tag in original_event.tags(): if tag.as_vec()[0] == "i": i_tag = tag if not encrypted: reply_tags.append(i_tag) if encrypted: print(content) content = nip04_encrypt(self.keys.secret_key(), PublicKey.from_hex(original_event.pubkey().to_hex()), content) reply_event = EventBuilder(original_event.kind() + 1000, str(content), reply_tags).to_event(self.keys) send_event(reply_event, client=self.client, dvm_config=self.dvm_config) print("[" + self.dvm_config.NIP89.NAME + "] " + str( original_event.kind() + 1000) + " Job Response event sent: " + reply_event.as_json()) def send_job_status_reaction(original_event, status, is_paid=True, amount=0, client=None, content=None, dvm_config=None): task = get_task(original_event, client=client, dvm_config=dvm_config) alt_description, reaction = build_status_reaction(status, task, amount, content) e_tag = Tag.parse(["e", original_event.id().to_hex()]) p_tag = Tag.parse(["p", original_event.pubkey().to_hex()]) alt_tag = Tag.parse(["alt", alt_description]) status_tag = Tag.parse(["status", status]) reply_tags = [e_tag, alt_tag, status_tag] encryption_tags = [] encrypted = False for tag in original_event.tags(): if tag.as_vec()[0] == "encrypted": encrypted = True encrypted_tag = Tag.parse(["encrypted"]) encryption_tags.append(encrypted_tag) if encrypted: encryption_tags.append(p_tag) else: reply_tags.append(p_tag) if status == "success" or status == "error": # for x in self.job_list: if x.event == original_event: is_paid = x.is_paid amount = x.amount break bolt11 = "" payment_hash = "" expires = original_event.created_at().as_secs() + (60 * 60 * 24) if status == "payment-required" or (status == "processing" and not is_paid): if dvm_config.LNBITS_INVOICE_KEY != "": try: bolt11, payment_hash = create_bolt11_ln_bits(amount,dvm_config) except Exception as e: print(e) try: bolt11, payment_hash = create_bolt11_lud16(dvm_config.LN_ADDRESS, amount) except Exception as e: print(e) bolt11 = None elif dvm_config.LN_ADDRESS != "": try: bolt11, payment_hash = create_bolt11_lud16(dvm_config.LN_ADDRESS, amount) except Exception as e: print(e) bolt11 = None if not any(x.event == original_event for x in self.job_list): self.job_list.append( JobToWatch(event=original_event, timestamp=original_event.created_at().as_secs(), amount=amount, is_paid=is_paid, status=status, result="", is_processed=False, bolt11=bolt11, payment_hash=payment_hash, expires=expires)) # print(str(self.job_list)) if (status == "payment-required" or status == "payment-rejected" or ( status == "processing" and not is_paid) or (status == "success" and not is_paid)): if dvm_config.LNBITS_INVOICE_KEY != "": amount_tag = Tag.parse(["amount", str(amount * 1000), bolt11]) else: amount_tag = Tag.parse(["amount", str(amount * 1000)]) # to millisats reply_tags.append(amount_tag) if encrypted: content_tag = Tag.parse(["content", reaction]) reply_tags.append(content_tag) str_tags = [] for element in reply_tags: str_tags.append(element.as_vec()) content = json.dumps(str_tags) content = nip04_encrypt(self.keys.secret_key(), PublicKey.from_hex(original_event.pubkey().to_hex()), content) reply_tags = encryption_tags else: content = reaction keys = Keys.from_sk_str(dvm_config.PRIVATE_KEY) reaction_event = EventBuilder(EventDefinitions.KIND_FEEDBACK, str(content), reply_tags).to_event(keys) send_event(reaction_event, client=self.client, dvm_config=self.dvm_config) print("[" + self.dvm_config.NIP89.NAME + "]" + ": Sent Kind " + str( EventDefinitions.KIND_FEEDBACK) + " Reaction: " + status + " " + reaction_event.as_json()) return reaction_event.as_json() def do_work(job_event, amount): if ((EventDefinitions.KIND_NIP90_EXTRACT_TEXT <= job_event.kind() <= EventDefinitions.KIND_NIP90_GENERIC) or job_event.kind() == EventDefinitions.KIND_DM): task = get_task(job_event, client=self.client, dvm_config=self.dvm_config) for dvm in self.dvm_config.SUPPORTED_DVMS: result = "" try: if task == dvm.TASK: request_form = dvm.create_request_from_nostr_event(job_event, self.client, self.dvm_config) if dvm_config.USE_OWN_VENV: python_location = "/bin/python" if platform == "win32": python_location = "/Scripts/python" python_bin = (r'cache/venvs/' + os.path.basename(dvm_config.SCRIPT).split(".py")[0] + python_location) retcode = subprocess.call([python_bin, dvm_config.SCRIPT, '--request', json.dumps(request_form), '--identifier', dvm_config.IDENTIFIER, '--output', 'output.txt']) print("Finished processing, loading data..") with open(os.path.abspath('output.txt')) as f: resultall = f.readlines() for line in resultall: if line != '\n': result += line os.remove(os.path.abspath('output.txt')) assert not result.startswith("Error:") print(result) else: # Some components might have issues with running code in otuside venv. # We install locally in these cases for now result = dvm.process(request_form) try: post_processed = dvm.post_process(str(result), job_event) send_nostr_reply_event(post_processed, job_event.as_json()) except Exception as e: send_job_status_reaction(job_event, "error", content=str(e), dvm_config=self.dvm_config) except Exception as e: # we could send the exception here to the user, but maybe that's not a good idea after all. send_job_status_reaction(job_event, "error", content=result, dvm_config=self.dvm_config) # Zapping back the user on error if amount > 0 and self.dvm_config.LNBITS_ADMIN_KEY != "": user = get_or_add_user(self.dvm_config.DB, job_event.pubkey().to_hex(), client=self.client, config=self.dvm_config) print(user.lud16 + " " + str(amount)) bolt11 = zaprequest(user.lud16, amount, "Couldn't finish job, returning sats", job_event, user.npub, self.keys, self.dvm_config.RELAY_LIST, zaptype="private") if bolt11 is None: print("Receiver has no Lightning address, can't zap back.") return try: payment_hash = pay_bolt11_ln_bits(bolt11, self.dvm_config) except Exception as e: print(e) return self.client.handle_notifications(NotificationHandler()) while True: for job in self.job_list: if job.bolt11 != "" and job.payment_hash != "" and not job.is_paid:
ispaid = check_bolt11_ln_bits_is_paid(job.payment_hash, self.dvm_config)
19
2023-11-17 18:32:56+00:00
16k
IBM/oper8
oper8/watch_manager/python_watch_manager/filters/filters.py
[ { "identifier": "KubeEventType", "path": "oper8/deploy_manager/kube_event.py", "snippet": "class KubeEventType(Enum):\n \"\"\"Enum for all possible kubernetes event types\"\"\"\n\n DELETED = \"DELETED\"\n MODIFIED = \"MODIFIED\"\n ADDED = \"ADDED\"" }, { "identifier": "ManagedObject"...
from abc import ABC, abstractmethod from collections import deque from typing import Optional from ....deploy_manager import KubeEventType from ....managed_object import ManagedObject from ....reconcile import ReconcileManager from ....status import READY_CONDITION, get_condition from ....utils import abstractclassproperty from ..utils import ( RESERVED_PLATFORM_ANNOTATIONS, RESOURCE_VERSION_KEEP_COUNT, obj_to_hash, ) import alog
11,329
The test result """ result = self.test(resource, event) if result is not None and not result: log.debug3( "Failed filter: %s with return val %s", self, result, extra={"resource": resource}, ) self.update(resource) return result ## Generic Resource filters class CreationDeletionFilter(Filter): """Filter to ensure reconciliation on creation and deletion events""" def test( # pylint: disable=inconsistent-return-statements self, resource: ManagedObject, event: KubeEventType, ) -> Optional[bool]: """Return true if event is ADDED or DELETED""" # Ignore non Added/Deleted Events if event not in [KubeEventType.ADDED, KubeEventType.DELETED]: return return True class GenerationFilter(Filter): """Filter for reconciling on generation changes for resources that support it""" def __init__(self, resource: ManagedObject): """Set generation instance variable""" super().__init__(resource) self.generation = None def test( # pylint: disable=inconsistent-return-statements self, resource: ManagedObject, event: KubeEventType, ) -> Optional[bool]: """Return true if resource generation is different than before""" # Only update&test resources with a generation if not self.generation: return # Only test on resource updates if event in [KubeEventType.ADDED, KubeEventType.DELETED]: return # Test if new generation is different return self.generation != resource.metadata.get("generation") def update(self, resource: ManagedObject): """Update the currently observed generation""" self.generation = resource.metadata.get("generation") class NoGenerationFilter(Filter): """Filter for reconciling changes to spec on resources that don't support the generation field like pods. It does this by hashing the objects excluding status and metadata""" def __init__(self, resource: ManagedObject): """Check if resource supports generation and initialize the hash dict""" self.supports_generation = resource.metadata.get("generation") is not None self.resource_hashes = {} super().__init__(resource) def test( # pylint: disable=inconsistent-return-statements self, resource: ManagedObject, event: KubeEventType, ) -> Optional[bool]: """Return True if a resources current hash differs from the current""" # Don't test resources that support generation or if we don't have hashes yet if self.supports_generation or not self.resource_hashes: return # Only test on resource updates if event in [KubeEventType.ADDED, KubeEventType.DELETED]: return # Check each stored resource hash to see if its # changed for key, obj_has in self.resource_hashes.items(): if obj_has != obj_to_hash(resource.get(key)): log.debug2("Detected change in %s", key) return True return False def update(self, resource: ManagedObject): """Update the observed spec hashes""" if self.supports_generation: return # Get the default hashes for all object keys except metadata # and status for key, obj in resource.definition.items(): if key in ["metadata", "status", "kind", "apiVersion"]: continue self.resource_hashes[key] = obj_to_hash(obj) class ResourceVersionFilter(Filter): """Filter for duplicate resource versions which happens when restarting a watch connection""" def __init__(self, resource: ManagedObject): """Initialize the resource version list""" # Use a dequeue instead of a list/set to set a bound on the number # of tracked versions
""" Filters are used to limit the amount of events being reconciled by a watch manager This is based off of the kubernetes controller runtime's "predicates": https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.15.0/pkg/predicate#Funcs The default set of filters is derived from operator-sdk's ansible predicates https://github.com/operator-framework/operator-sdk/blob/50c6ac03746ff4edf582feb9a71d2a7ea6ae6c40/internal/ansible/controller/controller.go#L105 """ # Standard # First Party # Local log = alog.use_channel("PWMFLT") ## Default Types class Filter(ABC): """Generic Filter Interface for subclassing. Every subclass should implement a `test` function which returns true when a resource should be reconciled. Subclasses can optionally implement a `update` method if the filter requires storing some stateful information like ResourceVersion or Metadata. NOTE: A unique Filter instance is created for each resource """ def __init__(self, resource: ManagedObject): # noqa: B027 """Initializer can be used to detect configuration or create instance variables. Even though a resource is provided it should not set state until update is called Args: resource: ManagedObject This resource can be used by subclass to gather generic information. """ ## Abstract Interface ###################################################### # # These functions must be implemented by child classes ## @abstractmethod def test(self, resource: ManagedObject, event: KubeEventType) -> Optional[bool]: """Test whether the resource&event passes the filter. Returns true if the filter should be reconciled and return false if it should not be. A filter can optionally return None to ignore an event Args: resource: ManagedObject The current resource being checked event: KubeEventType The event type that triggered this filter Returns: result: Optional[bool] The result of the test. """ ## Base Class Interface #################################################### # # These methods MAY be implemented by children, but contain default # implementations that are appropriate for simple cases. # ## def update(self, resource: ManagedObject): # noqa: B027 """Update the instances current state. Args: resource: ManagedObject The current state of the resource """ def update_and_test(self, resource: ManagedObject, event: KubeEventType) -> bool: """First test a resource/event against a filter then update the current state Args: resource: ManagedObject The resource being filtered event: KubeEventType The event to be filtered Returns: test_result: bool The test result """ result = self.test(resource, event) if result is not None and not result: log.debug3( "Failed filter: %s with return val %s", self, result, extra={"resource": resource}, ) self.update(resource) return result ## Generic Resource filters class CreationDeletionFilter(Filter): """Filter to ensure reconciliation on creation and deletion events""" def test( # pylint: disable=inconsistent-return-statements self, resource: ManagedObject, event: KubeEventType, ) -> Optional[bool]: """Return true if event is ADDED or DELETED""" # Ignore non Added/Deleted Events if event not in [KubeEventType.ADDED, KubeEventType.DELETED]: return return True class GenerationFilter(Filter): """Filter for reconciling on generation changes for resources that support it""" def __init__(self, resource: ManagedObject): """Set generation instance variable""" super().__init__(resource) self.generation = None def test( # pylint: disable=inconsistent-return-statements self, resource: ManagedObject, event: KubeEventType, ) -> Optional[bool]: """Return true if resource generation is different than before""" # Only update&test resources with a generation if not self.generation: return # Only test on resource updates if event in [KubeEventType.ADDED, KubeEventType.DELETED]: return # Test if new generation is different return self.generation != resource.metadata.get("generation") def update(self, resource: ManagedObject): """Update the currently observed generation""" self.generation = resource.metadata.get("generation") class NoGenerationFilter(Filter): """Filter for reconciling changes to spec on resources that don't support the generation field like pods. It does this by hashing the objects excluding status and metadata""" def __init__(self, resource: ManagedObject): """Check if resource supports generation and initialize the hash dict""" self.supports_generation = resource.metadata.get("generation") is not None self.resource_hashes = {} super().__init__(resource) def test( # pylint: disable=inconsistent-return-statements self, resource: ManagedObject, event: KubeEventType, ) -> Optional[bool]: """Return True if a resources current hash differs from the current""" # Don't test resources that support generation or if we don't have hashes yet if self.supports_generation or not self.resource_hashes: return # Only test on resource updates if event in [KubeEventType.ADDED, KubeEventType.DELETED]: return # Check each stored resource hash to see if its # changed for key, obj_has in self.resource_hashes.items(): if obj_has != obj_to_hash(resource.get(key)): log.debug2("Detected change in %s", key) return True return False def update(self, resource: ManagedObject): """Update the observed spec hashes""" if self.supports_generation: return # Get the default hashes for all object keys except metadata # and status for key, obj in resource.definition.items(): if key in ["metadata", "status", "kind", "apiVersion"]: continue self.resource_hashes[key] = obj_to_hash(obj) class ResourceVersionFilter(Filter): """Filter for duplicate resource versions which happens when restarting a watch connection""" def __init__(self, resource: ManagedObject): """Initialize the resource version list""" # Use a dequeue instead of a list/set to set a bound on the number # of tracked versions
self.resource_versions = deque([], maxlen=RESOURCE_VERSION_KEEP_COUNT)
8
2023-11-15 16:43:29+00:00
16k
Jisencc/yolov5_dual_weighting
segment/predict.py
[ { "identifier": "DetectMultiBackend", "path": "models/common.py", "snippet": "class DetectMultiBackend(nn.Module):\n # YOLOv5 MultiBackend class for python inference on various backends\n def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False, data=None, fp16=False, fuse=Tr...
import argparse import os import platform import sys import torch from pathlib import Path from ultralytics.utils.plotting import Annotator, colors, save_one_box from models.common import DetectMultiBackend from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2, increment_path, non_max_suppression, print_args, scale_boxes, scale_segments, strip_optimizer) from utils.segment.general import masks2segments, process_mask, process_mask_native from utils.torch_utils import select_device, smart_inference_mode
11,996
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Run YOLOv5 segmentation inference on images, videos, directories, streams, etc. Usage - sources: $ python segment/predict.py --weights yolov5s-seg.pt --source 0 # webcam img.jpg # image vid.mp4 # video screen # screenshot path/ # directory list.txt # list of images list.streams # list of streams 'path/*.jpg' # glob 'https://youtu.be/LNwODJXcvt4' # YouTube 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream Usage - formats: $ python segment/predict.py --weights yolov5s-seg.pt # PyTorch yolov5s-seg.torchscript # TorchScript yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn yolov5s-seg_openvino_model # OpenVINO yolov5s-seg.engine # TensorRT yolov5s-seg.mlmodel # CoreML (macOS-only) yolov5s-seg_saved_model # TensorFlow SavedModel yolov5s-seg.pb # TensorFlow GraphDef yolov5s-seg.tflite # TensorFlow Lite yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU yolov5s-seg_paddle_model # PaddlePaddle """ FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative @smart_inference_mode() def run( weights=ROOT / 'yolov5s-seg.pt', # model.pt path(s) source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam) data=ROOT / 'data/coco128.yaml', # dataset.yaml path imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / 'runs/predict-seg', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference vid_stride=1, # video frame-rate stride retina_masks=False, ): source = str(source) save_img = not nosave and not source.endswith('.txt') # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file) screenshot = source.lower().startswith('screen') if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, names, pt = model.stride, model.names, model.pt imgsz = check_img_size(imgsz, s=stride) # check image size # Dataloader bs = 1 # batch_size if webcam: view_img = check_imshow(warn=True)
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license """ Run YOLOv5 segmentation inference on images, videos, directories, streams, etc. Usage - sources: $ python segment/predict.py --weights yolov5s-seg.pt --source 0 # webcam img.jpg # image vid.mp4 # video screen # screenshot path/ # directory list.txt # list of images list.streams # list of streams 'path/*.jpg' # glob 'https://youtu.be/LNwODJXcvt4' # YouTube 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream Usage - formats: $ python segment/predict.py --weights yolov5s-seg.pt # PyTorch yolov5s-seg.torchscript # TorchScript yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn yolov5s-seg_openvino_model # OpenVINO yolov5s-seg.engine # TensorRT yolov5s-seg.mlmodel # CoreML (macOS-only) yolov5s-seg_saved_model # TensorFlow SavedModel yolov5s-seg.pb # TensorFlow GraphDef yolov5s-seg.tflite # TensorFlow Lite yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU yolov5s-seg_paddle_model # PaddlePaddle """ FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative @smart_inference_mode() def run( weights=ROOT / 'yolov5s-seg.pt', # model.pt path(s) source=ROOT / 'data/images', # file/dir/URL/glob/screen/0(webcam) data=ROOT / 'data/coco128.yaml', # dataset.yaml path imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / 'runs/predict-seg', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference vid_stride=1, # video frame-rate stride retina_masks=False, ): source = str(source) save_img = not nosave and not source.endswith('.txt') # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file) screenshot = source.lower().startswith('screen') if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half) stride, names, pt = model.stride, model.names, model.pt imgsz = check_img_size(imgsz, s=stride) # check image size # Dataloader bs = 1 # batch_size if webcam: view_img = check_imshow(warn=True)
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
5
2023-11-12 13:28:26+00:00
16k
RAIVNLab/MatFormer-OLMo
olmo/train.py
[ { "identifier": "PathOrStr", "path": "olmo/aliases.py", "snippet": "" }, { "identifier": "CheckpointType", "path": "olmo/config.py", "snippet": "class CheckpointType(StrEnum):\n sharded = \"sharded\"\n unsharded = \"unsharded\"" }, { "identifier": "SpeedMonitorConfig", ...
import logging import math import random import shutil import time import numpy as np import torch import torch.nn.functional as F import wandb from collections import deque from dataclasses import dataclass, field from itertools import islice from pathlib import Path from typing import Any, Deque, Dict, List, Optional, TextIO, Tuple from packaging import version from torch.distributed.fsdp import FullStateDictConfig from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import StateDictType from torch.distributed.fsdp.api import ( FullOptimStateDictConfig, ShardedOptimStateDictConfig, ShardedStateDictConfig, ) from torch.utils.data import DataLoader from torchmetrics import MeanMetric from .aliases import PathOrStr from .config import CheckpointType, SpeedMonitorConfig, TrainConfig from .data import IterableDataset from .eval import Evaluator from .exceptions import OlmoConfigurationError from .model import Olmo, MatformerManager from .optim import set_new_base_lr from .util import ( barrier, get_global_rank, get_world_size, move_to_device, peak_gpu_memory, resource_path, syncronize_flag, upload, wait_on, )
12,939
self.global_train_tokens_seen = state_dict.get( # newer addition "global_train_tokens_seen", self.global_data_step * self.cfg.global_train_batch_size * self.cfg.model.max_sequence_length, ) if not self.cfg.restore_dataloader: self.global_data_step = 0 self.global_train_examples_seen = 0 self.global_train_tokens_seen = 0 elif self.cfg.fast_forward_batches: self.global_data_step += self.cfg.fast_forward_batches # Technically we don't "see" these batches that we fast-forward through, but we use # this variable to update the position of the dataset so we need to include them here. self.global_train_examples_seen += self.cfg.fast_forward_batches * self.cfg.global_train_batch_size # NOTE: on the other hand we don't add anything to 'self.global_train_tokens_seen' here because # that variable is meant to track the actual number of tokens trained on. if self.global_data_step > 0: if self.global_data_step > self.global_step: log.info( f"Fast-forwarding data loader to step {self.global_step:,d}+{self.global_data_step-self.global_step:,d} " f"({self.global_train_examples_seen:,d} examples)" ) else: log.info( f"Fast-forwarding data loader to step {self.global_data_step:,d} " f"({self.global_train_examples_seen:,d} examples)" ) assert isinstance(self.train_loader.dataset, IterableDataset) self.train_loader.dataset.start_index = self.global_train_examples_seen if not self.cfg.restore_base_learning_rate: # Reset base learning rate to the value in the config, not the checkpoint. set_new_base_lr(self.optim, self.scheduler, self.cfg.optimizer.learning_rate) # RNG states. if "rng" in state_dict: rng_state = state_dict["rng"] self.restore_rng_state(rng_state) def restore_rng_state(self, rng_state: Dict[str, Any]) -> None: random.setstate(rng_state["python"]) np.random.set_state(rng_state["numpy"]) torch.set_rng_state(rng_state["torch"]) torch.cuda.set_rng_state(rng_state["cuda"]) def save_sharded_checkpoint(self) -> Path: checkpoint_dir = Path(self.cfg.save_folder) / f"step{self.global_step}" checkpoint_dir_tmp = Path(self.cfg.save_folder) / f"step{self.global_step}-tmp" try: next(checkpoint_dir.glob("*")) if self.cfg.save_overwrite: if get_global_rank() == 0: shutil.rmtree(checkpoint_dir) else: raise OlmoConfigurationError( f"Checkpoint for step {self.global_step} already exists, use --save-overwrite to overwrite it" ) except StopIteration: pass if get_global_rank() == 0: checkpoint_dir_tmp.mkdir(parents=True, exist_ok=True) self.checkpoints.append(checkpoint_dir) barrier() # Flush data indices file. if self.indices_file is not None: self.indices_file.flush() # Write the checkpoint. with FSDP.state_dict_type( self.fsdp_model, state_dict_type=StateDictType.SHARDED_STATE_DICT, state_dict_config=ShardedStateDictConfig(offload_to_cpu=True), optim_state_dict_config=ShardedOptimStateDictConfig(offload_to_cpu=True), ): # NOTE: Alternatively we could use the checkpointing method in this test # https://github.com/pytorch/pytorch/blob/main/test/distributed/checkpoint/test_fsdp_optim_state.py # but we've had issues with that on AMD GPUs. See # https://github.com/pytorch/pytorch/issues/100041 # checkpoint.save_state_dict(self.state_dict(), checkpoint.FileSystemWriter(checkpoint_dir)) torch.save(self.state_dict(), checkpoint_dir_tmp / f"rank{get_global_rank()}.pt") # Save config too. if get_global_rank() == 0: self.cfg.save(checkpoint_dir_tmp / "config.yaml") barrier() if get_global_rank() == 0: # Replace temp directory with target checkpoint directory. checkpoint_dir_tmp.replace(checkpoint_dir) # Link to 'latest'. latest_path = Path(self.cfg.save_folder) / "latest" latest_path.unlink(missing_ok=True) latest_path.symlink_to(checkpoint_dir.name, target_is_directory=True) # In the cases where we're using a shared NFS drive between ranks to save checkpoints, # replacing the temp directory with the final directory from rank 0 might not be immediately # realized in the file systems of the other ranks. # So we wait here across all ranks until that final checkpoint directory is visible. wait_on(lambda: checkpoint_dir.exists(), "Waiting for checkpoint directory", timeout=10.0) # Remove old checkpoints. if self.cfg.save_num_checkpoints_to_keep > 0: while len(self.checkpoints) > self.cfg.save_num_checkpoints_to_keep: self.remove_sharded_checkpoint(0) barrier() # Upload checkpoint to bucket. if self.cfg.remote_save_folder is not None: files_to_upload = [f"rank{get_global_rank()}.pt"] if get_global_rank() == 0: files_to_upload.append("config.yaml") for fname in files_to_upload: source = checkpoint_dir / fname target = f"{self.cfg.remote_save_folder}/{checkpoint_dir.name}/{fname}" log.info(f"Uploading {source} to {target}...")
from __future__ import annotations __all__ = ["SpeedMonitor", "LRMonitor", "Trainer"] log = logging.getLogger(__name__) @dataclass class SpeedMonitor: cfg: SpeedMonitorConfig start_times: Deque[float] = field(default_factory=lambda: deque([])) global_total_tokens: int = 0 device_interval_tokens: Deque[int] = field(default_factory=lambda: deque([])) def batch_start(self, global_total_tokens: int, device_batch_num_tokens: int, record: bool = True) -> None: self.global_total_tokens = global_total_tokens if record: if len(self.start_times) >= self.cfg.window_size: self.start_times.popleft() self.device_interval_tokens.popleft() self.start_times.append(time.monotonic()) self.device_interval_tokens.append(device_batch_num_tokens) def reset(self) -> None: self.start_times.clear() self.device_interval_tokens.clear() def check(self) -> Dict[str, float]: metrics: Dict[str, float] = {"throughput/total_tokens": self.global_total_tokens} if self.start_times: interval_seconds = time.monotonic() - self.start_times[0] interval_batches = len(self.start_times) interval_tokens = sum(self.device_interval_tokens) metrics["throughput/device/tokens_per_second"] = interval_tokens / interval_seconds metrics["throughput/device/batches_per_second"] = interval_batches / interval_seconds return metrics @dataclass class LRMonitor: optim: torch.optim.Optimizer def check(self) -> Dict[str, float]: lrs = [group["lr"] for group in self.optim.param_groups] return {f"optim/learning_rate_group{idx}": lr for idx, lr in enumerate(lrs)} @dataclass class Trainer: cfg: TrainConfig model: Olmo fsdp_model: FSDP optim: torch.optim.Optimizer scheduler: torch.optim.lr_scheduler.LRScheduler train_loader: DataLoader device: torch.device evaluators: List[Evaluator] ce_train_loss_metric: MeanMetric z_train_loss_metric: Optional[MeanMetric] = None global_step: int = 0 global_data_step: int = 0 """This is now redundant since adding 'global_train_examples_seen'.""" global_train_examples_seen: int = 0 """Tracks the global number of training examples seen for the purpose of restoring the dataset position on restarts.""" global_train_tokens_seen: int = 0 """Tracks the global total number of tokens trained on.""" checkpoints: List[Path] = field(default_factory=list) unsharded_checkpoints: List[Path] = field(default_factory=list) min_train_loss: float = float("inf") indices_file: Optional[TextIO] = None def state_dict(self) -> Dict[str, Any]: state_dict = self.non_tensor_state_dict() state_dict["model"] = self.fsdp_model.state_dict() state_dict["optim"] = FSDP.optim_state_dict(self.fsdp_model, self.optim) return state_dict def non_tensor_state_dict(self) -> Dict[str, Any]: return { "scheduler": self.scheduler.state_dict(), "global_step": self.global_step, "global_data_step": self.global_data_step, "global_train_examples_seen": self.global_train_examples_seen, "global_train_tokens_seen": self.global_train_tokens_seen, "checkpoints": self.checkpoints, "unsharded_checkpoints": self.unsharded_checkpoints, "rng": { "python": random.getstate(), "numpy": np.random.get_state(), "torch": torch.random.get_rng_state(), "cuda": torch.cuda.get_rng_state(), }, } def load_non_tensor_state_dict(self, state_dict: Dict[str, Any]) -> None: # Checkpoint paths. self.checkpoints = [ path for path in state_dict["checkpoints"] if path.is_dir() and path.resolve().parent == Path(self.cfg.save_folder).resolve() ] self.unsharded_checkpoints = [ path for path in state_dict["unsharded_checkpoints"] if path.is_dir() and path.resolve().parent == Path(self.cfg.save_folder).resolve() ] # Learning rate scheduler. self.scheduler.load_state_dict(state_dict["scheduler"]) # Dataset / dataloader position. self.global_step = state_dict["global_step"] self.global_data_step = state_dict["global_data_step"] self.global_train_examples_seen = state_dict.get( # newer addition "global_train_examples_seen", self.global_data_step * self.cfg.global_train_batch_size ) self.global_train_tokens_seen = state_dict.get( # newer addition "global_train_tokens_seen", self.global_data_step * self.cfg.global_train_batch_size * self.cfg.model.max_sequence_length, ) if not self.cfg.restore_dataloader: self.global_data_step = 0 self.global_train_examples_seen = 0 self.global_train_tokens_seen = 0 elif self.cfg.fast_forward_batches: self.global_data_step += self.cfg.fast_forward_batches # Technically we don't "see" these batches that we fast-forward through, but we use # this variable to update the position of the dataset so we need to include them here. self.global_train_examples_seen += self.cfg.fast_forward_batches * self.cfg.global_train_batch_size # NOTE: on the other hand we don't add anything to 'self.global_train_tokens_seen' here because # that variable is meant to track the actual number of tokens trained on. if self.global_data_step > 0: if self.global_data_step > self.global_step: log.info( f"Fast-forwarding data loader to step {self.global_step:,d}+{self.global_data_step-self.global_step:,d} " f"({self.global_train_examples_seen:,d} examples)" ) else: log.info( f"Fast-forwarding data loader to step {self.global_data_step:,d} " f"({self.global_train_examples_seen:,d} examples)" ) assert isinstance(self.train_loader.dataset, IterableDataset) self.train_loader.dataset.start_index = self.global_train_examples_seen if not self.cfg.restore_base_learning_rate: # Reset base learning rate to the value in the config, not the checkpoint. set_new_base_lr(self.optim, self.scheduler, self.cfg.optimizer.learning_rate) # RNG states. if "rng" in state_dict: rng_state = state_dict["rng"] self.restore_rng_state(rng_state) def restore_rng_state(self, rng_state: Dict[str, Any]) -> None: random.setstate(rng_state["python"]) np.random.set_state(rng_state["numpy"]) torch.set_rng_state(rng_state["torch"]) torch.cuda.set_rng_state(rng_state["cuda"]) def save_sharded_checkpoint(self) -> Path: checkpoint_dir = Path(self.cfg.save_folder) / f"step{self.global_step}" checkpoint_dir_tmp = Path(self.cfg.save_folder) / f"step{self.global_step}-tmp" try: next(checkpoint_dir.glob("*")) if self.cfg.save_overwrite: if get_global_rank() == 0: shutil.rmtree(checkpoint_dir) else: raise OlmoConfigurationError( f"Checkpoint for step {self.global_step} already exists, use --save-overwrite to overwrite it" ) except StopIteration: pass if get_global_rank() == 0: checkpoint_dir_tmp.mkdir(parents=True, exist_ok=True) self.checkpoints.append(checkpoint_dir) barrier() # Flush data indices file. if self.indices_file is not None: self.indices_file.flush() # Write the checkpoint. with FSDP.state_dict_type( self.fsdp_model, state_dict_type=StateDictType.SHARDED_STATE_DICT, state_dict_config=ShardedStateDictConfig(offload_to_cpu=True), optim_state_dict_config=ShardedOptimStateDictConfig(offload_to_cpu=True), ): # NOTE: Alternatively we could use the checkpointing method in this test # https://github.com/pytorch/pytorch/blob/main/test/distributed/checkpoint/test_fsdp_optim_state.py # but we've had issues with that on AMD GPUs. See # https://github.com/pytorch/pytorch/issues/100041 # checkpoint.save_state_dict(self.state_dict(), checkpoint.FileSystemWriter(checkpoint_dir)) torch.save(self.state_dict(), checkpoint_dir_tmp / f"rank{get_global_rank()}.pt") # Save config too. if get_global_rank() == 0: self.cfg.save(checkpoint_dir_tmp / "config.yaml") barrier() if get_global_rank() == 0: # Replace temp directory with target checkpoint directory. checkpoint_dir_tmp.replace(checkpoint_dir) # Link to 'latest'. latest_path = Path(self.cfg.save_folder) / "latest" latest_path.unlink(missing_ok=True) latest_path.symlink_to(checkpoint_dir.name, target_is_directory=True) # In the cases where we're using a shared NFS drive between ranks to save checkpoints, # replacing the temp directory with the final directory from rank 0 might not be immediately # realized in the file systems of the other ranks. # So we wait here across all ranks until that final checkpoint directory is visible. wait_on(lambda: checkpoint_dir.exists(), "Waiting for checkpoint directory", timeout=10.0) # Remove old checkpoints. if self.cfg.save_num_checkpoints_to_keep > 0: while len(self.checkpoints) > self.cfg.save_num_checkpoints_to_keep: self.remove_sharded_checkpoint(0) barrier() # Upload checkpoint to bucket. if self.cfg.remote_save_folder is not None: files_to_upload = [f"rank{get_global_rank()}.pt"] if get_global_rank() == 0: files_to_upload.append("config.yaml") for fname in files_to_upload: source = checkpoint_dir / fname target = f"{self.cfg.remote_save_folder}/{checkpoint_dir.name}/{fname}" log.info(f"Uploading {source} to {target}...")
upload(source, target, save_overwrite=self.cfg.save_overwrite)
17
2023-11-14 02:24:07+00:00
16k
1in-oos/ccplus
caringcaribou/modules/uds.py
[ { "identifier": "auto_blacklist", "path": "caringcaribou/utils/can_actions.py", "snippet": "def auto_blacklist(bus, duration, classifier_function, print_results):\n \"\"\"Listens for false positives on the CAN bus and generates an arbitration ID blacklist.\n\n Finds all can.Message <msg> on 'bus' ...
from caringcaribou.utils.can_actions import auto_blacklist from caringcaribou.utils.common import list_to_hex_str, parse_int_dec_or_hex from caringcaribou.utils.constants import ARBITRATION_ID_MAX, ARBITRATION_ID_MAX_EXTENDED,ARBITRATION_ID_MIN_EXTENDED from caringcaribou.utils.constants import ARBITRATION_ID_MIN from caringcaribou.utils.iso15765_2 import IsoTp from caringcaribou.utils.iso14229_1 import Constants, Iso14229_1, NegativeResponseCodes, Services, ServiceID from sys import stdout, version_info, stderr import argparse import datetime import time
12,245
0x12: "SUB_FUNCTION_NOT_SUPPORTED", 0x13: "INCORRECT_MESSAGE_LENGTH_OR_INVALID_FORMAT", 0x14: "RESPONSE_TOO_LONG", 0x21: "BUSY_REPEAT_REQUEST", 0x22: "CONDITIONS_NOT_CORRECT", 0x24: "REQUEST_SEQUENCE_ERROR", 0x25: "NO_RESPONSE_FROM_SUBNET_COMPONENT", 0x26: "FAILURE_PREVENTS_EXECUTION_OF_REQUESTED_ACTION", 0x31: "REQUEST_OUT_OF_RANGE", 0x33: "SECURITY_ACCESS_DENIED", 0x35: "INVALID_KEY", 0x36: "EXCEEDED_NUMBER_OF_ATTEMPTS", 0x37: "REQUIRED_TIME_DELAY_NOT_EXPIRED", 0x70: "UPLOAD_DOWNLOAD_NOT_ACCEPTED", 0x71: "TRANSFER_DATA_SUSPENDED", 0x72: "GENERAL_PROGRAMMING_FAILURE", 0x73: "WRONG_BLOCK_SEQUENCE_COUNTER", 0x78: "REQUEST_CORRECTLY_RECEIVED_RESPONSE_PENDING", 0x7E: "SUB_FUNCTION_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x7F: "SERVICE_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x81: "RPM_TOO_HIGH", 0x82: "RPM_TOO_LOW", 0x83: "ENGINE_IS_RUNNING", 0x84: "ENGINE_IS_NOT_RUNNING", 0x85: "ENGINE_RUN_TIME_TOO_LOW", 0x86: "TEMPERATURE_TOO_HIGH", 0x87: "TEMPERATURE_TOO_LOW", 0x88: "VEHICLE_SPEED_TOO_HIGH", 0x89: "VEHICLE_SPEED_TOO_LOW", 0x8A: "THROTTLE_PEDAL_TOO_HIGH", 0x8B: "THROTTLE_PEDAL_TOO_LOW", 0x8C: "TRANSMISSION_RANGE_NOT_IN_NEUTRAL", 0x8D: "TRANSMISSION_RANGE_NOT_IN_GEAR", 0x8F: "BRAKE_SWITCHES_NOT_CLOSED", 0x90: "SHIFT_LEVER_NOT_IN_PARK", 0x91: "TORQUE_CONVERTER_CLUTCH_LOCKED", 0x92: "VOLTAGE_TOO_HIGH", 0x93: "VOLTAGE_TOO_LOW" } DELAY_DISCOVERY = 0.01 DELAY_TESTER_PRESENT = 0.5 DELAY_SECSEED_RESET = 0.01 TIMEOUT_SERVICES = 0.2 TIMEOUT_SUBSERVICES = 0.02 # Max number of arbitration IDs to backtrack during verification VERIFICATION_BACKTRACK = 5 # Extra time in seconds to wait for responses during verification VERIFICATION_EXTRA_DELAY = 0.5 BYTE_MIN = 0x00 BYTE_MAX = 0xFF DUMP_DID_MIN = 0x0000 DUMP_DID_MAX = 0xFFFF DUMP_DID_TIMEOUT = 0.2 def uds_discovery(E, min_id, max_id, blacklist_args, auto_blacklist_duration, delay, verify, print_results=True): """Scans for diagnostics support by brute forcing session control messages to different arbitration IDs. Returns a list of all (client_arb_id, server_arb_id) pairs found. :param min_id: start arbitration ID value :param max_id: end arbitration ID value :param blacklist_args: blacklist for arbitration ID values :param auto_blacklist_duration: seconds to scan for interfering arbitration IDs to blacklist automatically :param delay: delay between each message :param verify: whether found arbitration IDs should be verified :param print_results: whether results should be printed to stdout :type min_id: int :type max_id: int :type blacklist_args: [int] :type auto_blacklist_duration: float :type delay: float :type verify: bool :type print_results: bool :return: list of (client_arbitration_id, server_arbitration_id) pairs :rtype [(int, int)] """ # Set defaults #-E为扩展帧 if E: max_id = ARBITRATION_ID_MAX_EXTENDED min_id = ARBITRATION_ID_MIN_EXTENDED elif min_id is None: min_id = ARBITRATION_ID_MIN max_id = ARBITRATION_ID_MAX if auto_blacklist_duration is None: auto_blacklist_duration = 0 if blacklist_args is None: blacklist_args = [] # Sanity checks if max_id < min_id: raise ValueError("max_id must not be smaller than min_id -" " got min:0x{0:x}, max:0x{1:x}".format(min_id, max_id)) if auto_blacklist_duration < 0: raise ValueError("auto_blacklist_duration must not be smaller " "than 0, got {0}'".format(auto_blacklist_duration)) diagnostic_session_control = Services.DiagnosticSessionControl service_id = diagnostic_session_control.service_id sub_function = diagnostic_session_control.DiagnosticSessionType.DEFAULT_SESSION session_control_data = [service_id, sub_function] valid_session_control_responses = [0x50, 0x7F] def is_valid_response(message): return (len(message.data) >= 2 and message.data[1] in valid_session_control_responses) found_arbitration_ids = []
''' module_template.py This file contains a template for a simple CaringCaribou module. The module's entry point is the 'module_main' function. Steps to add this module to CaringCaribou and run it: 1. Copy this template into the `caringcaribou/modules` directory: $ cp module_template.py my_module.py 2. In `setup.py`, add an entry under `caringcaribou.modules`, referencing your new module like: `my_module = caringcaribou.modules.my_module` 3. Run: `setup.py install` 4. Verify that the module is available, it should be listed in the output of `cc.py -h` 5. Run the following command to run module and show usage instructions: $ cc.py my_module -h ''' from __future__ import print_function # Handle large ranges efficiently in both python 2 and 3 if version_info[0] == 2: range = xrange UDS_SERVICE_NAMES = { 0x10: "DIAGNOSTIC_SESSION_CONTROL", 0x11: "ECU_RESET", 0x14: "CLEAR_DIAGNOSTIC_INFORMATION", 0x19: "READ_DTC_INFORMATION", 0x20: "RETURN_TO_NORMAL", 0x22: "READ_DATA_BY_IDENTIFIER", 0x23: "READ_MEMORY_BY_ADDRESS", 0x24: "READ_SCALING_DATA_BY_IDENTIFIER", 0x27: "SECURITY_ACCESS", 0x28: "COMMUNICATION_CONTROL", 0x2A: "READ_DATA_BY_PERIODIC_IDENTIFIER", 0x2C: "DYNAMICALLY_DEFINE_DATA_IDENTIFIER", 0x2D: "DEFINE_PID_BY_MEMORY_ADDRESS", 0x2E: "WRITE_DATA_BY_IDENTIFIER", 0x2F: "INPUT_OUTPUT_CONTROL_BY_IDENTIFIER", 0x31: "ROUTINE_CONTROL", 0x34: "REQUEST_DOWNLOAD", 0x35: "REQUEST_UPLOAD", 0x36: "TRANSFER_DATA", 0x37: "REQUEST_TRANSFER_EXIT", 0x38: "REQUEST_FILE_TRANSFER", 0x3D: "WRITE_MEMORY_BY_ADDRESS", 0x3E: "TESTER_PRESENT", 0x7F: "NEGATIVE_RESPONSE", 0x83: "ACCESS_TIMING_PARAMETER", 0x84: "SECURED_DATA_TRANSMISSION", 0x85: "CONTROL_DTC_SETTING", 0x86: "RESPONSE_ON_EVENT", 0x87: "LINK_CONTROL" } NRC_NAMES = { 0x00: "POSITIVE_RESPONSE", 0x10: "GENERAL_REJECT", 0x11: "SERVICE_NOT_SUPPORTED", 0x12: "SUB_FUNCTION_NOT_SUPPORTED", 0x13: "INCORRECT_MESSAGE_LENGTH_OR_INVALID_FORMAT", 0x14: "RESPONSE_TOO_LONG", 0x21: "BUSY_REPEAT_REQUEST", 0x22: "CONDITIONS_NOT_CORRECT", 0x24: "REQUEST_SEQUENCE_ERROR", 0x25: "NO_RESPONSE_FROM_SUBNET_COMPONENT", 0x26: "FAILURE_PREVENTS_EXECUTION_OF_REQUESTED_ACTION", 0x31: "REQUEST_OUT_OF_RANGE", 0x33: "SECURITY_ACCESS_DENIED", 0x35: "INVALID_KEY", 0x36: "EXCEEDED_NUMBER_OF_ATTEMPTS", 0x37: "REQUIRED_TIME_DELAY_NOT_EXPIRED", 0x70: "UPLOAD_DOWNLOAD_NOT_ACCEPTED", 0x71: "TRANSFER_DATA_SUSPENDED", 0x72: "GENERAL_PROGRAMMING_FAILURE", 0x73: "WRONG_BLOCK_SEQUENCE_COUNTER", 0x78: "REQUEST_CORRECTLY_RECEIVED_RESPONSE_PENDING", 0x7E: "SUB_FUNCTION_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x7F: "SERVICE_NOT_SUPPORTED_IN_ACTIVE_SESSION", 0x81: "RPM_TOO_HIGH", 0x82: "RPM_TOO_LOW", 0x83: "ENGINE_IS_RUNNING", 0x84: "ENGINE_IS_NOT_RUNNING", 0x85: "ENGINE_RUN_TIME_TOO_LOW", 0x86: "TEMPERATURE_TOO_HIGH", 0x87: "TEMPERATURE_TOO_LOW", 0x88: "VEHICLE_SPEED_TOO_HIGH", 0x89: "VEHICLE_SPEED_TOO_LOW", 0x8A: "THROTTLE_PEDAL_TOO_HIGH", 0x8B: "THROTTLE_PEDAL_TOO_LOW", 0x8C: "TRANSMISSION_RANGE_NOT_IN_NEUTRAL", 0x8D: "TRANSMISSION_RANGE_NOT_IN_GEAR", 0x8F: "BRAKE_SWITCHES_NOT_CLOSED", 0x90: "SHIFT_LEVER_NOT_IN_PARK", 0x91: "TORQUE_CONVERTER_CLUTCH_LOCKED", 0x92: "VOLTAGE_TOO_HIGH", 0x93: "VOLTAGE_TOO_LOW" } DELAY_DISCOVERY = 0.01 DELAY_TESTER_PRESENT = 0.5 DELAY_SECSEED_RESET = 0.01 TIMEOUT_SERVICES = 0.2 TIMEOUT_SUBSERVICES = 0.02 # Max number of arbitration IDs to backtrack during verification VERIFICATION_BACKTRACK = 5 # Extra time in seconds to wait for responses during verification VERIFICATION_EXTRA_DELAY = 0.5 BYTE_MIN = 0x00 BYTE_MAX = 0xFF DUMP_DID_MIN = 0x0000 DUMP_DID_MAX = 0xFFFF DUMP_DID_TIMEOUT = 0.2 def uds_discovery(E, min_id, max_id, blacklist_args, auto_blacklist_duration, delay, verify, print_results=True): """Scans for diagnostics support by brute forcing session control messages to different arbitration IDs. Returns a list of all (client_arb_id, server_arb_id) pairs found. :param min_id: start arbitration ID value :param max_id: end arbitration ID value :param blacklist_args: blacklist for arbitration ID values :param auto_blacklist_duration: seconds to scan for interfering arbitration IDs to blacklist automatically :param delay: delay between each message :param verify: whether found arbitration IDs should be verified :param print_results: whether results should be printed to stdout :type min_id: int :type max_id: int :type blacklist_args: [int] :type auto_blacklist_duration: float :type delay: float :type verify: bool :type print_results: bool :return: list of (client_arbitration_id, server_arbitration_id) pairs :rtype [(int, int)] """ # Set defaults #-E为扩展帧 if E: max_id = ARBITRATION_ID_MAX_EXTENDED min_id = ARBITRATION_ID_MIN_EXTENDED elif min_id is None: min_id = ARBITRATION_ID_MIN max_id = ARBITRATION_ID_MAX if auto_blacklist_duration is None: auto_blacklist_duration = 0 if blacklist_args is None: blacklist_args = [] # Sanity checks if max_id < min_id: raise ValueError("max_id must not be smaller than min_id -" " got min:0x{0:x}, max:0x{1:x}".format(min_id, max_id)) if auto_blacklist_duration < 0: raise ValueError("auto_blacklist_duration must not be smaller " "than 0, got {0}'".format(auto_blacklist_duration)) diagnostic_session_control = Services.DiagnosticSessionControl service_id = diagnostic_session_control.service_id sub_function = diagnostic_session_control.DiagnosticSessionType.DEFAULT_SESSION session_control_data = [service_id, sub_function] valid_session_control_responses = [0x50, 0x7F] def is_valid_response(message): return (len(message.data) >= 2 and message.data[1] in valid_session_control_responses) found_arbitration_ids = []
with IsoTp(None, None) as tp:
7
2023-11-13 05:05:46+00:00
16k
L1bra1/WeakMotion
train_WeakMotionNet.py
[ { "identifier": "WeakMotionNet", "path": "weak_model.py", "snippet": "class WeakMotionNet(nn.Module):\n def __init__(self, out_seq_len=1, FGBG_category_num=2, height_feat_size=13):\n super(WeakMotionNet, self).__init__()\n self.out_seq_len = out_seq_len\n\n self.motion_pred = Mot...
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import time import sys import argparse import os from shutil import copytree, copy from weak_model import WeakMotionNet from data.weak_nuscenes_dataloader import DatasetSingleSeq_Stage2 from data.weak_waymo_dataloader import DatasetSingleSeq_Stage2 as DatasetSingleSeq_Stage2_waymo from sklearn.metrics import confusion_matrix from tqdm import tqdm from loss_utils import FGBG_seg_loss, CCD_loss from evaluation_utils import evaluate_FGBG_prediction, evaluate_motion_prediction
12,365
saver.write("GPU number: {}\n".format(torch.cuda.device_count())) saver.flush() # Logging the details for this experiment saver.write("command line: {}\n".format(" ".join(sys.argv[1:]))) saver.write(args.__repr__() + "\n\n") saver.flush() # Specify gpu device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device_num = torch.cuda.device_count() print("device number", device_num) voxel_size = (0.25, 0.25, 0.4) if datatype == 'nuScenes': area_extents = np.array([[-32., 32.], [-32., 32.], [-3., 2.]]) elif datatype == 'Waymo': area_extents = np.array([[-32., 32.], [-32., 32.], [-1., 4.]]) tmp = args.motiondata trainset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': trainset = DatasetSingleSeq_Stage2(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': trainset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=num_workers) print("Training dataset size:", len(trainset)) tmp = args.evaldata evalset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': evalset = DatasetSingleSeq_Stage2(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': evalset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) evalloader = torch.utils.data.DataLoader(evalset, batch_size=1, shuffle=False, num_workers=num_workers) print("Training dataset size:", len(trainset)) model = WeakMotionNet(out_seq_len=out_seq_len, FGBG_category_num=2, height_feat_size=height_feat_size) model = nn.DataParallel(model) model = model.to(device) optimizer = optim.Adam(model.parameters(), lr=0.0005) scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[10, 20, 30, 40], gamma=0.5) if args.resume != '': checkpoint = torch.load(args.resume) start_epoch = checkpoint['epoch'] + 1 model.load_state_dict(checkpoint['model_state_dict']) print("Load model from {}, at epoch {}".format(args.resume, start_epoch - 1)) for epoch in range(start_epoch, num_epochs + 1): lr = optimizer.param_groups[0]['lr'] print("Epoch {}, learning rate {}".format(epoch, lr)) if need_log: saver.write("epoch: {}, lr: {}\t".format(epoch, lr)) saver.flush() model.train() loss_FGBG_seg, loss_disp = train(model, trainloader, optimizer, device, epoch, voxel_size, area_extents) model.eval() me_static, me_slow, me_fast, acc_bg, acc_fg = eval(model, evalloader, device) scheduler.step() if need_log: saver.write("loss_FGBG_seg:{}\t loss_disp:{}\n".format(loss_FGBG_seg, loss_disp)) saver.write("me_static:{}\t me_slow:{}\t me_fast:{}\n".format(me_static, me_slow, me_fast)) saver.write("acc_bg:{}\t acc_fg:{}\n".format(acc_bg, acc_fg)) saver.flush() # save model if need_log and (epoch >= 30): save_dict = {'epoch': epoch, 'model_state_dict': model.state_dict(), 'loss_FGBG_seg': loss_FGBG_seg.avg, 'loss_disp': loss_disp.avg} torch.save(save_dict, os.path.join(model_save_path, 'epoch_' + str(epoch) + '_%.3f_%.3f_%.3f_%.3f_%.3f'%(me_static, me_slow, me_fast, acc_bg, acc_fg) + '.pth')) if need_log: saver.close() def train(model, trainloader, optimizer, device, epoch, voxel_size, area_extents): running_loss_FGBG_seg = AverageMeter('FGBG_Seg', ':.6f') # for cell FG/BG segmentation error running_loss_disp= AverageMeter('disp', ':.6f') # for cell motion prediction error # for i, data in enumerate(trainloader, 0): for i, data in tqdm(enumerate(trainloader, 0), total=len(trainloader), smoothing=0.9): padded_voxel_points, _, _, \ non_empty_map, _, _, \ pc_seg, point_FGBG_gt_mask_seg, curr_seg_num, \ FG_point_0, FG_point_num_0, FG_point_1, FG_point_num_1, FG_point_2, FG_point_num_2 = data optimizer.zero_grad() # Move to GPU/CPU padded_voxel_points = padded_voxel_points.to(device) non_empty_map = non_empty_map.to(device) # Make prediction disp_pred, FGBG_pred = model(padded_voxel_points) # Compute and back-propagate the losses loss_FGBG_seg = FGBG_seg_loss(FGBG_pred, point_FGBG_gt_mask_seg, pc_seg, curr_seg_num, voxel_size, area_extents)
""" Train WeakMotionNet in Stage2 Some of the code are modified based on 'train_single_seq.py' in MotionNet. Reference: MotionNet (https://www.merl.com/research/?research=license-request&sw=MotionNet) """ class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def __str__(self): fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' return fmtstr.format(**self.__dict__) def check_folder(folder_path): if not os.path.exists(folder_path): os.mkdir(folder_path) return folder_path out_seq_len = 1 # The number of future frames we are going to predict height_feat_size = 13 # The size along the height dimension parser = argparse.ArgumentParser() parser.add_argument('-md', '--motiondata', default='/path_to/nuScenes/input-data/train/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-wd', '--weakdata', default='/path_to/nuScenes/weak-data/train/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('-FBd', '--FBdata', default='/path_to/nuScenes/FGBG-data/nuscenes_seg_0-01/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--datatype', default='nuScenes', type=str, choices=['Waymo', 'nuScenes']) parser.add_argument('-t', '--evaldata', default='/path_to/nuScenes/input-data/val/', type=str, help='The path to the preprocessed sparse BEV training data') parser.add_argument('--resume', default='', type=str, help='The path to the saved model that is loaded to resume training') parser.add_argument('--batch', default=8, type=int, help='Batch size') parser.add_argument('--nepoch', default=60, type=int, help='Number of epochs') parser.add_argument('--nworker', default=4, type=int, help='Number of workers') parser.add_argument('--log', default=True, action='store_true', help='Whether to log') parser.add_argument('--logpath', default='', help='The path to the output log file') parser.add_argument('--gpu', default='1') parser.add_argument('--annotation_ratio', default=0.01, type=float) args = parser.parse_args() print(args) num_epochs = args.nepoch need_log = args.log BATCH_SIZE = args.batch num_workers = args.nworker os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu datatype = args.datatype annotation_ratio = args.annotation_ratio def main(): start_epoch = 1 # Whether to log the training information if need_log: logger_root = args.logpath if args.logpath != '' else 'logs' time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S") if args.resume == '': model_save_path = check_folder(logger_root) model_save_path = check_folder(os.path.join(model_save_path, 'Stage2')) model_save_path = check_folder(os.path.join(model_save_path, time_stamp)) log_file_name = os.path.join(model_save_path, 'log.txt') saver = open(log_file_name, "w") saver.write("GPU number: {}\n".format(torch.cuda.device_count())) saver.flush() # Logging the details for this experiment saver.write("command line: {}\n".format(" ".join(sys.argv[0:]))) saver.write(args.__repr__() + "\n\n") saver.flush() else: model_save_path = args.resume log_file_name = os.path.join(model_save_path, 'log.txt') saver = open(log_file_name, "a") saver.write("GPU number: {}\n".format(torch.cuda.device_count())) saver.flush() # Logging the details for this experiment saver.write("command line: {}\n".format(" ".join(sys.argv[1:]))) saver.write(args.__repr__() + "\n\n") saver.flush() # Specify gpu device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") device_num = torch.cuda.device_count() print("device number", device_num) voxel_size = (0.25, 0.25, 0.4) if datatype == 'nuScenes': area_extents = np.array([[-32., 32.], [-32., 32.], [-3., 2.]]) elif datatype == 'Waymo': area_extents = np.array([[-32., 32.], [-32., 32.], [-1., 4.]]) tmp = args.motiondata trainset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': trainset = DatasetSingleSeq_Stage2(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': trainset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.motiondata, weakdata_root=args.weakdata, FBdata_root=args.FBdata, split=trainset_split, annotation_ratio=annotation_ratio, voxel_size=voxel_size, area_extents=area_extents) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=num_workers) print("Training dataset size:", len(trainset)) tmp = args.evaldata evalset_split = tmp.split('/')[-1] if tmp.split('/')[-1] is not '' else tmp.split('/')[-2] if datatype == 'nuScenes': evalset = DatasetSingleSeq_Stage2(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) elif datatype == 'Waymo': evalset = DatasetSingleSeq_Stage2_waymo(dataset_root=args.evaldata, split=evalset_split, voxel_size=voxel_size, area_extents=area_extents) evalloader = torch.utils.data.DataLoader(evalset, batch_size=1, shuffle=False, num_workers=num_workers) print("Training dataset size:", len(trainset)) model = WeakMotionNet(out_seq_len=out_seq_len, FGBG_category_num=2, height_feat_size=height_feat_size) model = nn.DataParallel(model) model = model.to(device) optimizer = optim.Adam(model.parameters(), lr=0.0005) scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[10, 20, 30, 40], gamma=0.5) if args.resume != '': checkpoint = torch.load(args.resume) start_epoch = checkpoint['epoch'] + 1 model.load_state_dict(checkpoint['model_state_dict']) print("Load model from {}, at epoch {}".format(args.resume, start_epoch - 1)) for epoch in range(start_epoch, num_epochs + 1): lr = optimizer.param_groups[0]['lr'] print("Epoch {}, learning rate {}".format(epoch, lr)) if need_log: saver.write("epoch: {}, lr: {}\t".format(epoch, lr)) saver.flush() model.train() loss_FGBG_seg, loss_disp = train(model, trainloader, optimizer, device, epoch, voxel_size, area_extents) model.eval() me_static, me_slow, me_fast, acc_bg, acc_fg = eval(model, evalloader, device) scheduler.step() if need_log: saver.write("loss_FGBG_seg:{}\t loss_disp:{}\n".format(loss_FGBG_seg, loss_disp)) saver.write("me_static:{}\t me_slow:{}\t me_fast:{}\n".format(me_static, me_slow, me_fast)) saver.write("acc_bg:{}\t acc_fg:{}\n".format(acc_bg, acc_fg)) saver.flush() # save model if need_log and (epoch >= 30): save_dict = {'epoch': epoch, 'model_state_dict': model.state_dict(), 'loss_FGBG_seg': loss_FGBG_seg.avg, 'loss_disp': loss_disp.avg} torch.save(save_dict, os.path.join(model_save_path, 'epoch_' + str(epoch) + '_%.3f_%.3f_%.3f_%.3f_%.3f'%(me_static, me_slow, me_fast, acc_bg, acc_fg) + '.pth')) if need_log: saver.close() def train(model, trainloader, optimizer, device, epoch, voxel_size, area_extents): running_loss_FGBG_seg = AverageMeter('FGBG_Seg', ':.6f') # for cell FG/BG segmentation error running_loss_disp= AverageMeter('disp', ':.6f') # for cell motion prediction error # for i, data in enumerate(trainloader, 0): for i, data in tqdm(enumerate(trainloader, 0), total=len(trainloader), smoothing=0.9): padded_voxel_points, _, _, \ non_empty_map, _, _, \ pc_seg, point_FGBG_gt_mask_seg, curr_seg_num, \ FG_point_0, FG_point_num_0, FG_point_1, FG_point_num_1, FG_point_2, FG_point_num_2 = data optimizer.zero_grad() # Move to GPU/CPU padded_voxel_points = padded_voxel_points.to(device) non_empty_map = non_empty_map.to(device) # Make prediction disp_pred, FGBG_pred = model(padded_voxel_points) # Compute and back-propagate the losses loss_FGBG_seg = FGBG_seg_loss(FGBG_pred, point_FGBG_gt_mask_seg, pc_seg, curr_seg_num, voxel_size, area_extents)
loss_disp = CCD_loss(disp_pred, FG_point_0, FG_point_num_0, FG_point_1, FG_point_num_1, FG_point_2, FG_point_num_2,
4
2023-11-12 07:03:29+00:00
16k
c3exchange/c3-smartcontracts-v1
contracts_unified/core/main.py
[ { "identifier": "update", "path": "contracts_unified/core/bare_calls/update.py", "snippet": "@Subroutine(TealType.none)\ndef update() -> Expr:\n \"\"\"Implements the contract method called on update\"\"\"\n\n return sender_is_creator()" }, { "identifier": "delete", "path": "contracts_u...
from pyteal import ( BareCallActions, CallConfig, MethodConfig, OnCompleteAction, OptimizeOptions, Reject, Router, ) from contracts_unified.core.bare_calls import delete, update from contracts_unified.core.methods import ( account_move, add_order, clean_orders, create, deposit, fund_mbr, liquidate, pool_move, portal_transfer, settle, update_instrument, update_parameter, withdraw, wormhole_deposit, )
11,912
""" This file implements the router of the Core contract. """ CORE_ROUTER = Router( "C3 Core", BareCallActions( update_application=OnCompleteAction.always(update()), delete_application=OnCompleteAction.always(delete()), ), clear_state=Reject(), ) CORE_ROUTER.add_method_handler( create, "create", MethodConfig(no_op=CallConfig.CREATE), "Create C3 Core contract", ) CORE_ROUTER.add_method_handler( update_instrument, "update_instrument", MethodConfig(no_op=CallConfig.CALL), "Add a new instrument (ASA) to the Core", ) CORE_ROUTER.add_method_handler( update_parameter, "update_parameter", MethodConfig(no_op=CallConfig.CALL), "Update a global parameter", ) CORE_ROUTER.add_method_handler( deposit, "deposit", MethodConfig(no_op=CallConfig.CALL), "Deposit assets to user account", ) CORE_ROUTER.add_method_handler( wormhole_deposit, "wormhole_deposit", MethodConfig(no_op=CallConfig.CALL), "Deposit assets to user account via Wormhole", ) CORE_ROUTER.add_method_handler( pool_move, "pool_move", MethodConfig(no_op=CallConfig.CALL), "Transfer instruments between user and pool", ) CORE_ROUTER.add_method_handler( add_order, "add_order", MethodConfig(no_op=CallConfig.CALL), "Add an order to the order book", ) CORE_ROUTER.add_method_handler( settle, "settle", MethodConfig(no_op=CallConfig.CALL), "Settle two orders" ) CORE_ROUTER.add_method_handler( withdraw, "withdraw", MethodConfig(no_op=CallConfig.CALL), "Withdraw funds from user account", ) CORE_ROUTER.add_method_handler(
""" This file implements the router of the Core contract. """ CORE_ROUTER = Router( "C3 Core", BareCallActions( update_application=OnCompleteAction.always(update()), delete_application=OnCompleteAction.always(delete()), ), clear_state=Reject(), ) CORE_ROUTER.add_method_handler( create, "create", MethodConfig(no_op=CallConfig.CREATE), "Create C3 Core contract", ) CORE_ROUTER.add_method_handler( update_instrument, "update_instrument", MethodConfig(no_op=CallConfig.CALL), "Add a new instrument (ASA) to the Core", ) CORE_ROUTER.add_method_handler( update_parameter, "update_parameter", MethodConfig(no_op=CallConfig.CALL), "Update a global parameter", ) CORE_ROUTER.add_method_handler( deposit, "deposit", MethodConfig(no_op=CallConfig.CALL), "Deposit assets to user account", ) CORE_ROUTER.add_method_handler( wormhole_deposit, "wormhole_deposit", MethodConfig(no_op=CallConfig.CALL), "Deposit assets to user account via Wormhole", ) CORE_ROUTER.add_method_handler( pool_move, "pool_move", MethodConfig(no_op=CallConfig.CALL), "Transfer instruments between user and pool", ) CORE_ROUTER.add_method_handler( add_order, "add_order", MethodConfig(no_op=CallConfig.CALL), "Add an order to the order book", ) CORE_ROUTER.add_method_handler( settle, "settle", MethodConfig(no_op=CallConfig.CALL), "Settle two orders" ) CORE_ROUTER.add_method_handler( withdraw, "withdraw", MethodConfig(no_op=CallConfig.CALL), "Withdraw funds from user account", ) CORE_ROUTER.add_method_handler(
portal_transfer,
9
2023-11-17 20:54:15+00:00
16k