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
yolain/ComfyUI-Easy-Use
py/easyNodes.py
[ { "identifier": "advanced_encode", "path": "py/adv_encode.py", "snippet": "def advanced_encode(clip, text, token_normalization, weight_interpretation, w_max=1.0, clip_balance=.5,\n apply_to_pooled=True):\n tokenized = clip.tokenize(text, return_word_ids=True)\n if isinstance(cli...
import sys import os import re import json import time import math import torch import psutil import random import datetime import comfy.sd import comfy.utils import numpy as np import folder_paths import comfy.samplers import comfy.controlnet import latent_preview import comfy.model_base import comfy.model_management from pathlib import Path from comfy.sd import CLIP, VAE from comfy.cli_args import args from urllib.request import urlopen from collections import defaultdict from PIL.PngImagePlugin import PngInfo from PIL import Image, ImageDraw, ImageFont from comfy.model_patcher import ModelPatcher from comfy_extras.chainner_models import model_loading from typing import Dict, List, Optional, Tuple, Union, Any from .adv_encode import advanced_encode, advanced_encode_XL from server import PromptServer from nodes import VAELoader, MAX_RESOLUTION, RepeatLatentBatch, NODE_CLASS_MAPPINGS as ALL_NODE_CLASS_MAPPINGS, ConditioningSetMask from comfy_extras.nodes_mask import LatentCompositeMasked from .config import BASE_RESOLUTIONS from .log import log_node_info, log_node_error, log_node_warn, log_node_success from .wildcards import process_with_loras, get_wildcard_list from comfy_extras.nodes_stable3d import camera_embeddings from .gradual_latent_hires_fix import sample_dpmpp_2s_ancestral, sample_dpmpp_2m_sde, sample_lcm, sample_euler_ancestral from .dynthres_core import DynThresh
10,669
#---------------------------------------------------------------加载器 开始----------------------------------------------------------------------# # 简易加载器完整 class fullLoader: @classmethod def INPUT_TYPES(cls): resolution_strings = [f"{width} x {height}" for width, height in BASE_RESOLUTIONS] a1111_prompt_style_default = False return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"),), "config_name": (["Default", ] + folder_paths.get_filename_list("configs"), {"default": "Default"}), "vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),), "clip_skip": ("INT", {"default": -1, "min": -24, "max": 0, "step": 1}), "lora_name": (["None"] + folder_paths.get_filename_list("loras"),), "lora_model_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "lora_clip_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "resolution": (resolution_strings,), "empty_latent_width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "empty_latent_height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "positive": ("STRING", {"default": "Positive", "multiline": True}), "positive_token_normalization": (["none", "mean", "length", "length+mean"],), "positive_weight_interpretation": (["comfy", "A1111", "comfy++", "compel", "fixed attention"],), "negative": ("STRING", {"default": "Negative", "multiline": True}), "negative_token_normalization": (["none", "mean", "length", "length+mean"],), "negative_weight_interpretation": (["comfy", "A1111", "comfy++", "compel", "fixed attention"],), "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), }, "optional": {"model_override": ("MODEL",), "clip_override": ("CLIP",), "vae_override": ("VAE",), "optional_lora_stack": ("LORA_STACK",), "a1111_prompt_style": ("BOOLEAN", {"default": a1111_prompt_style_default}),}, "hidden": {"prompt": "PROMPT", "my_unique_id": "UNIQUE_ID"} } RETURN_TYPES = ("PIPE_LINE", "MODEL", "VAE", "CLIP") RETURN_NAMES = ("pipe", "model", "vae", "clip") FUNCTION = "adv_pipeloader" CATEGORY = "EasyUse/Loaders" def adv_pipeloader(self, ckpt_name, config_name, vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength, resolution, empty_latent_width, empty_latent_height, positive, positive_token_normalization, positive_weight_interpretation, negative, negative_token_normalization, negative_weight_interpretation, batch_size, model_override=None, clip_override=None, vae_override=None, optional_lora_stack=None, a1111_prompt_style=False, prompt=None, my_unique_id=None ): model: ModelPatcher | None = None clip: CLIP | None = None vae: VAE | None = None can_load_lora = True pipe_lora_stack = [] # resolution if resolution != "自定义 x 自定义": try: width, height = map(int, resolution.split(' x ')) empty_latent_width = width empty_latent_height = height except ValueError: raise ValueError("Invalid base_resolution format.") # Create Empty Latent latent = torch.zeros([batch_size, 4, empty_latent_height // 8, empty_latent_width // 8]).cpu() samples = {"samples": latent} # Clean models from loaded_objects easyCache.update_loaded_objects(prompt) log_node_warn("正在处理模型...") # 判断是否存在 模型叠加xyplot, 若存在优先缓存第一个模型 xyinputs_id = next((x for x in prompt if str(prompt[x]["class_type"]) == "easy XYInputs: ModelMergeBlocks"), None) if xyinputs_id is not None: node = prompt[xyinputs_id] if "ckpt_name_1" in node["inputs"]: ckpt_name_1 = node["inputs"]["ckpt_name_1"] model, clip, vae = easyCache.load_checkpoint(ckpt_name_1) can_load_lora = False # Load models elif model_override is not None and clip_override is not None and vae_override is not None: model = model_override clip = clip_override vae = vae_override elif model_override is not None: raise Exception(f"[ERROR] clip or vae is missing") elif vae_override is not None: raise Exception(f"[ERROR] model or clip is missing") elif clip_override is not None: raise Exception(f"[ERROR] model or vae is missing") else: model, clip, vae = easyCache.load_checkpoint(ckpt_name, config_name) if optional_lora_stack is not None: for lora in optional_lora_stack: if can_load_lora: model, clip = easyCache.load_lora(lora[0], model, clip, lora[1], lora[2]) pipe_lora_stack.append({"lora_name": lora[0], "model": model, "clip": clip, "lora_model_strength": lora[1], "lora_clip_strength": lora[2]}) if lora_name != "None": if can_load_lora: model, clip = easyCache.load_lora(lora_name, model, clip, lora_model_strength, lora_clip_strength) pipe_lora_stack.append({"lora_name": lora_name, "model": model, "clip": clip, "lora_model_strength": lora_model_strength, "lora_clip_strength": lora_clip_strength}) # Check for custom VAE if vae_name not in ["Baked VAE", "Baked-VAE"]: vae = easyCache.load_vae(vae_name) # CLIP skip if not clip: raise Exception("No CLIP found") log_node_warn("正在处理提示词...") positive_seed = find_wildcards_seed(positive, prompt)
# 加载器 class easyLoader: def __init__(self): self.loaded_objects = { "ckpt": defaultdict(tuple), # {ckpt_name: (model, ...)} "clip": defaultdict(tuple), "clip_vision": defaultdict(tuple), "bvae": defaultdict(tuple), "vae": defaultdict(object), "lora": defaultdict(dict), # {lora_name: {UID: (model_lora, clip_lora)}} } self.memory_threshold = self.determine_memory_threshold(0.7) def clean_values(self, values: str): original_values = values.split("; ") cleaned_values = [] for value in original_values: cleaned_value = value.strip(';').strip() if cleaned_value == "": continue try: cleaned_value = int(cleaned_value) except ValueError: try: cleaned_value = float(cleaned_value) except ValueError: pass cleaned_values.append(cleaned_value) return cleaned_values def clear_unused_objects(self, desired_names: set, object_type: str): keys = set(self.loaded_objects[object_type].keys()) for key in keys - desired_names: del self.loaded_objects[object_type][key] def get_input_value(self, entry, key): val = entry["inputs"][key] return val if isinstance(val, str) else val[0] def process_pipe_loader(self, entry, desired_ckpt_names, desired_vae_names, desired_lora_names, desired_lora_settings, num_loras=3, suffix=""): for idx in range(1, num_loras + 1): lora_name_key = f"{suffix}lora{idx}_name" desired_lora_names.add(self.get_input_value(entry, lora_name_key)) setting = f'{self.get_input_value(entry, lora_name_key)};{entry["inputs"][f"{suffix}lora{idx}_model_strength"]};{entry["inputs"][f"{suffix}lora{idx}_clip_strength"]}' desired_lora_settings.add(setting) desired_ckpt_names.add(self.get_input_value(entry, f"{suffix}ckpt_name")) desired_vae_names.add(self.get_input_value(entry, f"{suffix}vae_name")) def update_loaded_objects(self, prompt): desired_ckpt_names = set() desired_vae_names = set() desired_lora_names = set() desired_lora_settings = set() for entry in prompt.values(): class_type = entry["class_type"] if class_type == "easy a1111Loader" or class_type == "easy comfyLoader": lora_name = self.get_input_value(entry, "lora_name") desired_lora_names.add(lora_name) setting = f'{lora_name};{entry["inputs"]["lora_model_strength"]};{entry["inputs"]["lora_clip_strength"]}' desired_lora_settings.add(setting) desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name")) desired_vae_names.add(self.get_input_value(entry, "vae_name")) elif class_type == "easy zero123Loader" or class_type == 'easy svdLoader': desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name")) desired_vae_names.add(self.get_input_value(entry, "vae_name")) elif class_type == "easy XYInputs: ModelMergeBlocks": desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name_1")) desired_ckpt_names.add(self.get_input_value(entry, "ckpt_name_2")) vae_use = self.get_input_value(entry, "vae_use") if vae_use != 'Use Model 1' and vae_use != 'Use Model 2': desired_vae_names.add(vae_use) object_types = ["ckpt", "clip", "bvae", "vae", "lora"] for object_type in object_types: desired_names = desired_ckpt_names if object_type in ["ckpt", "clip", "bvae"] else desired_vae_names if object_type == "vae" else desired_lora_names self.clear_unused_objects(desired_names, object_type) def add_to_cache(self, obj_type, key, value): """ Add an item to the cache with the current timestamp. """ timestamped_value = (value, time.time()) self.loaded_objects[obj_type][key] = timestamped_value def determine_memory_threshold(self, percentage=0.8): """ Determines the memory threshold as a percentage of the total available memory. Args: - percentage (float): The fraction of total memory to use as the threshold. Should be a value between 0 and 1. Default is 0.8 (80%). Returns: - memory_threshold (int): Memory threshold in bytes. """ total_memory = psutil.virtual_memory().total memory_threshold = total_memory * percentage return memory_threshold def get_memory_usage(self): """ Returns the memory usage of the current process in bytes. """ process = psutil.Process(os.getpid()) return process.memory_info().rss def eviction_based_on_memory(self): """ Evicts objects from cache based on memory usage and priority. """ current_memory = self.get_memory_usage() if current_memory < self.memory_threshold: return eviction_order = ["vae", "lora", "bvae", "clip", "ckpt"] for obj_type in eviction_order: if current_memory < self.memory_threshold: break # Sort items based on age (using the timestamp) items = list(self.loaded_objects[obj_type].items()) items.sort(key=lambda x: x[1][1]) # Sorting by timestamp for item in items: if current_memory < self.memory_threshold: break del self.loaded_objects[obj_type][item[0]] current_memory = self.get_memory_usage() def load_checkpoint(self, ckpt_name, config_name=None, load_vision=False): cache_name = ckpt_name if config_name not in [None, "Default"]: cache_name = ckpt_name + "_" + config_name if cache_name in self.loaded_objects["ckpt"]: cache_out = self.loaded_objects["clip_vision"][cache_name][0] if load_vision else self.loaded_objects["clip"][cache_name][0] return self.loaded_objects["ckpt"][cache_name][0], cache_out, self.loaded_objects["bvae"][cache_name][0] ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name) output_clip = False if load_vision else True output_clipvision = True if load_vision else False if config_name not in [None, "Default"]: config_path = folder_paths.get_full_path("configs", config_name) loaded_ckpt = comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=output_clip, output_clipvision=output_clipvision, embedding_directory=folder_paths.get_folder_paths("embeddings")) else: loaded_ckpt = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=output_clip, output_clipvision=output_clipvision, embedding_directory=folder_paths.get_folder_paths("embeddings")) self.add_to_cache("ckpt", cache_name, loaded_ckpt[0]) self.add_to_cache("bvae", cache_name, loaded_ckpt[2]) if load_vision: out = loaded_ckpt[3] self.add_to_cache("clip_vision", cache_name, out) else: out = loaded_ckpt[1] self.add_to_cache("clip", cache_name, loaded_ckpt[1]) self.eviction_based_on_memory() return loaded_ckpt[0], out, loaded_ckpt[2] def load_vae(self, vae_name): if vae_name in self.loaded_objects["vae"]: return self.loaded_objects["vae"][vae_name][0] vae_path = folder_paths.get_full_path("vae", vae_name) sd = comfy.utils.load_torch_file(vae_path) loaded_vae = comfy.sd.VAE(sd=sd) self.add_to_cache("vae", vae_name, loaded_vae) self.eviction_based_on_memory() return loaded_vae def load_lora(self, lora_name, model, clip, strength_model, strength_clip): model_hash = str(model)[44:-1] clip_hash = str(clip)[25:-1] unique_id = f'{model_hash};{clip_hash};{lora_name};{strength_model};{strength_clip}' if unique_id in self.loaded_objects["lora"] and unique_id in self.loaded_objects["lora"][lora_name]: return self.loaded_objects["lora"][unique_id][0] lora_path = folder_paths.get_full_path("loras", lora_name) lora = comfy.utils.load_torch_file(lora_path, safe_load=True) model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip) self.add_to_cache("lora", unique_id, (model_lora, clip_lora)) self.eviction_based_on_memory() return model_lora, clip_lora # 采样器 class easySampler: def __init__(self): self.last_helds: dict[str, list] = { "results": [], "pipe_line": [], } @staticmethod def tensor2pil(image: torch.Tensor) -> Image.Image: """Convert a torch tensor to a PIL image.""" return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) @staticmethod def pil2tensor(image: Image.Image) -> torch.Tensor: """Convert a PIL image to a torch tensor.""" return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0) @staticmethod def enforce_mul_of_64(d): d = int(d) if d <= 7: d = 8 leftover = d % 8 # 8 is the number of pixels per byte if leftover != 0: # if the number of pixels is not a multiple of 8 if (leftover < 4): # if the number of pixels is less than 4 d -= leftover # remove the leftover pixels else: # if the number of pixels is more than 4 d += 8 - leftover # add the leftover pixels return int(d) @staticmethod def safe_split(to_split: str, delimiter: str) -> List[str]: """Split the input string and return a list of non-empty parts.""" parts = to_split.split(delimiter) parts = [part for part in parts if part not in ('', ' ', ' ')] while len(parts) < 2: parts.append('None') return parts def common_ksampler(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False, preview_latent=True, disable_pbar=False): device = comfy.model_management.get_torch_device() latent_image = latent["samples"] if disable_noise: noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu") else: batch_inds = latent["batch_index"] if "batch_index" in latent else None noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds) noise_mask = None if "noise_mask" in latent: noise_mask = latent["noise_mask"] preview_format = "JPEG" if preview_format not in ["JPEG", "PNG"]: preview_format = "JPEG" previewer = False if preview_latent: previewer = latent_preview.get_previewer(device, model.model.latent_format) pbar = comfy.utils.ProgressBar(steps) def callback(step, x0, x, total_steps): preview_bytes = None if previewer: preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0) pbar.update_absolute(step + 1, total_steps, preview_bytes) samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) out = latent.copy() out["samples"] = samples return out def custom_ksampler(self, model, seed, steps, cfg, _sampler, sigmas, positive, negative, latent, disable_noise=False, preview_latent=True, disable_pbar=False): device = comfy.model_management.get_torch_device() latent_image = latent["samples"] if disable_noise: noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu") else: batch_inds = latent["batch_index"] if "batch_index" in latent else None noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds) noise_mask = None if "noise_mask" in latent: noise_mask = latent["noise_mask"] preview_format = "JPEG" if preview_format not in ["JPEG", "PNG"]: preview_format = "JPEG" previewer = False if preview_latent: previewer = latent_preview.get_previewer(device, model.model.latent_format) pbar = comfy.utils.ProgressBar(steps) def callback(step, x0, x, total_steps): preview_bytes = None if previewer: preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0) pbar.update_absolute(step + 1, total_steps, preview_bytes) samples = comfy.sample.sample_custom(model, noise, cfg, _sampler, sigmas, positive, negative, latent_image, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) out = latent.copy() out["samples"] = samples return out def get_value_by_id(self, key: str, my_unique_id: Any) -> Optional[Any]: """Retrieve value by its associated ID.""" try: for value, id_ in self.last_helds[key]: if id_ == my_unique_id: return value except KeyError: return None def update_value_by_id(self, key: str, my_unique_id: Any, new_value: Any) -> Union[bool, None]: """Update the value associated with a given ID. Return True if updated, False if appended, None if key doesn't exist.""" try: for i, (value, id_) in enumerate(self.last_helds[key]): if id_ == my_unique_id: self.last_helds[key][i] = (new_value, id_) return True self.last_helds[key].append((new_value, my_unique_id)) return False except KeyError: return False def upscale(self, samples, upscale_method, scale_by, crop): s = samples.copy() width = self.enforce_mul_of_64(round(samples["samples"].shape[3] * scale_by)) height = self.enforce_mul_of_64(round(samples["samples"].shape[2] * scale_by)) if (width > MAX_RESOLUTION): width = MAX_RESOLUTION if (height > MAX_RESOLUTION): height = MAX_RESOLUTION s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, crop) return (s,) def handle_upscale(self, samples: dict, upscale_method: str, factor: float, crop: bool) -> dict: """Upscale the samples if the upscale_method is not set to 'None'.""" if upscale_method != "None": samples = self.upscale(samples, upscale_method, factor, crop)[0] return samples def init_state(self, my_unique_id: Any, key: str, default: Any) -> Any: """Initialize the state by either fetching the stored value or setting a default.""" value = self.get_value_by_id(key, my_unique_id) if value is not None: return value return default def get_output(self, pipe: dict,) -> Tuple: """Return a tuple of various elements fetched from the input pipe dictionary.""" return ( pipe, pipe.get("images"), pipe.get("model"), pipe.get("positive"), pipe.get("negative"), pipe.get("samples"), pipe.get("vae"), pipe.get("clip"), pipe.get("seed"), ) def get_output_sdxl(self, sdxl_pipe: dict) -> Tuple: """Return a tuple of various elements fetched from the input sdxl_pipe dictionary.""" return ( sdxl_pipe, sdxl_pipe.get("model"), sdxl_pipe.get("positive"), sdxl_pipe.get("negative"), sdxl_pipe.get("vae"), sdxl_pipe.get("refiner_model"), sdxl_pipe.get("refiner_positive"), sdxl_pipe.get("refiner_negative"), sdxl_pipe.get("refiner_vae"), sdxl_pipe.get("samples"), sdxl_pipe.get("clip"), sdxl_pipe.get("images"), sdxl_pipe.get("seed") ) # XY图表 class easyXYPlot: def __init__(self, xyPlotData, save_prefix, image_output, prompt, extra_pnginfo, my_unique_id): self.x_node_type, self.x_type = easySampler.safe_split(xyPlotData.get("x_axis"), ': ') self.y_node_type, self.y_type = easySampler.safe_split(xyPlotData.get("y_axis"), ': ') self.x_values = xyPlotData.get("x_vals") if self.x_type != "None" else [] self.y_values = xyPlotData.get("y_vals") if self.y_type != "None" else [] self.grid_spacing = xyPlotData.get("grid_spacing") self.latent_id = 0 self.output_individuals = xyPlotData.get("output_individuals") self.x_label, self.y_label = [], [] self.max_width, self.max_height = 0, 0 self.latents_plot = [] self.image_list = [] self.num_cols = len(self.x_values) if len(self.x_values) > 0 else 1 self.num_rows = len(self.y_values) if len(self.y_values) > 0 else 1 self.total = self.num_cols * self.num_rows self.num = 0 self.save_prefix = save_prefix self.image_output = image_output self.prompt = prompt self.extra_pnginfo = extra_pnginfo self.my_unique_id = my_unique_id # Helper Functions @staticmethod def define_variable(plot_image_vars, value_type, value, index): plot_image_vars[value_type] = value if value_type in ["seed", "Seeds++ Batch"]: value_label = f"{value}" else: value_label = f"{value_type}: {value}" if "ControlNet" in value_type: if "," in value: line = value.split(',') value_label = f"{value_type}: {line[2]}" if value_type in ["ModelMergeBlocks"]: if ":" in value: line = value.split(':') value_label = f"{line[0]}" elif len(value) > 16: value_label = f"ModelMergeBlocks {index + 1}" else: value_label = f"MMB: {value}" if value_type in ["Positive Prompt S/R"]: value_label = f"pos prompt {index + 1}" if index>0 else f"pos prompt" if value_type in ["Negative Prompt S/R"]: value_label = f"neg prompt {index + 1}" if index>0 else f"neg prompt" if value_type in ["steps", "cfg", "denoise", "clip_skip", "lora_model_strength", "lora_clip_strength"]: value_label = f"{value_type}: {value}" if value_type == "positive": value_label = f"pos prompt {index + 1}" elif value_type == "negative": value_label = f"neg prompt {index + 1}" return plot_image_vars, value_label @staticmethod def get_font(font_size): return ImageFont.truetype(str(Path(os.path.join(Path(__file__).parent.parent, 'resources/OpenSans-Medium.ttf'))), font_size) @staticmethod def update_label(label, value, num_items): if len(label) < num_items: return [*label, value] return label @staticmethod def rearrange_tensors(latent, num_cols, num_rows): new_latent = [] for i in range(num_rows): for j in range(num_cols): index = j * num_rows + i new_latent.append(latent[index]) return new_latent def calculate_background_dimensions(self): border_size = int((self.max_width // 8) * 1.5) if self.y_type != "None" or self.x_type != "None" else 0 bg_width = self.num_cols * (self.max_width + self.grid_spacing) - self.grid_spacing + border_size * ( self.y_type != "None") bg_height = self.num_rows * (self.max_height + self.grid_spacing) - self.grid_spacing + border_size * ( self.x_type != "None") x_offset_initial = border_size if self.y_type != "None" else 0 y_offset = border_size if self.x_type != "None" else 0 return bg_width, bg_height, x_offset_initial, y_offset def adjust_font_size(self, text, initial_font_size, label_width): font = self.get_font(initial_font_size) text_width, _ = font.getsize(text) scaling_factor = 0.9 if text_width > (label_width * scaling_factor): return int(initial_font_size * (label_width / text_width) * scaling_factor) else: return initial_font_size def create_label(self, img, text, initial_font_size, is_x_label=True, max_font_size=70, min_font_size=10): label_width = img.width if is_x_label else img.height # Adjust font size font_size = self.adjust_font_size(text, initial_font_size, label_width) font_size = min(max_font_size, font_size) # Ensure font isn't too large font_size = max(min_font_size, font_size) # Ensure font isn't too small label_height = int(font_size * 1.5) if is_x_label else font_size label_bg = Image.new('RGBA', (label_width, label_height), color=(255, 255, 255, 0)) d = ImageDraw.Draw(label_bg) font = self.get_font(font_size) # Check if text will fit, if not insert ellipsis and reduce text if d.textsize(text, font=font)[0] > label_width: while d.textsize(text + '...', font=font)[0] > label_width and len(text) > 0: text = text[:-1] text = text + '...' # Compute text width and height for multi-line text text_lines = text.split('\n') text_widths, text_heights = zip(*[d.textsize(line, font=font) for line in text_lines]) max_text_width = max(text_widths) total_text_height = sum(text_heights) # Compute position for each line of text lines_positions = [] current_y = 0 for line, line_width, line_height in zip(text_lines, text_widths, text_heights): text_x = (label_width - line_width) // 2 text_y = current_y + (label_height - total_text_height) // 2 current_y += line_height lines_positions.append((line, (text_x, text_y))) # Draw each line of text for line, (text_x, text_y) in lines_positions: d.text((text_x, text_y), line, fill='black', font=font) return label_bg def sample_plot_image(self, plot_image_vars, samples, preview_latent, latents_plot, image_list, disable_noise, start_step, last_step, force_full_denoise, x_value=None, y_value=None): model, clip, vae, positive, negative, seed, steps, cfg = None, None, None, None, None, None, None, None sampler_name, scheduler, denoise = None, None, None # 高级用法 if plot_image_vars["x_node_type"] == "advanced" or plot_image_vars["y_node_type"] == "advanced": if self.x_type == "Seeds++ Batch" or self.y_type == "Seeds++ Batch": seed = int(x_value) if self.x_type == "Seeds++ Batch" else int(y_value) if self.x_type == "Steps" or self.y_type == "Steps": steps = int(x_value) if self.x_type == "Steps" else int(y_value) if self.x_type == "StartStep" or self.y_type == "StartStep": start_step = int(x_value) if self.x_type == "StartStep" else int(y_value) if self.x_type == "EndStep" or self.y_type == "EndStep": last_step = int(x_value) if self.x_type == "EndStep" else int(y_value) if self.x_type == "CFG Scale" or self.y_type == "CFG Scale": cfg = float(x_value) if self.x_type == "CFG Scale" else float(y_value) if self.x_type == "Sampler" or self.y_type == "Sampler" or self.y_type == "Sampler & Scheduler": sampler_name = float(x_value) if self.x_type == "Sampler" or self.x_type == "Sampler & Scheduler" else float(y_value) if self.x_type == "Scheduler" or self.y_type == "Scheduler" or self.y_type == "Sampler & Scheduler": scheduler = float(x_value) if self.x_type == "Scheduler" or self.x_type == "Sampler & Scheduler" else float(y_value) if self.x_type == "Denoise" or self.y_type == "Denoise": denoise = float(x_value) if self.x_type == "Denoise" else float(y_value) # 模型叠加 if self.x_type == "ModelMergeBlocks" or self.y_type == "ModelMergeBlocks": ckpt_name_1, ckpt_name_2 = plot_image_vars['models'] model1, clip1, vae1 = easyCache.load_checkpoint(ckpt_name_1) model2, clip2, vae2 = easyCache.load_checkpoint(ckpt_name_2) xy_values = x_value if self.x_type == "ModelMergeBlocks" else y_value if ":" in xy_values: xy_line = xy_values.split(':') xy_values = xy_line[1] xy_arrs = xy_values.split(',') # ModelMergeBlocks if len(xy_arrs) == 3: input, middle, out = xy_arrs kwargs = { "input": input, "middle": middle, "out": out } elif len(xy_arrs) == 30: kwargs = {} kwargs["time_embed."] = xy_arrs[0] kwargs["label_emb."] = xy_arrs[1] for i in range(12): kwargs["input_blocks.{}.".format(i)] = xy_arrs[2+i] for i in range(3): kwargs["middle_block.{}.".format(i)] = xy_arrs[14+i] for i in range(12): kwargs["output_blocks.{}.".format(i)] = xy_arrs[17+i] kwargs["out."] = xy_arrs[29] else: raise Exception("ModelMergeBlocks weight length error") default_ratio = next(iter(kwargs.values())) m = model1.clone() kp = model2.get_key_patches("diffusion_model.") for k in kp: ratio = float(default_ratio) k_unet = k[len("diffusion_model."):] last_arg_size = 0 for arg in kwargs: if k_unet.startswith(arg) and last_arg_size < len(arg): ratio = float(kwargs[arg]) last_arg_size = len(arg) m.add_patches({k: kp[k]}, 1.0 - ratio, ratio) vae_use = plot_image_vars['vae_use'] clip = clip2 if vae_use == 'Use Model 2' else clip1 if vae_use == 'Use Model 2': vae = vae2 elif vae_use == 'Use Model 1': vae = vae1 else: (vae,) = VAELoader().load_vae(vae_use) model = m # 如果存在lora_stack叠加lora optional_lora_stack = plot_image_vars['lora_stack'] if optional_lora_stack is not None and optional_lora_stack != []: for lora in optional_lora_stack: lora_name = lora["lora_name"] model = model if model is not None else lora["model"] clip = clip if clip is not None else lora["clip"] lora_model_strength = lora["lora_model_strength"] lora_clip_strength = lora["lora_clip_strength"] if "lbw" in lora: lbw = lora["lbw"] lbw_a = lora["lbw_a"] lbw_b = lora["lbw_b"] cls = ALL_NODE_CLASS_MAPPINGS['LoraLoaderBlockWeight //Inspire'] model, clip, _ = cls().doit(model, clip, lora_name, lora_model_strength, lora_clip_strength, False, 0, lbw_a, lbw_b, "", lbw) model, clip = easyCache.load_lora(lora_name, model, clip, lora_model_strength, lora_clip_strength) # 处理clip clip = clip.clone() if plot_image_vars['clip_skip'] != 0: clip.clip_layer(plot_image_vars['clip_skip']) # 提示词 if "Positive" in self.x_type or "Positive" in self.y_type: if self.x_type == 'Positive Prompt S/R' or self.y_type == 'Positive Prompt S/R': positive = x_value if self.x_type == "Positive Prompt S/R" else y_value if plot_image_vars['a1111_prompt_style']: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = plot_image_vars['steps'] clip = clip if clip is not None else plot_image_vars["clip"] positive, = cls().encode(clip, positive, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception( f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: clip = clip if clip is not None else plot_image_vars["clip"] positive, positive_pooled = advanced_encode(clip, positive, plot_image_vars['positive_token_normalization'], plot_image_vars[ 'positive_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") positive = [[positive, {"pooled_output": positive_pooled}]] if "Negative" in self.x_type or "Negative" in self.y_type: if self.x_type == 'Negative Prompt S/R' or self.y_type == 'Negative Prompt S/R': negative = x_value if self.x_type == "Negative Prompt S/R" else y_value if plot_image_vars['a1111_prompt_style']: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = plot_image_vars['steps'] clip = clip if clip is not None else plot_image_vars["clip"] negative, = cls().encode(clip, negative, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception( f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: clip = clip if clip is not None else plot_image_vars["clip"] negative, negative_pooled = advanced_encode(clip, negative, plot_image_vars['negative_token_normalization'], plot_image_vars[ 'negative_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") negative = [[negative, {"pooled_output": negative_pooled}]] # ControlNet if "ControlNet" in self.x_type or "ControlNet" in self.y_type: _pipe = { "model": model if model is not None else plot_image_vars["model"], "positive": positive if positive is not None else plot_image_vars["positive_cond"], "negative": negative if negative is not None else plot_image_vars["negative_cond"], "vae": vae if vae is not None else plot_image_vars['vae'], "clip": clip if clip is not None else plot_image_vars['clip'], "samples": None, "images": None, "loader_settings": {} } cnet = plot_image_vars["cnet"] if "cnet" in plot_image_vars else None if cnet: strength, start_percent, end_percent = x_value.split(',') if "ControlNet" in self.x_type else y_value.split(',') strength = float(strength) start_percent = float(start_percent) end_percent = float(end_percent) for index, item in enumerate(cnet): control_net_names = item[0] image = item[1] for idx, control_net_name in enumerate(control_net_names): # print(control_net_name) _pipe, = controlnetAdvanced().controlnetApply(_pipe, image, control_net_name, None, strength, start_percent, end_percent) positive = _pipe['positive'] negative = _pipe['negative'] del _pipe # 简单用法 if plot_image_vars["x_node_type"] == "loader" or plot_image_vars["y_node_type"] == "loader": model, clip, vae = easyCache.load_checkpoint(plot_image_vars['ckpt_name']) if plot_image_vars['lora_name'] != "None": model, clip = easyCache.load_lora(plot_image_vars['lora_name'], model, clip, plot_image_vars['lora_model_strength'], plot_image_vars['lora_clip_strength']) # Check for custom VAE if plot_image_vars['vae_name'] not in ["Baked-VAE", "Baked VAE"]: vae = easyCache.load_vae(plot_image_vars['vae_name']) # CLIP skip if not clip: raise Exception("No CLIP found") clip = clip.clone() clip.clip_layer(plot_image_vars['clip_skip']) if plot_image_vars['a1111_prompt_style']: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = plot_image_vars['steps'] positive, = cls().encode(clip, plot_image_vars['positive'], "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) negative, = cls().encode(clip, plot_image_vars['negative'], "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception(f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: positive, positive_pooled = advanced_encode(clip, plot_image_vars['positive'], plot_image_vars['positive_token_normalization'], plot_image_vars['positive_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") positive = [[positive, {"pooled_output": positive_pooled}]] negative, negative_pooled = advanced_encode(clip, plot_image_vars['negative'], plot_image_vars['negative_token_normalization'], plot_image_vars['negative_weight_interpretation'], w_max=1.0, apply_to_pooled="enable") negative = [[negative, {"pooled_output": negative_pooled}]] model = model if model is not None else plot_image_vars["model"] clip = clip if clip is not None else plot_image_vars["clip"] vae = vae if vae is not None else plot_image_vars["vae"] positive = positive if positive is not None else plot_image_vars["positive_cond"] negative = negative if negative is not None else plot_image_vars["negative_cond"] seed = seed if seed is not None else plot_image_vars["seed"] steps = steps if steps is not None else plot_image_vars["steps"] cfg = cfg if cfg is not None else plot_image_vars["cfg"] sampler_name = sampler_name if sampler_name is not None else plot_image_vars["sampler_name"] scheduler = scheduler if scheduler is not None else plot_image_vars["scheduler"] denoise = denoise if denoise is not None else plot_image_vars["denoise"] # Sample samples = sampler.common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, samples, denoise=denoise, disable_noise=disable_noise, preview_latent=preview_latent, start_step=start_step, last_step=last_step, force_full_denoise=force_full_denoise) # Decode images and store latent = samples["samples"] # Add the latent tensor to the tensors list latents_plot.append(latent) # Decode the image image = vae.decode(latent).cpu() if self.output_individuals in [True, "True"]: easy_save = easySave(self.my_unique_id, self.prompt, self.extra_pnginfo) easy_save.images(image, self.save_prefix, self.image_output, group_id=self.num) # Convert the image from tensor to PIL Image and add it to the list pil_image = easySampler.tensor2pil(image) image_list.append(pil_image) # Update max dimensions self.max_width = max(self.max_width, pil_image.width) self.max_height = max(self.max_height, pil_image.height) # Return the touched variables return image_list, self.max_width, self.max_height, latents_plot # Process Functions def validate_xy_plot(self): if self.x_type == 'None' and self.y_type == 'None': log_node_warn(f'easyKsampler[{self.my_unique_id}]','No Valid Plot Types - Reverting to default sampling...') return False else: return True def get_latent(self, samples): # Extract the 'samples' tensor from the dictionary latent_image_tensor = samples["samples"] # Split the tensor into individual image tensors image_tensors = torch.split(latent_image_tensor, 1, dim=0) # Create a list of dictionaries containing the individual image tensors latent_list = [{'samples': image} for image in image_tensors] # Set latent only to the first latent of batch if self.latent_id >= len(latent_list): log_node_warn(f'easy kSampler[{self.my_unique_id}]',f'The selected latent_id ({self.latent_id}) is out of range.') log_node_warn(f'easy kSampler[{self.my_unique_id}]', f'Automatically setting the latent_id to the last image in the list (index: {len(latent_list) - 1}).') self.latent_id = len(latent_list) - 1 return latent_list[self.latent_id] def get_labels_and_sample(self, plot_image_vars, latent_image, preview_latent, start_step, last_step, force_full_denoise, disable_noise): for x_index, x_value in enumerate(self.x_values): plot_image_vars, x_value_label = self.define_variable(plot_image_vars, self.x_type, x_value, x_index) self.x_label = self.update_label(self.x_label, x_value_label, len(self.x_values)) if self.y_type != 'None': for y_index, y_value in enumerate(self.y_values): plot_image_vars, y_value_label = self.define_variable(plot_image_vars, self.y_type, y_value, y_index) self.y_label = self.update_label(self.y_label, y_value_label, len(self.y_values)) # ttNl(f'{CC.GREY}X: {x_value_label}, Y: {y_value_label}').t( # f'Plot Values {self.num}/{self.total} ->').p() self.image_list, self.max_width, self.max_height, self.latents_plot = self.sample_plot_image( plot_image_vars, latent_image, preview_latent, self.latents_plot, self.image_list, disable_noise, start_step, last_step, force_full_denoise, x_value, y_value) self.num += 1 else: # ttNl(f'{CC.GREY}X: {x_value_label}').t(f'Plot Values {self.num}/{self.total} ->').p() self.image_list, self.max_width, self.max_height, self.latents_plot = self.sample_plot_image( plot_image_vars, latent_image, preview_latent, self.latents_plot, self.image_list, disable_noise, start_step, last_step, force_full_denoise, x_value) self.num += 1 # Rearrange latent array to match preview image grid self.latents_plot = self.rearrange_tensors(self.latents_plot, self.num_cols, self.num_rows) # Concatenate the tensors along the first dimension (dim=0) self.latents_plot = torch.cat(self.latents_plot, dim=0) return self.latents_plot def plot_images_and_labels(self): # Calculate the background dimensions bg_width, bg_height, x_offset_initial, y_offset = self.calculate_background_dimensions() # Create the white background image background = Image.new('RGBA', (int(bg_width), int(bg_height)), color=(255, 255, 255, 255)) output_image = [] for row_index in range(self.num_rows): x_offset = x_offset_initial for col_index in range(self.num_cols): index = col_index * self.num_rows + row_index img = self.image_list[index] output_image.append(sampler.pil2tensor(img)) background.paste(img, (x_offset, y_offset)) # Handle X label if row_index == 0 and self.x_type != "None": label_bg = self.create_label(img, self.x_label[col_index], int(48 * img.width / 512)) label_y = (y_offset - label_bg.height) // 2 background.alpha_composite(label_bg, (x_offset, label_y)) # Handle Y label if col_index == 0 and self.y_type != "None": label_bg = self.create_label(img, self.y_label[row_index], int(48 * img.height / 512), False) label_bg = label_bg.rotate(90, expand=True) label_x = (x_offset - label_bg.width) // 2 label_y = y_offset + (img.height - label_bg.height) // 2 background.alpha_composite(label_bg, (label_x, label_y)) x_offset += img.width + self.grid_spacing y_offset += img.height + self.grid_spacing return (sampler.pil2tensor(background), output_image) easyCache = easyLoader() sampler = easySampler() def check_link_to_clip(node_id, clip_id, visited=None, node=None): """Check if a given node links directly or indirectly to a loader node.""" if visited is None: visited = set() if node_id in visited: return False visited.add(node_id) if "pipe" in node["inputs"]: link_ids = node["inputs"]["pipe"] for id in link_ids: if id != 0 and id == str(clip_id): return True return False def find_nearest_steps(clip_id, prompt): """Find the nearest KSampler or preSampling node that references the given id.""" for id in prompt: node = prompt[id] if "Sampler" in node["class_type"] or "sampler" in node["class_type"] or "Sampling" in node["class_type"]: # Check if this KSampler node directly or indirectly references the given CLIPTextEncode node if check_link_to_clip(id, clip_id, None, node): steps = node["inputs"]["steps"] if "steps" in node["inputs"] else 1 return steps return 1 def find_wildcards_seed(text, prompt): if "__" in text: for i in prompt: if "wildcards" in prompt[i]['class_type'] and text == prompt[i]['inputs']['text']: return prompt[i]['inputs']['seed_num'] if "seed_num" in prompt[i]['inputs'] else None else: return None class easySave: def __init__(self, my_unique_id=0, prompt=None, extra_pnginfo=None, number_padding=5, overwrite_existing=False, output_dir=folder_paths.get_temp_directory()): self.number_padding = int(number_padding) if number_padding not in [None, "None", 0] else None self.overwrite_existing = overwrite_existing self.my_unique_id = my_unique_id self.prompt = prompt self.extra_pnginfo = extra_pnginfo self.type = 'temp' self.output_dir = output_dir if self.output_dir != folder_paths.get_temp_directory(): self.output_dir = self.folder_parser(self.output_dir, self.prompt, self.my_unique_id) if not os.path.exists(self.output_dir): self._create_directory(self.output_dir) @staticmethod def _create_directory(folder: str): """Try to create the directory and log the status.""" log_node_warn("", f"Folder {folder} does not exist. Attempting to create...") if not os.path.exists(folder): try: os.makedirs(folder) log_node_success("",f"{folder} Created Successfully") except OSError: log_node_error(f"Failed to create folder {folder}") pass @staticmethod def _map_filename(filename: str, filename_prefix: str) -> Tuple[int, str, Optional[int]]: """Utility function to map filename to its parts.""" # Get the prefix length and extract the prefix prefix_len = len(os.path.basename(filename_prefix)) prefix = filename[:prefix_len] # Search for the primary digits digits = re.search(r'(\d+)', filename[prefix_len:]) # Search for the number in brackets after the primary digits group_id = re.search(r'\((\d+)\)', filename[prefix_len:]) return (int(digits.group()) if digits else 0, prefix, int(group_id.group(1)) if group_id else 0) @staticmethod def _format_date(text: str, date: datetime.datetime) -> str: """Format the date according to specific patterns.""" date_formats = { 'd': lambda d: d.day, 'dd': lambda d: '{:02d}'.format(d.day), 'M': lambda d: d.month, 'MM': lambda d: '{:02d}'.format(d.month), 'h': lambda d: d.hour, 'hh': lambda d: '{:02d}'.format(d.hour), 'm': lambda d: d.minute, 'mm': lambda d: '{:02d}'.format(d.minute), 's': lambda d: d.second, 'ss': lambda d: '{:02d}'.format(d.second), 'y': lambda d: d.year, 'yy': lambda d: str(d.year)[2:], 'yyy': lambda d: str(d.year)[1:], 'yyyy': lambda d: d.year, } # We need to sort the keys in reverse order to ensure we match the longest formats first for format_str in sorted(date_formats.keys(), key=len, reverse=True): if format_str in text: text = text.replace(format_str, str(date_formats[format_str](date))) return text @staticmethod def _gather_all_inputs(prompt: Dict[str, dict], unique_id: str, linkInput: str = '', collected_inputs: Optional[Dict[str, Union[str, List[str]]]] = None) -> Dict[ str, Union[str, List[str]]]: """Recursively gather all inputs from the prompt dictionary.""" if prompt == None: return None collected_inputs = collected_inputs or {} prompt_inputs = prompt[str(unique_id)]["inputs"] for p_input, p_input_value in prompt_inputs.items(): a_input = f"{linkInput}>{p_input}" if linkInput else p_input if isinstance(p_input_value, list): easySave._gather_all_inputs(prompt, p_input_value[0], a_input, collected_inputs) else: existing_value = collected_inputs.get(a_input) if existing_value is None: collected_inputs[a_input] = p_input_value elif p_input_value not in existing_value: collected_inputs[a_input] = existing_value + "; " + p_input_value # if "text" in collected_inputs: # del collected_inputs['text'] # print(collected_inputs) return collected_inputs @staticmethod def _get_filename_with_padding(output_dir, filename, number_padding, group_id, ext): """Return filename with proper padding.""" try: filtered = list(filter(lambda a: a[1] == filename, map(lambda x: easySave._map_filename(x, filename), os.listdir(output_dir)))) last = max(filtered)[0] for f in filtered: if f[0] == last: if f[2] == 0 or f[2] == group_id: last += 1 counter = last except (ValueError, FileNotFoundError): os.makedirs(output_dir, exist_ok=True) counter = 1 if group_id == 0: return f"{filename}.{ext}" if number_padding is None else f"{filename}_{counter:0{number_padding}}.{ext}" else: return f"{filename}_({group_id}).{ext}" if number_padding is None else f"{filename}_{counter:0{number_padding}}_({group_id}).{ext}" @staticmethod def filename_parser(output_dir: str, filename_prefix: str, prompt: Dict[str, dict], my_unique_id: str, number_padding: int, group_id: int, ext: str) -> str: """Parse the filename using provided patterns and replace them with actual values.""" subfolder = os.path.dirname(os.path.normpath(filename_prefix)) filename = os.path.basename(os.path.normpath(filename_prefix)) filename = re.sub(r'%date:(.*?)%', lambda m: easySave._format_date(m.group(1), datetime.datetime.now()), filename_prefix) all_inputs = easySave._gather_all_inputs(prompt, my_unique_id) filename = re.sub(r'%(.*?)%', lambda m: str(all_inputs.get(m.group(1), '')), filename) filename = re.sub(r'[/\\]+', '-', filename) filename = easySave._get_filename_with_padding(output_dir, filename, number_padding, group_id, ext) return filename, subfolder @staticmethod def folder_parser(output_dir: str, prompt: Dict[str, dict], my_unique_id: str): output_dir = re.sub(r'%date:(.*?)%', lambda m: easySave._format_date(m.group(1), datetime.datetime.now()), output_dir) all_inputs = easySave._gather_all_inputs(prompt, my_unique_id) return re.sub(r'%(.*?)%', lambda m: str(all_inputs.get(m.group(1), '')), output_dir) def images(self, images, filename_prefix, output_type, embed_workflow=True, ext="png", group_id=0): FORMAT_MAP = { "png": "PNG", "jpg": "JPEG", "jpeg": "JPEG", "bmp": "BMP", "tif": "TIFF", "tiff": "TIFF" } if ext not in FORMAT_MAP: raise ValueError(f"Unsupported file extension {ext}") if output_type == "Hide": return list() if output_type in ("Save", "Hide/Save", "Sender/Save"): output_dir = self.output_dir if self.output_dir != folder_paths.get_temp_directory() else folder_paths.get_output_directory() self.type = "output" if output_type in ("Preview", "Sender"): output_dir = self.output_dir filename_prefix = 'easyPreview' results = list() for image in images: img = Image.fromarray(np.clip(255. * image.cpu().numpy(), 0, 255).astype(np.uint8)) filename = filename_prefix.replace("%width%", str(img.size[0])).replace("%height%", str(img.size[1])) filename, subfolder = easySave.filename_parser(output_dir, filename, self.prompt, self.my_unique_id, self.number_padding, group_id, ext) file_path = os.path.join(output_dir, filename) if ext == "png" and embed_workflow in (True, "True"): metadata = PngInfo() if self.prompt is not None: metadata.add_text("prompt", json.dumps(self.prompt)) if hasattr(self, 'extra_pnginfo') and self.extra_pnginfo is not None: for key, value in self.extra_pnginfo.items(): metadata.add_text(key, json.dumps(value)) if self.overwrite_existing or not os.path.isfile(file_path): img.save(file_path, pnginfo=metadata, format=FORMAT_MAP[ext]) else: if self.overwrite_existing or not os.path.isfile(file_path): img.save(file_path, format=FORMAT_MAP[ext]) else: log_node_error("",f"File {file_path} already exists... Skipping") results.append({ "filename": filename, "subfolder": subfolder, "type": self.type }) return results def textfile(self, text, filename_prefix, output_type, group_id=0, ext='txt'): if output_type == "Hide": return [] if output_type in ("Save", "Hide/Save"): output_dir = self.output_dir if self.output_dir != folder_paths.get_temp_directory() else folder_paths.get_output_directory() if output_type == "Preview": filename_prefix = 'easyPreview' filename = easySave.filename_parser(output_dir, filename_prefix, self.prompt, self.my_unique_id, self.number_padding, group_id, ext) file_path = os.path.join(output_dir, filename) if self.overwrite_existing or not os.path.isfile(file_path): with open(file_path, 'w') as f: f.write(text) else: log_node_error("", f"File {file_path} already exists... Skipping") # ---------------------------------------------------------------提示词 开始----------------------------------------------------------------------# # 正面提示词 class positivePrompt: def __init__(self): pass @classmethod def INPUT_TYPES(s): return {"required": { "positive": ("STRING", {"default": "", "multiline": True, "placeholder": "Positive"}),} } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("positive",) FUNCTION = "main" CATEGORY = "EasyUse/Prompt" @staticmethod def main(positive): return positive, # 通配符提示词 class wildcardsPrompt: def __init__(self): pass @classmethod def INPUT_TYPES(s): wildcard_list = get_wildcard_list() return {"required": { "text": ("STRING", {"default": "", "multiline": True, "dynamicPrompts": False, "placeholder": "(Support Lora Block Weight and wildcard)"}), "Select to add LoRA": (["Select the LoRA to add to the text"] + folder_paths.get_filename_list("loras"),), "Select to add Wildcard": (["Select the Wildcard to add to the text"] + wildcard_list,), "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("text",) OUTPUT_NODE = True FUNCTION = "main" CATEGORY = "EasyUse/Prompt" @staticmethod def main(*args, **kwargs): my_unique_id = kwargs["my_unique_id"] extra_pnginfo = kwargs["extra_pnginfo"] prompt = kwargs["prompt"] seed_num = kwargs["seed_num"] # Clean loaded_objects easyCache.update_loaded_objects(prompt) my_unique_id = int(my_unique_id) easy_save = easySave(my_unique_id, prompt, extra_pnginfo) # if my_unique_id: # workflow = extra_pnginfo["workflow"] # node = next((x for x in workflow["nodes"] if str(x["id"]) == my_unique_id), None) # if node: # seed_num = prompt[my_unique_id]['inputs']['seed_num'] if 'seed_num' in prompt[my_unique_id][ # 'inputs'] else 0 # length = len(node["widgets_values"]) # node["widgets_values"][length - 2] = seed_num text = kwargs['text'] return {"ui": {"value": [seed_num]}, "result": (text,)} # 负面提示词 class negativePrompt: def __init__(self): pass @classmethod def INPUT_TYPES(s): return {"required": { "negative": ("STRING", {"default": "", "multiline": True, "placeholder": "Negative"}),} } RETURN_TYPES = ("STRING",) RETURN_NAMES = ("negative",) FUNCTION = "main" CATEGORY = "EasyUse/Prompt" @staticmethod def main(negative): return negative, # 肖像大师 # Created by AI Wiz Art (Stefano Flore) # Version: 2.2 # https://stefanoflore.it # https://ai-wiz.art class portraitMaster: @classmethod def INPUT_TYPES(s): max_float_value = 1.95 prompt_path = Path(os.path.join(Path(__file__).parent.parent, 'resources/portrait_prompt.json')) if not os.path.exists(prompt_path): response = urlopen('https://raw.githubusercontent.com/yolain/ComfyUI-Easy-Use/main/resources/portrait_prompt.json') temp_prompt = json.loads(response.read()) prompt_serialized = json.dumps(temp_prompt, indent=4) with open(prompt_path, "w") as f: f.write(prompt_serialized) del response, temp_prompt # Load local with open(prompt_path, 'r') as f: list = json.load(f) keys = [ ['shot', 'COMBO', {"key": "shot_list"}], ['shot_weight', 'FLOAT'], ['gender', 'COMBO', {"default": "Woman", "key": "gender_list"}], ['age', 'INT', {"default": 30, "min": 18, "max": 90, "step": 1, "display": "slider"}], ['nationality_1', 'COMBO', {"default": "Chinese", "key": "nationality_list"}], ['nationality_2', 'COMBO', {"key": "nationality_list"}], ['nationality_mix', 'FLOAT'], ['body_type', 'COMBO', {"key": "body_type_list"}], ['body_type_weight', 'FLOAT'], ['model_pose', 'COMBO', {"key": "model_pose_list"}], ['eyes_color', 'COMBO', {"key": "eyes_color_list"}], ['facial_expression', 'COMBO', {"key": "face_expression_list"}], ['facial_expression_weight', 'FLOAT'], ['face_shape', 'COMBO', {"key": "face_shape_list"}], ['face_shape_weight', 'FLOAT'], ['facial_asymmetry', 'FLOAT'], ['hair_style', 'COMBO', {"key": "hair_style_list"}], ['hair_color', 'COMBO', {"key": "hair_color_list"}], ['disheveled', 'FLOAT'], ['beard', 'COMBO', {"key": "beard_list"}], ['skin_details', 'FLOAT'], ['skin_pores', 'FLOAT'], ['dimples', 'FLOAT'], ['freckles', 'FLOAT'], ['moles', 'FLOAT'], ['skin_imperfections', 'FLOAT'], ['skin_acne', 'FLOAT'], ['tanned_skin', 'FLOAT'], ['eyes_details', 'FLOAT'], ['iris_details', 'FLOAT'], ['circular_iris', 'FLOAT'], ['circular_pupil', 'FLOAT'], ['light_type', 'COMBO', {"key": "light_type_list"}], ['light_direction', 'COMBO', {"key": "light_direction_list"}], ['light_weight', 'FLOAT'] ] widgets = {} for i, obj in enumerate(keys): if obj[1] == 'COMBO': key = obj[2]['key'] if obj[2] and 'key' in obj[2] else obj[0] _list = list[key].copy() _list.insert(0, '-') widgets[obj[0]] = (_list, {**obj[2]}) elif obj[1] == 'FLOAT': widgets[obj[0]] = ("FLOAT", {"default": 0, "step": 0.05, "min": 0, "max": max_float_value, "display": "slider",}) elif obj[1] == 'INT': widgets[obj[0]] = (obj[1], obj[2]) del list return { "required": { **widgets, "photorealism_improvement": (["enable", "disable"],), "prompt_start": ("STRING", {"multiline": True, "default": "raw photo, (realistic:1.5)"}), "prompt_additional": ("STRING", {"multiline": True, "default": ""}), "prompt_end": ("STRING", {"multiline": True, "default": ""}), "negative_prompt": ("STRING", {"multiline": True, "default": ""}), } } RETURN_TYPES = ("STRING", "STRING",) RETURN_NAMES = ("positive", "negative",) FUNCTION = "pm" CATEGORY = "EasyUse/Prompt" def pm(self, shot="-", shot_weight=1, gender="-", body_type="-", body_type_weight=0, eyes_color="-", facial_expression="-", facial_expression_weight=0, face_shape="-", face_shape_weight=0, nationality_1="-", nationality_2="-", nationality_mix=0.5, age=30, hair_style="-", hair_color="-", disheveled=0, dimples=0, freckles=0, skin_pores=0, skin_details=0, moles=0, skin_imperfections=0, wrinkles=0, tanned_skin=0, eyes_details=1, iris_details=1, circular_iris=1, circular_pupil=1, facial_asymmetry=0, prompt_additional="", prompt_start="", prompt_end="", light_type="-", light_direction="-", light_weight=0, negative_prompt="", photorealism_improvement="disable", beard="-", model_pose="-", skin_acne=0): prompt = [] if gender == "-": gender = "" else: if age <= 25 and gender == 'Woman': gender = 'girl' if age <= 25 and gender == 'Man': gender = 'boy' gender = " " + gender + " " if nationality_1 != '-' and nationality_2 != '-': nationality = f"[{nationality_1}:{nationality_2}:{round(nationality_mix, 2)}]" elif nationality_1 != '-': nationality = nationality_1 + " " elif nationality_2 != '-': nationality = nationality_2 + " " else: nationality = "" if prompt_start != "": prompt.append(f"{prompt_start}") if shot != "-" and shot_weight > 0: prompt.append(f"({shot}:{round(shot_weight, 2)})") prompt.append(f"({nationality}{gender}{round(age)}-years-old:1.5)") if body_type != "-" and body_type_weight > 0: prompt.append(f"({body_type}, {body_type} body:{round(body_type_weight, 2)})") if model_pose != "-": prompt.append(f"({model_pose}:1.5)") if eyes_color != "-": prompt.append(f"({eyes_color} eyes:1.25)") if facial_expression != "-" and facial_expression_weight > 0: prompt.append( f"({facial_expression}, {facial_expression} expression:{round(facial_expression_weight, 2)})") if face_shape != "-" and face_shape_weight > 0: prompt.append(f"({face_shape} shape face:{round(face_shape_weight, 2)})") if hair_style != "-": prompt.append(f"({hair_style} hairstyle:1.25)") if hair_color != "-": prompt.append(f"({hair_color} hair:1.25)") if beard != "-": prompt.append(f"({beard}:1.15)") if disheveled != "-" and disheveled > 0: prompt.append(f"(disheveled:{round(disheveled, 2)})") if prompt_additional != "": prompt.append(f"{prompt_additional}") if skin_details > 0: prompt.append(f"(skin details, skin texture:{round(skin_details, 2)})") if skin_pores > 0: prompt.append(f"(skin pores:{round(skin_pores, 2)})") if skin_imperfections > 0: prompt.append(f"(skin imperfections:{round(skin_imperfections, 2)})") if skin_acne > 0: prompt.append(f"(acne, skin with acne:{round(skin_acne, 2)})") if wrinkles > 0: prompt.append(f"(skin imperfections:{round(wrinkles, 2)})") if tanned_skin > 0: prompt.append(f"(tanned skin:{round(tanned_skin, 2)})") if dimples > 0: prompt.append(f"(dimples:{round(dimples, 2)})") if freckles > 0: prompt.append(f"(freckles:{round(freckles, 2)})") if moles > 0: prompt.append(f"(skin pores:{round(moles, 2)})") if eyes_details > 0: prompt.append(f"(eyes details:{round(eyes_details, 2)})") if iris_details > 0: prompt.append(f"(iris details:{round(iris_details, 2)})") if circular_iris > 0: prompt.append(f"(circular iris:{round(circular_iris, 2)})") if circular_pupil > 0: prompt.append(f"(circular pupil:{round(circular_pupil, 2)})") if facial_asymmetry > 0: prompt.append(f"(facial asymmetry, face asymmetry:{round(facial_asymmetry, 2)})") if light_type != '-' and light_weight > 0: if light_direction != '-': prompt.append(f"({light_type} {light_direction}:{round(light_weight, 2)})") else: prompt.append(f"({light_type}:{round(light_weight, 2)})") if prompt_end != "": prompt.append(f"{prompt_end}") prompt = ", ".join(prompt) prompt = prompt.lower() if photorealism_improvement == "enable": prompt = prompt + ", (professional photo, balanced photo, balanced exposure:1.2), (film grain:1.15)" if photorealism_improvement == "enable": negative_prompt = negative_prompt + ", (shinny skin, reflections on the skin, skin reflections:1.25)" log_node_info("Portrait Master as generate the prompt:", prompt) return (prompt, negative_prompt,) # 潜空间sigma相乘 class latentMultiplyBySigma: @classmethod def INPUT_TYPES(s): return {"required": { "sampler_name": (comfy.samplers.KSampler.SAMPLERS,), "scheduler": (comfy.samplers.KSampler.SCHEDULERS,), "steps": ("INT", {"default": 10000, "min": 0, "max": 10000}), "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}), "end_at_step": ("INT", {"default": 10000, "min": 1, "max": 10000}), }, "optional": { "pipe": ("PIPE_LINE",), "optional_model": ("MODEL",), "optional_latent": ("LATENT",) }} RETURN_TYPES = ("PIPE_LINE", "LATENT", "FLOAT",) RETURN_NAMES = ("pipe", "latent", "sigma",) FUNCTION = "run" CATEGORY = "EasyUse/Latent" def run(self, sampler_name, scheduler, steps, start_at_step, end_at_step, pipe=None, optional_model=None, optional_latent=None): model = optional_model if optional_model is not None else pipe["model"] samples = optional_latent if optional_latent is not None else pipe["samples"] device = comfy.model_management.get_torch_device() end_at_step = min(steps, end_at_step) start_at_step = min(start_at_step, end_at_step) real_model = None comfy.model_management.load_model_gpu(model) real_model = model.model sampler = comfy.samplers.KSampler(real_model, steps=steps, device=device, sampler=sampler_name, scheduler=scheduler, denoise=1.0, model_options=model.model_options) sigmas = sampler.sigmas sigma = sigmas[start_at_step] - sigmas[end_at_step] sigma /= model.model.latent_format.scale_factor sigma = sigma.cpu().numpy() samples_out = samples.copy() s1 = samples["samples"] samples_out["samples"] = s1 * sigma if pipe is None: pipe = {} new_pipe = { **pipe, "samples": samples_out } del pipe return (new_pipe, samples_out, sigma) # Latent遮罩复合 class latentCompositeMaskedWithCond: @classmethod def INPUT_TYPES(s): return { "required": { "pipe": ("PIPE_LINE",), "text_combine": ("STRING", {"default": ""}), "source_latent": ("LATENT",), "source_mask": ("MASK",), "new_mask": ("MASK",), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("PIPE_LINE", "LATENT", "CONDITIONING") RETURN_NAMES = ("pipe", "latent", "conditioning",) FUNCTION = "run" OUTPUT_MODE = True CATEGORY = "EasyUse/Latent" def run(self, pipe, text_combine, source_latent, source_mask, new_mask, prompt=None, extra_pnginfo=None, my_unique_id=None): clip = pipe["clip"] destination_latent = pipe["samples"] positive = pipe["loader_settings"]["positive"] + ',' + text_combine positive_token_normalization = pipe["loader_settings"]["positive_token_normalization"] positive_weight_interpretation = pipe["loader_settings"]["positive_weight_interpretation"] a1111_prompt_style = pipe["loader_settings"]["a1111_prompt_style"] positive_cond = pipe["positive"] log_node_warn("正在处理提示词编码...") # Use new clip text encode by smzNodes like same as webui, when if you installed the smzNodes if a1111_prompt_style: if "smZ CLIPTextEncode" in ALL_NODE_CLASS_MAPPINGS: cls = ALL_NODE_CLASS_MAPPINGS['smZ CLIPTextEncode'] steps = pipe["steps"] positive_embeddings_final, = cls().encode(clip, positive, "A1111", True, True, False, False, 6, 1024, 1024, 0, 0, 1024, 1024, '', '', steps) else: raise Exception(f"[ERROR] To use clip text encode same as webui, you need to install 'smzNodes'") else: positive_embeddings_final, positive_pooled = advanced_encode(clip, positive, positive_token_normalization, positive_weight_interpretation, w_max=1.0, apply_to_pooled='enable') positive_embeddings_final = [[positive_embeddings_final, {"pooled_output": positive_pooled}]] # source cond (cond_1,) = ConditioningSetMask().append(positive_cond, source_mask, "default", 1) (cond_2,) = ConditioningSetMask().append(positive_embeddings_final, new_mask, "default", 1) positive_cond = cond_1 + cond_2 # latent composite masked (samples,) = LatentCompositeMasked().composite(destination_latent, source_latent, 0, 0, False) new_pipe = { **pipe, "positive": positive_cond, "samples": samples, "loader_settings": { **pipe["loader_settings"], "positive": positive, } } del pipe return (new_pipe, samples, positive_cond) # 随机种 class easySeed: @classmethod def INPUT_TYPES(s): return { "required": { "seed_num": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), }, "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID"}, } RETURN_TYPES = ("INT",) RETURN_NAMES = ("seed_num",) FUNCTION = "doit" CATEGORY = "EasyUse/Seed" OUTPUT_NODE = True def doit(self, seed_num=0, prompt=None, extra_pnginfo=None, my_unique_id=None): return seed_num, # 全局随机种 class globalSeed: @classmethod def INPUT_TYPES(s): return { "required": { "value": ("INT", {"default": 0, "min": 0, "max": 1125899906842624}), "mode": ("BOOLEAN", {"default": True, "label_on": "control_before_generate", "label_off": "control_after_generate"}), "action": (["fixed", "increment", "decrement", "randomize", "increment for each node", "decrement for each node", "randomize for each node"], ), "last_seed": ("STRING", {"default": ""}), } } RETURN_TYPES = () FUNCTION = "doit" CATEGORY = "EasyUse/Seed" OUTPUT_NODE = True def doit(self, **kwargs): return {} #---------------------------------------------------------------提示词 结束------------------------------------------------------------------------# #---------------------------------------------------------------加载器 开始----------------------------------------------------------------------# # 简易加载器完整 class fullLoader: @classmethod def INPUT_TYPES(cls): resolution_strings = [f"{width} x {height}" for width, height in BASE_RESOLUTIONS] a1111_prompt_style_default = False return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"),), "config_name": (["Default", ] + folder_paths.get_filename_list("configs"), {"default": "Default"}), "vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),), "clip_skip": ("INT", {"default": -1, "min": -24, "max": 0, "step": 1}), "lora_name": (["None"] + folder_paths.get_filename_list("loras"),), "lora_model_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "lora_clip_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), "resolution": (resolution_strings,), "empty_latent_width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "empty_latent_height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), "positive": ("STRING", {"default": "Positive", "multiline": True}), "positive_token_normalization": (["none", "mean", "length", "length+mean"],), "positive_weight_interpretation": (["comfy", "A1111", "comfy++", "compel", "fixed attention"],), "negative": ("STRING", {"default": "Negative", "multiline": True}), "negative_token_normalization": (["none", "mean", "length", "length+mean"],), "negative_weight_interpretation": (["comfy", "A1111", "comfy++", "compel", "fixed attention"],), "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}), }, "optional": {"model_override": ("MODEL",), "clip_override": ("CLIP",), "vae_override": ("VAE",), "optional_lora_stack": ("LORA_STACK",), "a1111_prompt_style": ("BOOLEAN", {"default": a1111_prompt_style_default}),}, "hidden": {"prompt": "PROMPT", "my_unique_id": "UNIQUE_ID"} } RETURN_TYPES = ("PIPE_LINE", "MODEL", "VAE", "CLIP") RETURN_NAMES = ("pipe", "model", "vae", "clip") FUNCTION = "adv_pipeloader" CATEGORY = "EasyUse/Loaders" def adv_pipeloader(self, ckpt_name, config_name, vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength, resolution, empty_latent_width, empty_latent_height, positive, positive_token_normalization, positive_weight_interpretation, negative, negative_token_normalization, negative_weight_interpretation, batch_size, model_override=None, clip_override=None, vae_override=None, optional_lora_stack=None, a1111_prompt_style=False, prompt=None, my_unique_id=None ): model: ModelPatcher | None = None clip: CLIP | None = None vae: VAE | None = None can_load_lora = True pipe_lora_stack = [] # resolution if resolution != "自定义 x 自定义": try: width, height = map(int, resolution.split(' x ')) empty_latent_width = width empty_latent_height = height except ValueError: raise ValueError("Invalid base_resolution format.") # Create Empty Latent latent = torch.zeros([batch_size, 4, empty_latent_height // 8, empty_latent_width // 8]).cpu() samples = {"samples": latent} # Clean models from loaded_objects easyCache.update_loaded_objects(prompt) log_node_warn("正在处理模型...") # 判断是否存在 模型叠加xyplot, 若存在优先缓存第一个模型 xyinputs_id = next((x for x in prompt if str(prompt[x]["class_type"]) == "easy XYInputs: ModelMergeBlocks"), None) if xyinputs_id is not None: node = prompt[xyinputs_id] if "ckpt_name_1" in node["inputs"]: ckpt_name_1 = node["inputs"]["ckpt_name_1"] model, clip, vae = easyCache.load_checkpoint(ckpt_name_1) can_load_lora = False # Load models elif model_override is not None and clip_override is not None and vae_override is not None: model = model_override clip = clip_override vae = vae_override elif model_override is not None: raise Exception(f"[ERROR] clip or vae is missing") elif vae_override is not None: raise Exception(f"[ERROR] model or clip is missing") elif clip_override is not None: raise Exception(f"[ERROR] model or vae is missing") else: model, clip, vae = easyCache.load_checkpoint(ckpt_name, config_name) if optional_lora_stack is not None: for lora in optional_lora_stack: if can_load_lora: model, clip = easyCache.load_lora(lora[0], model, clip, lora[1], lora[2]) pipe_lora_stack.append({"lora_name": lora[0], "model": model, "clip": clip, "lora_model_strength": lora[1], "lora_clip_strength": lora[2]}) if lora_name != "None": if can_load_lora: model, clip = easyCache.load_lora(lora_name, model, clip, lora_model_strength, lora_clip_strength) pipe_lora_stack.append({"lora_name": lora_name, "model": model, "clip": clip, "lora_model_strength": lora_model_strength, "lora_clip_strength": lora_clip_strength}) # Check for custom VAE if vae_name not in ["Baked VAE", "Baked-VAE"]: vae = easyCache.load_vae(vae_name) # CLIP skip if not clip: raise Exception("No CLIP found") log_node_warn("正在处理提示词...") positive_seed = find_wildcards_seed(positive, prompt)
model, clip, positive, positive_decode, show_positive_prompt, pipe_lora_stack = process_with_loras(positive, model, clip, "Positive", positive_seed, can_load_lora, pipe_lora_stack)
7
2023-12-10 07:02:36+00:00
12k
Open-All-Scale-Causal-Engine/OpenASCE
openasce/inference/graph_inference.py
[ { "identifier": "CausalGraph", "path": "openasce/discovery/causal_graph.py", "snippet": "class CausalGraph(object):\n \"\"\"Causal Graph Class\n\n Represent the casual graph\n\n \"\"\"\n\n DEFAULT_COLUMN_NAME_PREFIX = \"x\"\n\n def __init__(self, names=[], bn=None, w: np.ndarray = None):\...
import copy import numpy as np from functools import reduce from typing import Dict, Iterable, List from openasce.discovery.causal_graph import CausalGraph from openasce.discovery.discovery import Discovery from openasce.discovery.graph_node_form import GraphNodeForm from openasce.inference.inference_model import InferenceModel from openasce.utils.logger import logger
7,404
class GraphInferModel(InferenceModel): """The inference using the causal graph Attributes: graph: The causal graph. If not set, the class will try to find it out if discovery is available. column_names: all names of sample treatment_name: treatment column name in column_names label_name: target column name in column_names """ def __init__( self, *, graph: CausalGraph = None, column_names: List[str] = None, treatment_name: str = None, label_name: str = None, num_iteration=20, ) -> None: """ Arguments: graph: causal graph column_names: all names of column treatment_name: the name of treatment column label_name: the name of target name """ super().__init__() self._graph = graph self._column_names = column_names self._treatment_name = treatment_name self._label_name = label_name self._discovery = None self._data = None self._num_iteration = num_iteration self._label_value = None @property def data(self): assert self._data is not None, f"Must have sample data." return self._data @property def graph(self): assert self._graph is not None, "The graph object should be set" return self._graph @graph.setter def graph(self, value): assert self._graph is None, "The graph object should be set once only" self._graph = value # graph is available, set the column names using graph columns self.column_names = list(self.graph.names_to_index.keys()) @property def column_names(self): """All nodes' name. Note: should include the treatment node and label node. """ assert self._column_names is not None, "The column names should be set" return self._column_names @column_names.setter def column_names(self, value: List[str]): assert self._column_names is None, "The column names should be set once only" self._column_names = value @property def treatment_name(self): assert self._treatment_name is not None, "The treatment name should be set" return self._treatment_name @treatment_name.setter def treatment_name(self, value: str): assert ( self._treatment_name is None ), "The treatment name should be set once only" self._treatment_name = value @property def label_name(self): assert self._label_name is not None, "The label name should be set" return self._label_name @label_name.setter def label_name(self, value: str): assert self._label_name is None, "The label name should be set once only" self._label_name = value @property def discovery(self) -> Discovery: assert self._discovery is not None, "The discovery object should be set" return self._discovery @discovery.setter def discovery(self, value: Discovery): self._discovery = value def fit( self, *, X: Iterable[np.ndarray], Y: Iterable[np.ndarray] = None, T: Iterable[np.ndarray] = None, **kwargs, ) -> None: """Feed the sample data to train the graph Arguments: X: All features of the samples including the treatment and the label node. Y: Ignore in causal graph inference T: Ignore in causal graph inference. Returns: """ if Y is not None or T is not None:
# Copyright 2023 AntGroup CO., Ltd. # # 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. class GraphInferModel(InferenceModel): """The inference using the causal graph Attributes: graph: The causal graph. If not set, the class will try to find it out if discovery is available. column_names: all names of sample treatment_name: treatment column name in column_names label_name: target column name in column_names """ def __init__( self, *, graph: CausalGraph = None, column_names: List[str] = None, treatment_name: str = None, label_name: str = None, num_iteration=20, ) -> None: """ Arguments: graph: causal graph column_names: all names of column treatment_name: the name of treatment column label_name: the name of target name """ super().__init__() self._graph = graph self._column_names = column_names self._treatment_name = treatment_name self._label_name = label_name self._discovery = None self._data = None self._num_iteration = num_iteration self._label_value = None @property def data(self): assert self._data is not None, f"Must have sample data." return self._data @property def graph(self): assert self._graph is not None, "The graph object should be set" return self._graph @graph.setter def graph(self, value): assert self._graph is None, "The graph object should be set once only" self._graph = value # graph is available, set the column names using graph columns self.column_names = list(self.graph.names_to_index.keys()) @property def column_names(self): """All nodes' name. Note: should include the treatment node and label node. """ assert self._column_names is not None, "The column names should be set" return self._column_names @column_names.setter def column_names(self, value: List[str]): assert self._column_names is None, "The column names should be set once only" self._column_names = value @property def treatment_name(self): assert self._treatment_name is not None, "The treatment name should be set" return self._treatment_name @treatment_name.setter def treatment_name(self, value: str): assert ( self._treatment_name is None ), "The treatment name should be set once only" self._treatment_name = value @property def label_name(self): assert self._label_name is not None, "The label name should be set" return self._label_name @label_name.setter def label_name(self, value: str): assert self._label_name is None, "The label name should be set once only" self._label_name = value @property def discovery(self) -> Discovery: assert self._discovery is not None, "The discovery object should be set" return self._discovery @discovery.setter def discovery(self, value: Discovery): self._discovery = value def fit( self, *, X: Iterable[np.ndarray], Y: Iterable[np.ndarray] = None, T: Iterable[np.ndarray] = None, **kwargs, ) -> None: """Feed the sample data to train the graph Arguments: X: All features of the samples including the treatment and the label node. Y: Ignore in causal graph inference T: Ignore in causal graph inference. Returns: """ if Y is not None or T is not None:
logger.info(
4
2023-12-06 05:54:36+00:00
12k
eclipse-t2i/eclipse-inference
main.py
[ { "identifier": "PriorTransformer", "path": "src/priors/prior_transformer.py", "snippet": "class PriorTransformer(ModelMixin, ConfigMixin):\n \"\"\"\n A Prior Transformer model.\n\n Parameters:\n num_attention_heads (`int`, *optional*, defaults to 32): The number of heads to use for mult...
import gradio as gr import torch import math import numpy as np import torch from PIL import Image from torchvision import transforms from transformers import ( CLIPProcessor, CLIPModel, CLIPTokenizer, CLIPTextModelWithProjection, CLIPVisionModelWithProjection, CLIPFeatureExtractor, ) from typing import List from PIL import Image, ImageChops from diffusers import UnCLIPPipeline from transformers import CLIPTokenizer from src.priors.prior_transformer import ( PriorTransformer, ) # original huggingface prior transformer without time conditioning from src.pipelines.pipeline_kandinsky_prior import KandinskyPriorPipeline from diffusers import DiffusionPipeline
8,689
# from diffusers.utils.torch_utils import randn_tensor __DEVICE__ = "cpu" if torch.cuda.is_available(): __DEVICE__ = "cuda" class Ours: def __init__(self, device): text_encoder = ( CLIPTextModelWithProjection.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", projection_dim=1280, torch_dtype=torch.float16, ) .eval() .requires_grad_(False) ) tokenizer = CLIPTokenizer.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k" ) prior = PriorTransformer.from_pretrained( "ECLIPSE-Community/ECLIPSE_KandinskyV22_Prior", torch_dtype=torch.float16, )
# from diffusers.utils.torch_utils import randn_tensor __DEVICE__ = "cpu" if torch.cuda.is_available(): __DEVICE__ = "cuda" class Ours: def __init__(self, device): text_encoder = ( CLIPTextModelWithProjection.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", projection_dim=1280, torch_dtype=torch.float16, ) .eval() .requires_grad_(False) ) tokenizer = CLIPTokenizer.from_pretrained( "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k" ) prior = PriorTransformer.from_pretrained( "ECLIPSE-Community/ECLIPSE_KandinskyV22_Prior", torch_dtype=torch.float16, )
self.pipe_prior = KandinskyPriorPipeline.from_pretrained(
1
2023-12-07 05:17:08+00:00
12k
AIFSH/NativeDancer
nativedancer/third_part/detectron2/modeling/mmdet_wrapper.py
[ { "identifier": "ShapeSpec", "path": "nativedancer/third_part/detectron2/layers/shape_spec.py", "snippet": "class ShapeSpec:\n \"\"\"\n A simple structure that contains basic shape specification about a tensor.\n It is often used as the auxiliary inputs/outputs of models,\n to complement the...
import itertools import logging import numpy as np import torch from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from ..layers import ShapeSpec from ..structures import BitMasks, Boxes, ImageList, Instances from ..utils.events import get_event_storage from .backbone import Backbone from mmcv.utils import ConfigDict from mmdet.models import build_backbone from mmdet.models import build_neck from mmdet.models import build_detector from mmdet.core import PolygonMasks as mm_PolygonMasks, BitmapMasks as mm_BitMasks
9,579
""" def __init__( self, detector: Union[nn.Module, Mapping], *, # Default is 32 regardless of model: # https://github.com/open-mmlab/mmdetection/tree/master/configs/_base_/datasets size_divisibility=32, pixel_mean: Tuple[float], pixel_std: Tuple[float], ): """ Args: detector: a mmdet detector, or a mmdet config dict that defines a detector. size_divisibility: pad input images to multiple of this number pixel_mean: per-channel mean to normalize input image pixel_std: per-channel stddev to normalize input image """ super().__init__() if isinstance(detector, Mapping): detector = build_detector(_to_container(detector)) self.detector = detector self.detector.init_weights() self.size_divisibility = size_divisibility 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) assert ( self.pixel_mean.shape == self.pixel_std.shape ), f"{self.pixel_mean} and {self.pixel_std} have different shapes!" def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]): images = [x["image"].to(self.device) for x in batched_inputs] images = [(x - self.pixel_mean) / self.pixel_std for x in images] images = ImageList.from_tensors(images, size_divisibility=self.size_divisibility).tensor metas = [] rescale = {"height" in x for x in batched_inputs} if len(rescale) != 1: raise ValueError("Some inputs have original height/width, but some don't!") rescale = list(rescale)[0] output_shapes = [] for input in batched_inputs: meta = {} c, h, w = input["image"].shape meta["img_shape"] = meta["ori_shape"] = (h, w, c) if rescale: scale_factor = np.array( [w / input["width"], h / input["height"]] * 2, dtype="float32" ) ori_shape = (input["height"], input["width"]) output_shapes.append(ori_shape) meta["ori_shape"] = ori_shape + (c,) else: scale_factor = 1.0 output_shapes.append((h, w)) meta["scale_factor"] = scale_factor meta["flip"] = False padh, padw = images.shape[-2:] meta["pad_shape"] = (padh, padw, c) metas.append(meta) if self.training: gt_instances = [x["instances"].to(self.device) for x in batched_inputs] if gt_instances[0].has("gt_masks"): def convert_mask(m, shape): # mmdet mask format if isinstance(m, BitMasks): return mm_BitMasks(m.tensor.cpu().numpy(), shape[0], shape[1]) else: return mm_PolygonMasks(m.polygons, shape[0], shape[1]) gt_masks = [convert_mask(x.gt_masks, x.image_size) for x in gt_instances] losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], gt_masks=gt_masks, ) else: losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], ) return _parse_losses(losses_and_metrics) else: results = self.detector.simple_test(images, metas, rescale=rescale) results = [ {"instances": _convert_mmdet_result(r, shape)} for r, shape in zip(results, output_shapes) ] return results @property def device(self): return self.pixel_mean.device # Reference: show_result() in # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py def _convert_mmdet_result(result, shape: Tuple[int, int]) -> Instances: if isinstance(result, tuple): bbox_result, segm_result = result if isinstance(segm_result, tuple): segm_result = segm_result[0] else: bbox_result, segm_result = result, None bboxes = torch.from_numpy(np.vstack(bbox_result)) # Nx5 bboxes, scores = bboxes[:, :4], bboxes[:, -1] labels = [ torch.full((bbox.shape[0],), i, dtype=torch.int32) for i, bbox in enumerate(bbox_result) ] labels = torch.cat(labels) inst = Instances(shape)
# Copyright (c) Facebook, Inc. and its affiliates. logger = logging.getLogger(__name__) def _to_container(cfg): """ mmdet will assert the type of dict/list. So convert omegaconf objects to dict/list. """ if isinstance(cfg, DictConfig): cfg = OmegaConf.to_container(cfg, resolve=True) return ConfigDict(cfg) class MMDetBackbone(Backbone): """ Wrapper of mmdetection backbones to use in detectron2. mmdet backbones produce list/tuple of tensors, while detectron2 backbones produce a dict of tensors. This class wraps the given backbone to produce output in detectron2's convention, so it can be used in place of detectron2 backbones. """ def __init__( self, backbone: Union[nn.Module, Mapping], neck: Union[nn.Module, Mapping, None] = None, *, output_shapes: List[ShapeSpec], output_names: Optional[List[str]] = None, ): """ Args: backbone: either a backbone module or a mmdet config dict that defines a backbone. The backbone takes a 4D image tensor and returns a sequence of tensors. neck: either a backbone module or a mmdet config dict that defines a neck. The neck takes outputs of backbone and returns a sequence of tensors. If None, no neck is used. output_shapes: shape for every output of the backbone (or neck, if given). stride and channels are often needed. output_names: names for every output of the backbone (or neck, if given). By default, will use "out0", "out1", ... """ super().__init__() if isinstance(backbone, Mapping): backbone = build_backbone(_to_container(backbone)) self.backbone = backbone if isinstance(neck, Mapping): neck = build_neck(_to_container(neck)) self.neck = neck # "Neck" weights, if any, are part of neck itself. This is the interface # of mmdet so we follow it. Reference: # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/two_stage.py logger.info("Initializing mmdet backbone weights...") self.backbone.init_weights() # train() in mmdet modules is non-trivial, and has to be explicitly # called. Reference: # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/backbones/resnet.py self.backbone.train() if self.neck is not None: logger.info("Initializing mmdet neck weights ...") if isinstance(self.neck, nn.Sequential): for m in self.neck: m.init_weights() else: self.neck.init_weights() self.neck.train() self._output_shapes = output_shapes if not output_names: output_names = [f"out{i}" for i in range(len(output_shapes))] self._output_names = output_names def forward(self, x) -> Dict[str, Tensor]: outs = self.backbone(x) if self.neck is not None: outs = self.neck(outs) assert isinstance( outs, (list, tuple) ), "mmdet backbone should return a list/tuple of tensors!" if len(outs) != len(self._output_shapes): raise ValueError( "Length of output_shapes does not match outputs from the mmdet backbone: " f"{len(outs)} != {len(self._output_shapes)}" ) return {k: v for k, v in zip(self._output_names, outs)} def output_shape(self) -> Dict[str, ShapeSpec]: return {k: v for k, v in zip(self._output_names, self._output_shapes)} class MMDetDetector(nn.Module): """ Wrapper of a mmdetection detector model, for detection and instance segmentation. Input/output formats of this class follow detectron2's convention, so a mmdetection model can be trained and evaluated in detectron2. """ def __init__( self, detector: Union[nn.Module, Mapping], *, # Default is 32 regardless of model: # https://github.com/open-mmlab/mmdetection/tree/master/configs/_base_/datasets size_divisibility=32, pixel_mean: Tuple[float], pixel_std: Tuple[float], ): """ Args: detector: a mmdet detector, or a mmdet config dict that defines a detector. size_divisibility: pad input images to multiple of this number pixel_mean: per-channel mean to normalize input image pixel_std: per-channel stddev to normalize input image """ super().__init__() if isinstance(detector, Mapping): detector = build_detector(_to_container(detector)) self.detector = detector self.detector.init_weights() self.size_divisibility = size_divisibility 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) assert ( self.pixel_mean.shape == self.pixel_std.shape ), f"{self.pixel_mean} and {self.pixel_std} have different shapes!" def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]): images = [x["image"].to(self.device) for x in batched_inputs] images = [(x - self.pixel_mean) / self.pixel_std for x in images] images = ImageList.from_tensors(images, size_divisibility=self.size_divisibility).tensor metas = [] rescale = {"height" in x for x in batched_inputs} if len(rescale) != 1: raise ValueError("Some inputs have original height/width, but some don't!") rescale = list(rescale)[0] output_shapes = [] for input in batched_inputs: meta = {} c, h, w = input["image"].shape meta["img_shape"] = meta["ori_shape"] = (h, w, c) if rescale: scale_factor = np.array( [w / input["width"], h / input["height"]] * 2, dtype="float32" ) ori_shape = (input["height"], input["width"]) output_shapes.append(ori_shape) meta["ori_shape"] = ori_shape + (c,) else: scale_factor = 1.0 output_shapes.append((h, w)) meta["scale_factor"] = scale_factor meta["flip"] = False padh, padw = images.shape[-2:] meta["pad_shape"] = (padh, padw, c) metas.append(meta) if self.training: gt_instances = [x["instances"].to(self.device) for x in batched_inputs] if gt_instances[0].has("gt_masks"): def convert_mask(m, shape): # mmdet mask format if isinstance(m, BitMasks): return mm_BitMasks(m.tensor.cpu().numpy(), shape[0], shape[1]) else: return mm_PolygonMasks(m.polygons, shape[0], shape[1]) gt_masks = [convert_mask(x.gt_masks, x.image_size) for x in gt_instances] losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], gt_masks=gt_masks, ) else: losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], ) return _parse_losses(losses_and_metrics) else: results = self.detector.simple_test(images, metas, rescale=rescale) results = [ {"instances": _convert_mmdet_result(r, shape)} for r, shape in zip(results, output_shapes) ] return results @property def device(self): return self.pixel_mean.device # Reference: show_result() in # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py def _convert_mmdet_result(result, shape: Tuple[int, int]) -> Instances: if isinstance(result, tuple): bbox_result, segm_result = result if isinstance(segm_result, tuple): segm_result = segm_result[0] else: bbox_result, segm_result = result, None bboxes = torch.from_numpy(np.vstack(bbox_result)) # Nx5 bboxes, scores = bboxes[:, :4], bboxes[:, -1] labels = [ torch.full((bbox.shape[0],), i, dtype=torch.int32) for i, bbox in enumerate(bbox_result) ] labels = torch.cat(labels) inst = Instances(shape)
inst.pred_boxes = Boxes(bboxes)
1
2023-12-10 20:14:00+00:00
12k
ethanweber/nerfiller
nerfiller/scripts/inpaint_nerfstudio_dataset.py
[ { "identifier": "RGBInpainter", "path": "nerfiller/inpaint/rgb_inpainter.py", "snippet": "class RGBInpainter:\n \"\"\"\n Module for inpainting with the stable diffusion inpainting pipeline.\n \"\"\"\n\n def __init__(\n self,\n half_precision_weights: bool = True,\n lora_...
import json import shutil import mediapy import torch import tyro import math from pathlib import Path from nerfiller.inpaint.rgb_inpainter import RGBInpainter from nerfiller.inpaint.lama_inpainter import LaMaInpainter from nerfiller.nerf.dataset_utils import parse_nerfstudio_frame from nerfiller.utils.image_utils import get_inpainted_image_row from nerfiller.utils.camera_utils import rescale_intrinsics from nerfiller.configs.inpaint import InpaintConfig, AnnotatedBaseConfigUnion from datetime import datetime from nerfiller.utils.diff_utils import register_extended_attention from nerfiller.utils.mask_utils import downscale_mask
10,722
def main( config: InpaintConfig, ): """ Inpaint a Nerfstudio dataset where the masks == 0. """ if config.method_name == "individual-lama": rgb_inpainter = LaMaInpainter(device=config.device, model_path=Path("data/models/big-lama")) else: # Load the inpainting module. rgb_inpainter = RGBInpainter( half_precision_weights=config.half_precision_weights, lora_model_path=config.lora_model_path, device=config.device, vae_device=config.vae_device, ) if config.text_guidance_scale != 0.0: assert config.prompt != "", "You need to set an actual prompt to use this method." # Process the text prompts. text_embeddings = rgb_inpainter.compute_text_embeddings(config.prompt, config.negative_prompt) if config.use_expanded_attention:
def main( config: InpaintConfig, ): """ Inpaint a Nerfstudio dataset where the masks == 0. """ if config.method_name == "individual-lama": rgb_inpainter = LaMaInpainter(device=config.device, model_path=Path("data/models/big-lama")) else: # Load the inpainting module. rgb_inpainter = RGBInpainter( half_precision_weights=config.half_precision_weights, lora_model_path=config.lora_model_path, device=config.device, vae_device=config.vae_device, ) if config.text_guidance_scale != 0.0: assert config.prompt != "", "You need to set an actual prompt to use this method." # Process the text prompts. text_embeddings = rgb_inpainter.compute_text_embeddings(config.prompt, config.negative_prompt) if config.use_expanded_attention:
register_extended_attention(rgb_inpainter.unet)
6
2023-12-07 19:12:08+00:00
12k
nnanhuang/Customize-it-3D
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, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.rank_zero 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 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 ldm.modules.attention import CrossAttention
9,718
""" 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, ): 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)
""" 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, ): 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)
6
2023-12-14 11:03:35+00:00
12k
TaoHuang13/diffusion_reward
scripts/train_vqdiffusion.py
[ { "identifier": "build_dataloader", "path": "diffusion_reward/models/video_models/vqdiffusion/data/build.py", "snippet": "def build_dataloader(config, args=None, return_dataset=True):\n dataset_cfg = config['dataloader']\n train_dataset = []\n for ds_cfg in dataset_cfg['train_datasets']:\n ...
import os import warnings import hydra import torch from diffusion_reward.models.video_models.vqdiffusion.data.build import \ build_dataloader from diffusion_reward.models.video_models.vqdiffusion.distributed.launch import launch from diffusion_reward.models.video_models.vqdiffusion.engine.logger import Logger from diffusion_reward.models.video_models.vqdiffusion.engine.solver import Solver from diffusion_reward.models.video_models.vqdiffusion.modeling.build import \ build_model from diffusion_reward.models.video_models.vqdiffusion.utils.io import load_yaml_config from diffusion_reward.models.video_models.vqdiffusion.utils.misc import ( merge_opts_to_config, modify_config_for_debug, seed_everything)
8,663
# environment variables NODE_RANK = os.environ['AZ_BATCHAI_TASK_INDEX'] if 'AZ_BATCHAI_TASK_INDEX' in os.environ else 0 NODE_RANK = int(NODE_RANK) MASTER_ADDR, MASTER_PORT = os.environ['AZ_BATCH_MASTER_NODE'].split(':') if 'AZ_BATCH_MASTER_NODE' in os.environ else ("127.0.0.1", 29500) MASTER_PORT = int(MASTER_PORT) DIST_URL = 'tcp://%s:%s' % (MASTER_ADDR, MASTER_PORT) @hydra.main(config_path='../diffusion_reward/configs/models/video_models/vqdiffusion', config_name='default') def main(args): args.save_dir = os.path.abspath(os.path.dirname(__file__)) args.node_rank = NODE_RANK args.dist_url = DIST_URL if args.seed is not None or args.cudnn_deterministic: seed_everything(args.seed, args.cudnn_deterministic) if args.gpu is not None: warnings.warn('You have chosen a specific GPU. This will completely disable ddp.') torch.cuda.set_device(args.gpu) args.ngpus_per_node = 1 args.world_size = 1 else: if args.num_node == 1: args.dist_url == "auto" else: assert args.num_node > 1 args.ngpus_per_node = torch.cuda.device_count() args.world_size = args.ngpus_per_node * args.num_node launch(main_worker, args.ngpus_per_node, args.num_node, args.node_rank, args.dist_url, args=(args,)) def main_worker(local_rank, args): args.local_rank = local_rank args.global_rank = args.local_rank + args.node_rank * args.ngpus_per_node # load config config = args config = merge_opts_to_config(config, args.opts) if args.debug: config = modify_config_for_debug(config) # get logger logger = Logger(args) # get model model = build_model(config, args) # print(model) if args.sync_bn: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) # get dataloader dataloader_info = build_dataloader(config, args) # get solver
# environment variables NODE_RANK = os.environ['AZ_BATCHAI_TASK_INDEX'] if 'AZ_BATCHAI_TASK_INDEX' in os.environ else 0 NODE_RANK = int(NODE_RANK) MASTER_ADDR, MASTER_PORT = os.environ['AZ_BATCH_MASTER_NODE'].split(':') if 'AZ_BATCH_MASTER_NODE' in os.environ else ("127.0.0.1", 29500) MASTER_PORT = int(MASTER_PORT) DIST_URL = 'tcp://%s:%s' % (MASTER_ADDR, MASTER_PORT) @hydra.main(config_path='../diffusion_reward/configs/models/video_models/vqdiffusion', config_name='default') def main(args): args.save_dir = os.path.abspath(os.path.dirname(__file__)) args.node_rank = NODE_RANK args.dist_url = DIST_URL if args.seed is not None or args.cudnn_deterministic: seed_everything(args.seed, args.cudnn_deterministic) if args.gpu is not None: warnings.warn('You have chosen a specific GPU. This will completely disable ddp.') torch.cuda.set_device(args.gpu) args.ngpus_per_node = 1 args.world_size = 1 else: if args.num_node == 1: args.dist_url == "auto" else: assert args.num_node > 1 args.ngpus_per_node = torch.cuda.device_count() args.world_size = args.ngpus_per_node * args.num_node launch(main_worker, args.ngpus_per_node, args.num_node, args.node_rank, args.dist_url, args=(args,)) def main_worker(local_rank, args): args.local_rank = local_rank args.global_rank = args.local_rank + args.node_rank * args.ngpus_per_node # load config config = args config = merge_opts_to_config(config, args.opts) if args.debug: config = modify_config_for_debug(config) # get logger logger = Logger(args) # get model model = build_model(config, args) # print(model) if args.sync_bn: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) # get dataloader dataloader_info = build_dataloader(config, args) # get solver
solver = Solver(config=config, args=args, model=model, dataloader=dataloader_info, logger=logger)
3
2023-12-05 02:42:28+00:00
12k
mkang315/ASF-YOLO
models/yolo.py
[ { "identifier": "check_anchor_order", "path": "utils/autoanchor.py", "snippet": "def check_anchor_order(m):\n # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary\n a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer\n da = a...
import argparse import contextlib import os import platform import sys import thop # for FLOPs computation import yaml # for torch hub from copy import deepcopy from pathlib import Path from models.common import * from models.experimental import * from utils.autoanchor import check_anchor_order from utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args from utils.plots import feature_visualization from utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device, time_sync)
7,866
m = self.model[-1] # Detect() module for mi, s in zip(m.m, m.stride): # from b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) b.data[:, 5:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility class SegmentationModel(DetectionModel): # YOLOv5 segmentation model def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None): super().__init__(cfg, ch, nc, anchors) class ClassificationModel(BaseModel): # YOLOv5 classification model def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index super().__init__() self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg) def _from_detection_model(self, model, nc=1000, cutoff=10): # Create a YOLOv5 classification model from a YOLOv5 detection model if isinstance(model, DetectMultiBackend): model = model.model # unwrap DetectMultiBackend model.model = model.model[:cutoff] # backbone m = model.model[-1] # last layer ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module c = Classify(ch, nc) # Classify() c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type model.model[-1] = c # replace self.model = model.model self.stride = model.stride self.save = [] self.nc = nc def _from_yaml(self, cfg): # Create a YOLOv5 classification model from a *.yaml file self.model = None def parse_model(d, ch): # model_dict, input_channels(3) # Parse a YOLOv5 model.yaml dictionary LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation') if act: Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU() LOGGER.info(f"{colorstr('activation:')} {act}") # print na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors no = na * (nc + 5) # number of outputs = anchors * (classes + 5) layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args m = eval(m) if isinstance(m, str) else m # eval strings for j, a in enumerate(args): with contextlib.suppress(NameError): args[j] = eval(a) if isinstance(a, str) else a # eval strings n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain if m in { Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, DownSample}: c1, c2 = ch[f], args[0] if c2 != no: # if not output c2 = make_divisible(c2 * gw, 8) args = [c1, c2, *args[1:]] if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}: args.insert(2, n) # number of repeats n = 1 elif m is nn.BatchNorm2d: args = [ch[f]] elif m is Concat: c2 = sum(ch[x] for x in f) elif m is ScalSeq: c2 = args[0] elif m is Add: c2 = args[0] elif m is Zoom_cat: c2 = 3*args[0] elif m is attention_model: c2 = args[0] # TODO: channel, gw, gd elif m in {Detect, Segment}: args.append([ch[x] for x in f]) if isinstance(args[1], int): # number of anchors args[1] = [list(range(args[1] * 2))] * len(f) if m is Segment: args[3] = make_divisible(args[3] * gw, 8) elif m is Contract: c2 = ch[f] * args[0] ** 2 elif m is Expand: c2 = ch[f] // args[0] ** 2 else: c2 = ch[f] m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module t = str(m)[8:-2].replace('__main__.', '') # module type np = sum(x.numel() for x in m_.parameters()) # number params m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist layers.append(m_) if i == 0: ch = [] ch.append(c2) return nn.Sequential(*layers), sorted(save) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--profile', action='store_true', help='profile model speed') parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer') parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') opt = parser.parse_args()
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ YOLO-specific modules Usage: $ python models/yolo.py --cfg yolov5s.yaml """ 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 if platform.system() != 'Windows': ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative try: except ImportError: thop = None class Detect(nn.Module): # YOLOv5 Detect head for detection models stride = None # strides computed during build dynamic = False # force grid reconstruction export = False # export mode def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer super().__init__() self.nc = nc # number of classes self.no = nc + 5 # number of outputs per anchor self.nl = len(anchors) # number of detection layers self.na = len(anchors[0]) // 2 # number of anchors self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2) self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv self.inplace = inplace # use inplace ops (e.g. slice assignment) def forward(self, x): z = [] # inference output for i in range(self.nl): x[i] = self.m[i](x[i]) # conv bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() if not self.training: # inference if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]: self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i) if isinstance(self, Segment): # (boxes + masks) xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4) xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh y = torch.cat((xy, wh, conf.sigmoid(), mask), 4) else: # Detect (boxes only) xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4) xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh y = torch.cat((xy, wh, conf), 4) z.append(y.view(bs, self.na * nx * ny, self.no)) return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x) def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, '1.10.0')): d = self.anchors[i].device t = self.anchors[i].dtype shape = 1, self.na, ny, nx, 2 # grid shape y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t) yv, xv = torch.meshgrid(y, x, indexing='ij') if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5 anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape) return grid, anchor_grid class Segment(Detect): # YOLOv5 Segment head for segmentation models def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True): super().__init__(nc, anchors, ch, inplace) self.nm = nm # number of masks self.npr = npr # number of protos self.no = 5 + nc + self.nm # number of outputs per anchor self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv self.proto = Proto(ch[0], self.npr, self.nm) # protos self.detect = Detect.forward def forward(self, x): p = self.proto(x[0]) x = self.detect(self, x) return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1]) class BaseModel(nn.Module): # YOLOv5 base model def forward(self, x, profile=False, visualize=False): return self._forward_once(x, profile, visualize) # single-scale inference, train def _forward_once(self, x, profile=False, visualize=False): y, dt = [], [] # outputs for m in self.model: if m.f != -1: # if not from previous layer x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers if profile: self._profile_one_layer(m, x, dt) x = m(x) # run y.append(x if m.i in self.save else None) # save output if visualize: feature_visualization(x, m.type, m.i, save_dir=visualize) return x def _profile_one_layer(self, m, x, dt): c = m == self.model[-1] # is final layer, copy input as inplace fix o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs t = time_sync() for _ in range(10): m(x.copy() if c else x) dt.append((time_sync() - t) * 100) if m == self.model[0]: LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module") LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') if c: LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers LOGGER.info('Fusing layers... ') for m in self.model.modules(): if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv delattr(m, 'bn') # remove batchnorm m.forward = m.forward_fuse # update forward self.info() return self def info(self, verbose=False, img_size=640): # print model information model_info(self, verbose, img_size) def _apply(self, fn): # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers self = super()._apply(fn) m = self.model[-1] # Detect() if isinstance(m, (Detect, Segment)): m.stride = fn(m.stride) m.grid = list(map(fn, m.grid)) if isinstance(m.anchor_grid, list): m.anchor_grid = list(map(fn, m.anchor_grid)) return self class DetectionModel(BaseModel): # YOLOv5 detection model def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes super().__init__() if isinstance(cfg, dict): self.yaml = cfg # model dict else: # is *.yaml self.yaml_file = Path(cfg).name with open(cfg, encoding='ascii', errors='ignore') as f: self.yaml = yaml.safe_load(f) # model dict # Define model ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels if nc and nc != self.yaml['nc']: LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") self.yaml['nc'] = nc # override yaml value if anchors: LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') self.yaml['anchors'] = round(anchors) # override yaml value self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist self.names = [str(i) for i in range(self.yaml['nc'])] # default names self.inplace = self.yaml.get('inplace', True) # Build strides, anchors m = self.model[-1] # Detect() if isinstance(m, (Detect, Segment)): s = 256 # 2x min stride m.inplace = self.inplace forward = lambda x: self.forward(x)[0] if isinstance(m, Segment) else self.forward(x) m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))]) # forward check_anchor_order(m) m.anchors /= m.stride.view(-1, 1, 1) self.stride = m.stride self._initialize_biases() # only run once # Init weights, biases initialize_weights(self) self.info() LOGGER.info('') def forward(self, x, augment=False, profile=False, visualize=False): if augment: return self._forward_augment(x) # augmented inference, None return self._forward_once(x, profile, visualize) # single-scale inference, train def _forward_augment(self, x): img_size = x.shape[-2:] # height, width s = [1, 0.83, 0.67] # scales f = [None, 3, None] # flips (2-ud, 3-lr) y = [] # outputs for si, fi in zip(s, f): xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) yi = self._forward_once(xi)[0] # forward # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save yi = self._descale_pred(yi, fi, si, img_size) y.append(yi) y = self._clip_augmented(y) # clip augmented tails return torch.cat(y, 1), None # augmented inference, train def _descale_pred(self, p, flips, scale, img_size): # de-scale predictions following augmented inference (inverse operation) if self.inplace: p[..., :4] /= scale # de-scale if flips == 2: p[..., 1] = img_size[0] - p[..., 1] # de-flip ud elif flips == 3: p[..., 0] = img_size[1] - p[..., 0] # de-flip lr else: x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale if flips == 2: y = img_size[0] - y # de-flip ud elif flips == 3: x = img_size[1] - x # de-flip lr p = torch.cat((x, y, wh, p[..., 4:]), -1) return p def _clip_augmented(self, y): # Clip YOLOv5 augmented inference tails nl = self.model[-1].nl # number of detection layers (P3-P5) g = sum(4 ** x for x in range(nl)) # grid points e = 1 # exclude layer count i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices y[0] = y[0][:, :-i] # large i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices y[-1] = y[-1][:, i:] # small return y def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency # https://arxiv.org/abs/1708.02002 section 3.3 # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. m = self.model[-1] # Detect() module for mi, s in zip(m.m, m.stride): # from b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) b.data[:, 5:5 + m.nc] += math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility class SegmentationModel(DetectionModel): # YOLOv5 segmentation model def __init__(self, cfg='yolov5s-seg.yaml', ch=3, nc=None, anchors=None): super().__init__(cfg, ch, nc, anchors) class ClassificationModel(BaseModel): # YOLOv5 classification model def __init__(self, cfg=None, model=None, nc=1000, cutoff=10): # yaml, model, number of classes, cutoff index super().__init__() self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg) def _from_detection_model(self, model, nc=1000, cutoff=10): # Create a YOLOv5 classification model from a YOLOv5 detection model if isinstance(model, DetectMultiBackend): model = model.model # unwrap DetectMultiBackend model.model = model.model[:cutoff] # backbone m = model.model[-1] # last layer ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels # ch into module c = Classify(ch, nc) # Classify() c.i, c.f, c.type = m.i, m.f, 'models.common.Classify' # index, from, type model.model[-1] = c # replace self.model = model.model self.stride = model.stride self.save = [] self.nc = nc def _from_yaml(self, cfg): # Create a YOLOv5 classification model from a *.yaml file self.model = None def parse_model(d, ch): # model_dict, input_channels(3) # Parse a YOLOv5 model.yaml dictionary LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}") anchors, nc, gd, gw, act = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'], d.get('activation') if act: Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU() LOGGER.info(f"{colorstr('activation:')} {act}") # print na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors no = na * (nc + 5) # number of outputs = anchors * (classes + 5) layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args m = eval(m) if isinstance(m, str) else m # eval strings for j, a in enumerate(args): with contextlib.suppress(NameError): args[j] = eval(a) if isinstance(a, str) else a # eval strings n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain if m in { Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3, C3TR, C3SPP, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, DownSample}: c1, c2 = ch[f], args[0] if c2 != no: # if not output c2 = make_divisible(c2 * gw, 8) args = [c1, c2, *args[1:]] if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}: args.insert(2, n) # number of repeats n = 1 elif m is nn.BatchNorm2d: args = [ch[f]] elif m is Concat: c2 = sum(ch[x] for x in f) elif m is ScalSeq: c2 = args[0] elif m is Add: c2 = args[0] elif m is Zoom_cat: c2 = 3*args[0] elif m is attention_model: c2 = args[0] # TODO: channel, gw, gd elif m in {Detect, Segment}: args.append([ch[x] for x in f]) if isinstance(args[1], int): # number of anchors args[1] = [list(range(args[1] * 2))] * len(f) if m is Segment: args[3] = make_divisible(args[3] * gw, 8) elif m is Contract: c2 = ch[f] * args[0] ** 2 elif m is Expand: c2 = ch[f] // args[0] ** 2 else: c2 = ch[f] m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module t = str(m)[8:-2].replace('__main__.', '') # module type np = sum(x.numel() for x in m_.parameters()) # number params m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}') # print save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist layers.append(m_) if i == 0: ch = [] ch.append(c2) return nn.Sequential(*layers), sorted(save) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--profile', action='store_true', help='profile model speed') parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer') parser.add_argument('--test', action='store_true', help='test all yolo*.yaml') opt = parser.parse_args()
opt.cfg = check_yaml(opt.cfg) # check YAML
3
2023-12-10 14:18:29+00:00
12k
ylacombe/finetune-hf-vits
convert_original_discriminator_checkpoint.py
[ { "identifier": "VitsFeatureExtractor", "path": "utils/feature_extraction_vits.py", "snippet": "class VitsFeatureExtractor(SequenceFeatureExtractor):\n r\"\"\"\n Constructs a Vits feature extractor.\n\n This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExt...
import argparse import torch from transformers.models.vits.modeling_vits import VitsModel from transformers.models.vits.tokenization_vits import VitsTokenizer from huggingface_hub import hf_hub_download from utils.feature_extraction_vits import VitsFeatureExtractor from utils.configuration_vits import VitsConfig, logging from utils.modeling_vits_training import VitsDiscriminator, VitsModelForPreTraining
8,048
"""Convert VITS discriminator checkpoint and add it to an already converted VITS checkpoint.""" logging.set_verbosity_info() logger = logging.get_logger("transformers.models.vits") MAPPING = { "conv_post": "final_conv", } TOP_LEVEL_KEYS = [] IGNORE_KEYS = [] @torch.no_grad() def convert_checkpoint( language_code, pytorch_dump_folder_path, checkpoint_path=None, generator_checkpoint_path=None, repo_id=None, ): """ Copy/paste/tweak model's weights to transformers design. """ if language_code is not None: checkpoint_path = hf_hub_download(repo_id="facebook/mms-tts", subfolder=f"full_models/{language_code}", filename="D_100000.pth") generator_checkpoint_path = f"facebook/mms-tts-{language_code}"
"""Convert VITS discriminator checkpoint and add it to an already converted VITS checkpoint.""" logging.set_verbosity_info() logger = logging.get_logger("transformers.models.vits") MAPPING = { "conv_post": "final_conv", } TOP_LEVEL_KEYS = [] IGNORE_KEYS = [] @torch.no_grad() def convert_checkpoint( language_code, pytorch_dump_folder_path, checkpoint_path=None, generator_checkpoint_path=None, repo_id=None, ): """ Copy/paste/tweak model's weights to transformers design. """ if language_code is not None: checkpoint_path = hf_hub_download(repo_id="facebook/mms-tts", subfolder=f"full_models/{language_code}", filename="D_100000.pth") generator_checkpoint_path = f"facebook/mms-tts-{language_code}"
config = VitsConfig.from_pretrained(generator_checkpoint_path)
1
2023-12-11 17:56:49+00:00
12k
youngskkim/CRN
exps/det/CRN_r18_256x704_128x128_4key.py
[ { "identifier": "synchronize", "path": "utils/torch_dist.py", "snippet": "def synchronize():\n \"\"\"Helper function to synchronize (barrier)\n among all processes when using distributed training\"\"\"\n if not dist.is_available():\n return\n if not dist.is_initialized():\n ...
import torch from utils.torch_dist import synchronize from exps.base_cli import run_cli from exps.base_exp import BEVDepthLightningModel from models.camera_radar_net_det import CameraRadarNetDet
8,895
point_cloud_range=[0, 2.0, 0, 704, 58.0, 2], max_voxels=(768, 1024) ), 'pts_voxel_encoder': dict( type='PillarFeatureNet', in_channels=5, feat_channels=[32, 64], with_distance=False, with_cluster_center=False, with_voxel_center=True, voxel_size=[8, 0.4, 2], point_cloud_range=[0, 2.0, 0, 704, 58.0, 2], norm_cfg=dict(type='BN1d', eps=1e-3, momentum=0.01), legacy=True ), 'pts_middle_encoder': dict( type='PointPillarsScatter', in_channels=64, output_shape=(140, 88) ), 'pts_backbone': dict( type='SECOND', in_channels=64, out_channels=[64, 128, 256], layer_nums=[2, 3, 3], layer_strides=[1, 2, 2], norm_cfg=dict(type='BN', eps=1e-3, momentum=0.01), conv_cfg=dict(type='Conv2d', bias=True, padding_mode='reflect') ), 'pts_neck': dict( type='SECONDFPN', in_channels=[64, 128, 256], out_channels=[64, 64, 64], upsample_strides=[0.5, 1, 2], norm_cfg=dict(type='BN', eps=1e-3, momentum=0.01), upsample_cfg=dict(type='deconv', bias=False), use_conv_for_no_stride=True ), 'out_channels_pts': 80, } ################################################ self.fuser_conf = { 'img_dims': 80, 'pts_dims': 80, 'embed_dims': 128, 'num_layers': 6, 'num_heads': 4, 'bev_shape': (128, 128), } ################################################ self.head_conf = { 'bev_backbone_conf': dict( type='ResNet', in_channels=128, depth=18, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=[0, 1, 2], norm_eval=False, base_channels=128, ), 'bev_neck_conf': dict( type='SECONDFPN', in_channels=[128, 128, 256, 512], upsample_strides=[1, 2, 4, 8], out_channels=[64, 64, 64, 64] ), 'tasks': [ dict(num_class=1, class_names=['car']), dict(num_class=2, class_names=['truck', 'construction_vehicle']), dict(num_class=2, class_names=['bus', 'trailer']), dict(num_class=1, class_names=['barrier']), dict(num_class=2, class_names=['motorcycle', 'bicycle']), dict(num_class=2, class_names=['pedestrian', 'traffic_cone']), ], 'common_heads': dict( reg=(2, 2), height=(1, 2), dim=(3, 2), rot=(2, 2), vel=(2, 2)), 'bbox_coder': dict( type='CenterPointBBoxCoder', post_center_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_num=500, score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], pc_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], code_size=9, ), 'train_cfg': dict( point_cloud_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], grid_size=[512, 512, 1], voxel_size=[0.2, 0.2, 8], out_size_factor=4, dense_reg=1, gaussian_overlap=0.1, max_objs=500, min_radius=2, code_weights=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], ), 'test_cfg': dict( post_center_limit_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_per_img=500, max_pool_nms=False, min_radius=[4, 12, 10, 1, 0.85, 0.175], score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], nms_type='circle', pre_max_size=1000, post_max_size=200, nms_thr=0.2, ), 'in_channels': 256, # Equal to bev_neck output_channels. 'loss_cls': dict(type='GaussianFocalLoss', reduction='mean'), 'loss_bbox': dict(type='L1Loss', reduction='mean', loss_weight=0.25), 'gaussian_overlap': 0.1, 'min_radius': 2, } ################################################ self.key_idxes = [-2, -4, -6]
""" mAP: 0.4492 mATE: 0.5236 mASE: 0.2857 mAOE: 0.5640 mAVE: 0.2781 mAAE: 0.1792 NDS: 0.5415 Eval time: 185.7s Per-class results: Object Class AP ATE ASE AOE AVE AAE car 0.702 0.312 0.172 0.146 0.306 0.197 truck 0.406 0.501 0.221 0.153 0.235 0.207 bus 0.506 0.542 0.210 0.130 0.404 0.178 trailer 0.227 0.880 0.252 0.600 0.205 0.100 construction_vehicle 0.133 0.819 0.518 1.251 0.111 0.352 pedestrian 0.450 0.558 0.291 0.683 0.368 0.174 motorcycle 0.478 0.413 0.257 0.820 0.425 0.213 bicycle 0.442 0.409 0.268 1.140 0.171 0.012 traffic_cone 0.544 0.414 0.378 nan nan nan barrier 0.604 0.388 0.291 0.153 nan nan img: 10.84 img_backbone: 3.62 img_dep: 1.35 img_transform: 5.01 img_pool: 0.54 pts: 8.46 pts_voxelize: 1.87 pts_backbone: 5.27 pts_head: 0.64 fusion: 6.77 fusion_pre: 0.81 fusion_layer: 5.31 fusion_post: 0.07 head: 7.97 head_backbone: 2.14 head_head: 5.83 total: 34.04 FPS: 29.38 | Name | Type | Params --------------------------------------------------------------------------------------- 0 | model | CameraRadarNetDet | 37.2 M 1 | model.backbone_img | RVTLSSFPN | 17.0 M 2 | model.backbone_img.img_backbone | ResNet | 11.2 M 3 | model.backbone_img.img_neck | SECONDFPN | 246 K 4 | model.backbone_img.depth_net | DepthNet | 4.8 M 5 | model.backbone_img.view_aggregation_net | ViewAggregation | 807 K 6 | model.backbone_pts | PtsBackbone | 3.1 M 7 | model.backbone_pts.pts_voxel_layer | Voxelization | 0 8 | model.backbone_pts.pts_voxel_encoder | PillarFeatureNet | 2.3 K 9 | model.backbone_pts.pts_middle_encoder | PointPillarsScatter | 0 10 | model.backbone_pts.pts_backbone | SECOND | 2.7 M 11 | model.backbone_pts.pts_neck | SECONDFPN | 90.5 K 12 | model.backbone_pts.pred_context | Sequential | 173 K 13 | model.backbone_pts.pred_occupancy | Sequential | 166 K 14 | model.fuser | MFAFuser | 1.2 M 15 | model.fuser.norm_img | LayerNorm | 160 16 | model.fuser.norm_pts | LayerNorm | 160 17 | model.fuser.input_proj | Linear | 20.6 K 18 | model.fuser.positional_encoding | LearnedPositionalEncoding | 16.4 K 19 | model.fuser.ffn_layers | ModuleList | 395 K 20 | model.fuser.norm_layers1 | ModuleList | 1.5 K 21 | model.fuser.norm_layers2 | ModuleList | 1.5 K 22 | model.fuser.attn_layers | ModuleList | 198 K 23 | model.fuser.reduce_conv | Sequential | 590 K 24 | model.head | BEVDepthHead | 15.8 M 25 | model.head.loss_cls | GaussianFocalLoss | 0 26 | model.head.loss_bbox | L1Loss | 0 27 | model.head.shared_conv | ConvModule | 147 K 28 | model.head.task_heads | ModuleList | 1.4 M 29 | model.head.trunk | ResNet | 11.9 M 30 | model.head.neck | SECONDFPN | 2.4 M --------------------------------------------------------------------------------------- """ class CRNLightningModel(BEVDepthLightningModel): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.return_image = True self.return_depth = True self.return_radar_pv = True ################################################ self.optimizer_config = dict( type='AdamW', lr=2e-4, weight_decay=1e-4) ################################################ self.ida_aug_conf = { 'resize_lim': (0.386, 0.55), 'final_dim': (256, 704), 'rot_lim': (0., 0.), 'H': 900, 'W': 1600, 'rand_flip': True, 'bot_pct_lim': (0.0, 0.0), 'cams': [ 'CAM_FRONT_LEFT', 'CAM_FRONT', 'CAM_FRONT_RIGHT', 'CAM_BACK_LEFT', 'CAM_BACK', 'CAM_BACK_RIGHT' ], 'Ncams': 6, } self.bda_aug_conf = { 'rot_ratio': 1.0, 'rot_lim': (-22.5, 22.5), 'scale_lim': (0.9, 1.1), 'flip_dx_ratio': 0.5, 'flip_dy_ratio': 0.5 } ################################################ self.backbone_img_conf = { 'x_bound': [-51.2, 51.2, 0.8], 'y_bound': [-51.2, 51.2, 0.8], 'z_bound': [-5, 3, 8], 'd_bound': [2.0, 58.0, 0.8], 'final_dim': (256, 704), 'downsample_factor': 16, 'img_backbone_conf': dict( type='ResNet', depth=18, frozen_stages=0, out_indices=[0, 1, 2, 3], norm_eval=False, init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18'), ), 'img_neck_conf': dict( type='SECONDFPN', in_channels=[64, 128, 256, 512], upsample_strides=[0.25, 0.5, 1, 2], out_channels=[64, 64, 64, 64], ), 'depth_net_conf': dict(in_channels=256, mid_channels=256), 'radar_view_transform': True, 'camera_aware': False, 'output_channels': 80, } ################################################ self.backbone_pts_conf = { 'pts_voxel_layer': dict( max_num_points=8, voxel_size=[8, 0.4, 2], point_cloud_range=[0, 2.0, 0, 704, 58.0, 2], max_voxels=(768, 1024) ), 'pts_voxel_encoder': dict( type='PillarFeatureNet', in_channels=5, feat_channels=[32, 64], with_distance=False, with_cluster_center=False, with_voxel_center=True, voxel_size=[8, 0.4, 2], point_cloud_range=[0, 2.0, 0, 704, 58.0, 2], norm_cfg=dict(type='BN1d', eps=1e-3, momentum=0.01), legacy=True ), 'pts_middle_encoder': dict( type='PointPillarsScatter', in_channels=64, output_shape=(140, 88) ), 'pts_backbone': dict( type='SECOND', in_channels=64, out_channels=[64, 128, 256], layer_nums=[2, 3, 3], layer_strides=[1, 2, 2], norm_cfg=dict(type='BN', eps=1e-3, momentum=0.01), conv_cfg=dict(type='Conv2d', bias=True, padding_mode='reflect') ), 'pts_neck': dict( type='SECONDFPN', in_channels=[64, 128, 256], out_channels=[64, 64, 64], upsample_strides=[0.5, 1, 2], norm_cfg=dict(type='BN', eps=1e-3, momentum=0.01), upsample_cfg=dict(type='deconv', bias=False), use_conv_for_no_stride=True ), 'out_channels_pts': 80, } ################################################ self.fuser_conf = { 'img_dims': 80, 'pts_dims': 80, 'embed_dims': 128, 'num_layers': 6, 'num_heads': 4, 'bev_shape': (128, 128), } ################################################ self.head_conf = { 'bev_backbone_conf': dict( type='ResNet', in_channels=128, depth=18, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=[0, 1, 2], norm_eval=False, base_channels=128, ), 'bev_neck_conf': dict( type='SECONDFPN', in_channels=[128, 128, 256, 512], upsample_strides=[1, 2, 4, 8], out_channels=[64, 64, 64, 64] ), 'tasks': [ dict(num_class=1, class_names=['car']), dict(num_class=2, class_names=['truck', 'construction_vehicle']), dict(num_class=2, class_names=['bus', 'trailer']), dict(num_class=1, class_names=['barrier']), dict(num_class=2, class_names=['motorcycle', 'bicycle']), dict(num_class=2, class_names=['pedestrian', 'traffic_cone']), ], 'common_heads': dict( reg=(2, 2), height=(1, 2), dim=(3, 2), rot=(2, 2), vel=(2, 2)), 'bbox_coder': dict( type='CenterPointBBoxCoder', post_center_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_num=500, score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], pc_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], code_size=9, ), 'train_cfg': dict( point_cloud_range=[-51.2, -51.2, -5, 51.2, 51.2, 3], grid_size=[512, 512, 1], voxel_size=[0.2, 0.2, 8], out_size_factor=4, dense_reg=1, gaussian_overlap=0.1, max_objs=500, min_radius=2, code_weights=[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], ), 'test_cfg': dict( post_center_limit_range=[-61.2, -61.2, -10.0, 61.2, 61.2, 10.0], max_per_img=500, max_pool_nms=False, min_radius=[4, 12, 10, 1, 0.85, 0.175], score_threshold=0.01, out_size_factor=4, voxel_size=[0.2, 0.2, 8], nms_type='circle', pre_max_size=1000, post_max_size=200, nms_thr=0.2, ), 'in_channels': 256, # Equal to bev_neck output_channels. 'loss_cls': dict(type='GaussianFocalLoss', reduction='mean'), 'loss_bbox': dict(type='L1Loss', reduction='mean', loss_weight=0.25), 'gaussian_overlap': 0.1, 'min_radius': 2, } ################################################ self.key_idxes = [-2, -4, -6]
self.model = CameraRadarNetDet(self.backbone_img_conf,
3
2023-12-06 14:57:49+00:00
12k
jinxixiang/magic_animate_unofficial
animatediff/magic_animate/unet_controlnet.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "animatediff/magic_animate/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n ...
from dataclasses import dataclass from typing import List, Optional, Tuple, Union from einops import rearrange from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from animatediff.magic_animate.unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from .resnet import InflatedConv3d from .resampler import Resampler from diffusers.utils import WEIGHTS_NAME import os import json import torch import torch.nn as nn import torch.utils.checkpoint
9,759
# up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) 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): res = 2 ** (3 - i) 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=layers_per_block + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=reversed_attention_head_dim[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, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps) self.conv_act = nn.SiLU() self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maxium amount of memory will be 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_slicable_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_slicable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_slicable_dims(module) num_slicable_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_slicable_layers * [1] slice_size = num_slicable_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):
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # 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. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class ControlNetConditioningEmbedding(nn.Module): """ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full model) to encode image-space conditions ... into feature maps ..." """ def __init__( self, conditioning_embedding_channels: int, conditioning_channels: int = 3, block_out_channels: Tuple[int, ...] = (16, 32, 96, 256), ): super().__init__() self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1) self.blocks = nn.ModuleList([]) for i in range(len(block_out_channels) - 1): channel_in = block_out_channels[i] channel_out = block_out_channels[i + 1] self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1)) self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2)) self.conv_out = zero_module( nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1) ) def forward(self, conditioning): bsz = conditioning.shape[0] conditioning = rearrange(conditioning, 'b c f h w -> (b f) c h w').contiguous() embedding = self.conv_in(conditioning) embedding = torch.nn.functional.silu(embedding) for block in self.blocks: embedding = block(embedding) embedding = torch.nn.functional.silu(embedding) embedding = self.conv_out(embedding) embedding = rearrange(embedding, '(b f) c h w -> b c f h w', b=bsz).contiguous() return embedding def zero_module(module): for p in module.parameters(): nn.init.zeros_(p) return module class UNet3DConditionModel(ModelMixin, ConfigMixin): _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: 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: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", # Additional use_motion_module=False, motion_module_resolutions=(1, 2, 4, 8), motion_module_mid_block=False, motion_module_decoder_only=False, motion_module_type=None, motion_module_kwargs={}, unet_use_cross_frame_attention=None, unet_use_temporal_attention=None, # Addition for image embeddings use_image_condition=False, # Additional for dwpose adapter use_dwpose_adapter=False, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # 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) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None # dwpose condition if use_dwpose_adapter: self.dwpose_adapter = ControlNetConditioningEmbedding(conditioning_embedding_channels=4) # pose guider net else: self.dwpose_adapter = None self.use_image_condition = False if use_image_condition: self.use_image_condition = True self.image_proj_model = Resampler( dim=cross_attention_dim, depth=4, dim_head=64, heads=12, num_queries=16, embedding_dim=1024, output_dim=cross_attention_dim, ff_mult=4, ) self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i 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, in_channels=input_channel, out_channels=output_channel, temb_channels=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, attn_num_head_channels=attention_head_dim[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, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions) and ( not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn": self.mid_block = UNetMidBlock3DCrossAttn( in_channels=block_out_channels[-1], temb_channels=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, attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and motion_module_mid_block, motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the videos self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) 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): res = 2 ** (3 - i) 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=layers_per_block + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=reversed_attention_head_dim[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, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps) self.conv_act = nn.SiLU() self.conv_out = InflatedConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maxium amount of memory will be 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_slicable_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_slicable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_slicable_dims(module) num_slicable_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_slicable_layers * [1] slice_size = num_slicable_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)):
1
2023-12-12 00:16:39+00:00
12k
Chat-3D/Chat-3D-v2
others/process_vil3dref_results.py
[ { "identifier": "Chat3D", "path": "models/chat3d.py", "snippet": "class Chat3D(nn.Module):\n \"\"\"\n VideoChat model.\n \"\"\"\n def __init__(self, config):\n super().__init__()\n llama_model_path = config.get(\"llama_model_path\")\n low_resource = config.get(\"low_reso...
import json import jsonlines import math import torch import sys import torch from models.chat3d import Chat3D from utils.config_utils import setup_main from tasks.shared_utils import setup_model from utils.basic_utils import setup_seed from utils.distributed import get_rank from dataset.base_dataset import process_batch_data from tqdm import tqdm
9,540
""" loss/og3d: 2.9594, loss/obj3d_clf: 3.3753, loss/obj3d_clf_pre: 2.0714, loss/txt_clf: 0.6708, loss/total: 10.2789, loss/cross_attn_0: 0.0032, loss/cross_attn_1: 0.0011, loss/cross_attn_2: 0.0011, loss/cross_attn_3: 0.0012, loss/self_attn_0: 0.1595, loss/self_attn_1: 0.0425, loss/self_attn_2: 0.0541, loss/self_attn_3: 0.1030, loss/hidden_state_0: 0.3919, loss/hidden_state_1: 0.0765, loss/hidden_state_2: 0.1033, loss/hidden_state_3: 0.1308, loss/hidden_state_4: 0.1337, acc/og3d: 0.6373, acc/og3d_class: 0.8903, acc/obj3d_clf: 0.6828, acc/obj3d_clf_pre: 0.6131, acc/txt_clf: 0.9281 """ val_file = "/root/scene-LLaMA/datasets/exprs_neurips22/gtlabelpcd_mix/nr3d/preds/val_outs.json" nr3d_anno_file = "/root/scene-LLaMA/datasets/referit3d/annotations/bert_tokenized/nr3d.jsonl" anno_root = "annotations" # annotation dir attribute_file = f"{anno_root}/scannet_attributes_old.json" attributes = json.load(open(attribute_file, 'r')) val_results = json.load(open(val_file)) nr3d_anno = {} with jsonlines.open(nr3d_anno_file, "r") as reader: for l in reader: nr3d_anno[l["item_id"]] = l item_list = [] acc = 0 for k, v in val_results.items(): obj_ids = v["obj_ids"] obj_logits = v["obj_logits"] obj_logits = (torch.tensor(obj_logits)).softmax(dim=-1).tolist() scan_id = nr3d_anno[k]["scan_id"] utter = nr3d_anno[k]["utterance"] target_id = nr3d_anno[k]["target_id"] obj_num = len(attributes[scan_id]["locs"]) assert target_id < obj_num, f"{obj_num}, {target_id}, {scan_id}" logit_ids = zip(obj_logits, obj_ids) logit_ids = sorted(logit_ids, reverse=True) logits, ids = zip(*logit_ids) # logits = (torch.tensor(logits[:5]) / 5.).softmax(dim=-1).tolist() print(logits) if ids[0] == target_id: acc += 1 item_list.append({ "can_ids": ids[:5], "can_preds": logits[:5], "utter": utter, "target_id": target_id, "scan_id": scan_id }) # print(target_id) # print(ids[:5]) # print(logits[:5]) # exit() print("Acc:", float(acc) / len(item_list)) # print(item_list[:5]) # exit() sys.path.append(".") config = setup_main() setup_seed(config.seed + get_rank()) device = torch.device(config.device) num_steps_per_epoch = 7000 config.scheduler.num_training_steps = num_steps_per_epoch * config.scheduler.epochs config.scheduler.num_warmup_steps = num_steps_per_epoch * config.scheduler.warmup_epochs model_cls = eval(config.model.get('model_cls', 'Chat3D')) ( model, _, optimizer, scheduler, scaler, start_epoch, global_step,
""" loss/og3d: 2.9594, loss/obj3d_clf: 3.3753, loss/obj3d_clf_pre: 2.0714, loss/txt_clf: 0.6708, loss/total: 10.2789, loss/cross_attn_0: 0.0032, loss/cross_attn_1: 0.0011, loss/cross_attn_2: 0.0011, loss/cross_attn_3: 0.0012, loss/self_attn_0: 0.1595, loss/self_attn_1: 0.0425, loss/self_attn_2: 0.0541, loss/self_attn_3: 0.1030, loss/hidden_state_0: 0.3919, loss/hidden_state_1: 0.0765, loss/hidden_state_2: 0.1033, loss/hidden_state_3: 0.1308, loss/hidden_state_4: 0.1337, acc/og3d: 0.6373, acc/og3d_class: 0.8903, acc/obj3d_clf: 0.6828, acc/obj3d_clf_pre: 0.6131, acc/txt_clf: 0.9281 """ val_file = "/root/scene-LLaMA/datasets/exprs_neurips22/gtlabelpcd_mix/nr3d/preds/val_outs.json" nr3d_anno_file = "/root/scene-LLaMA/datasets/referit3d/annotations/bert_tokenized/nr3d.jsonl" anno_root = "annotations" # annotation dir attribute_file = f"{anno_root}/scannet_attributes_old.json" attributes = json.load(open(attribute_file, 'r')) val_results = json.load(open(val_file)) nr3d_anno = {} with jsonlines.open(nr3d_anno_file, "r") as reader: for l in reader: nr3d_anno[l["item_id"]] = l item_list = [] acc = 0 for k, v in val_results.items(): obj_ids = v["obj_ids"] obj_logits = v["obj_logits"] obj_logits = (torch.tensor(obj_logits)).softmax(dim=-1).tolist() scan_id = nr3d_anno[k]["scan_id"] utter = nr3d_anno[k]["utterance"] target_id = nr3d_anno[k]["target_id"] obj_num = len(attributes[scan_id]["locs"]) assert target_id < obj_num, f"{obj_num}, {target_id}, {scan_id}" logit_ids = zip(obj_logits, obj_ids) logit_ids = sorted(logit_ids, reverse=True) logits, ids = zip(*logit_ids) # logits = (torch.tensor(logits[:5]) / 5.).softmax(dim=-1).tolist() print(logits) if ids[0] == target_id: acc += 1 item_list.append({ "can_ids": ids[:5], "can_preds": logits[:5], "utter": utter, "target_id": target_id, "scan_id": scan_id }) # print(target_id) # print(ids[:5]) # print(logits[:5]) # exit() print("Acc:", float(acc) / len(item_list)) # print(item_list[:5]) # exit() sys.path.append(".") config = setup_main() setup_seed(config.seed + get_rank()) device = torch.device(config.device) num_steps_per_epoch = 7000 config.scheduler.num_training_steps = num_steps_per_epoch * config.scheduler.epochs config.scheduler.num_warmup_steps = num_steps_per_epoch * config.scheduler.warmup_epochs model_cls = eval(config.model.get('model_cls', 'Chat3D')) ( model, _, optimizer, scheduler, scaler, start_epoch, global_step,
) = setup_model(
2
2023-12-11 14:39:58+00:00
12k
SqueezeBits/owlite
owlite/owlite.py
[ { "identifier": "OWLITE_DEVICE_NAME", "path": "owlite_core/cli/device.py", "snippet": "OWLITE_DEVICE_NAME = CONNECTED_DEVICE[\"device\"] if CONNECTED_DEVICE else None" }, { "identifier": "OWLITE_FRONT_BASE_URL", "path": "owlite_core/constants.py", "snippet": "OWLITE_FRONT_BASE_URL = \"ht...
import json import os import torch from dataclasses import asdict, dataclass from typing import Any, Optional from torch.fx import GraphModule # type: ignore from torch.nn.parallel import DataParallel, DistributedDataParallel from owlite_core.cli.device import OWLITE_DEVICE_NAME from owlite_core.constants import ( OWLITE_FRONT_BASE_URL, OWLITE_REPO_PATH, OWLITE_REPORT_URL, ) from owlite_core.owlite_settings import OWLITE_SETTINGS from .api.device.devices import ( download_trt_engine, poll_run_benchmark, request_trt_benchmark, ) from .api.dove.doves import get_configuration, upload_baseline from .api.main.baselines import check_baseline_existence, create_baseline from .api.main.projects import create_or_load_project from .api.main.runs import ( copy_run, create_run, get_benchmark_key, get_run_info, update_run_info, upload_run_onnx_proto, ) from .backend.fx.trace import symbolic_trace from .backend.onnx.dynamize import configure_dynamic_dimensions from .backend.onnx.export import export, get_input_shape_signature from .logger import log from .options import GraphQuantizationOptions, ONNXExportOptions from .quantize import quantize
10,689
# type: ignore """OwLite Optimization Module This module facilitates optimization and benchmarking of models using OwLite services.""" @dataclass class OwLite: """Class handling OwLite project, baseline, and experiment configurations. The OwLite class manages project, baseline, and experiment configurations within the OwLite system. It allows users to create or load projects, set baselines, create or duplicate experiments, convert models, and benchmark models against the specified configurations. """ project_id: str project_name: str baseline_name: str experiment_name: str
# type: ignore """OwLite Optimization Module This module facilitates optimization and benchmarking of models using OwLite services.""" @dataclass class OwLite: """Class handling OwLite project, baseline, and experiment configurations. The OwLite class manages project, baseline, and experiment configurations within the OwLite system. It allows users to create or load projects, set baselines, create or duplicate experiments, convert models, and benchmark models against the specified configurations. """ project_id: str project_name: str baseline_name: str experiment_name: str
onnx_export_options: ONNXExportOptions
24
2023-12-08 06:41:50+00:00
12k
bolna-ai/bolna
bolna/providers.py
[ { "identifier": "PollySynthesizer", "path": "bolna/synthesizer/polly_synthesizer.py", "snippet": "class PollySynthesizer(BaseSynthesizer):\n def __init__(self, voice, language, audio_format=\"pcm\", sampling_rate=\"8000\", stream=False, engine=\"neural\",\n buffer_size=400):\n ...
from .synthesizer import PollySynthesizer, XTTSSynthesizer, ElevenlabsSynthesizer from .transcriber import DeepgramTranscriber from .input_handlers import DefaultInputHandler, TwilioInputHandler from .output_handlers import DefaultOutputHandler, TwilioOutputHandler from .llms import OpenAiLLM, LiteLLM
9,162
SUPPORTED_SYNTHESIZER_MODELS = { 'polly': PollySynthesizer, 'xtts': XTTSSynthesizer, "elevenlabs": ElevenlabsSynthesizer } SUPPORTED_TRANSCRIBER_MODELS = { 'deepgram': DeepgramTranscriber } SUPPORTED_LLM_MODELS = {
SUPPORTED_SYNTHESIZER_MODELS = { 'polly': PollySynthesizer, 'xtts': XTTSSynthesizer, "elevenlabs": ElevenlabsSynthesizer } SUPPORTED_TRANSCRIBER_MODELS = { 'deepgram': DeepgramTranscriber } SUPPORTED_LLM_MODELS = {
'openai': OpenAiLLM,
8
2023-12-13 09:07:35+00:00
12k
qitan/devops-backend-lite
apps/ucenter/views.py
[ { "identifier": "FEISHU_SYNC_USER_JOB_CACHE_KEY", "path": "common/variables.py", "snippet": "FEISHU_SYNC_USER_JOB_CACHE_KEY = 'celery_job:feishu_user_sync'" }, { "identifier": "Menu", "path": "dbapp/models.py", "snippet": "" }, { "identifier": "CustomModelViewSet", "path": "c...
import hashlib import django_filters import datetime import time import shortuuid import json import logging from django.core.cache import cache from rest_framework import viewsets, status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import action from rest_framework import pagination from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView from rest_framework_simplejwt.exceptions import TokenError, InvalidToken from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework_simplejwt.tokens import RefreshToken, Token, OutstandingToken from rest_framework.filters import SearchFilter, OrderingFilter from django_q.tasks import async_task, result from django.contrib.auth.models import update_last_login from django.db.models import Q from django.contrib.auth import logout from common.variables import FEISHU_SYNC_USER_JOB_CACHE_KEY from dbapp.models import Menu, Permission, Role, Organization, UserProfile, AuditLog, SystemConfig, DataDict from ucenter.serializers import MenuSerializers, MenuListSerializers, PermissionListSerializers, PermissionSerializers, \ RoleListSerializers, \ RoleSerializers, OrganizationSerializers, \ UserProfileListSerializers, UserProfileSerializers, UserProfileDetailSerializers, AuditLogSerializers, \ AuditLogActivitySerializers, SystemConfigSerializers, \ SystemConfigListSerializers, DataDictSerializers from common.extends.viewsets import CustomModelViewSet, CustomModelParentViewSet from common.extends.permissions import RbacPermission from common.extends.JwtAuth import CustomInvalidToken, TokenObtainPairSerializer, TokenRefreshSerializer from common.extends.handler import log_audit from common.extends.filters import AuditLogFilter, CustomSearchFilter from common.utils.JenkinsAPI import GlueJenkins from common.get_ip import user_ip from common.ext_fun import ThirdPartyUser, set_redis_data, get_redis_data, timeline_generate, time_period, \ node_filter from qtasks.tasks import test_notify from django.conf import settings from django.contrib.auth import login, REDIRECT_FIELD_NAME from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.cache import never_cache
10,672
{'get': ('data_list', '查看数据字典')}, {'post': ('data_create', '创建数据字典')}, {'put': ('data_edit', '编辑数据字典')}, {'patch': ('data_edit', '编辑数据字典')}, {'delete': ('data_delete', '删除数据字典')} """ perms_map = ( {'*': ('admin', '管理员')}, {'*': ('data_all', '数据字典管理')}, {'get': ('data_list', '查看数据字典')}, {'post': ('data_create', '创建数据字典')}, {'put': ('data_edit', '编辑数据字典')}, {'patch': ('data_edit', '编辑数据字典')}, {'delete': ('data_delete', '删除数据字典')} ) queryset = DataDict.objects.all() serializer_class = DataDictSerializers filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ('key', 'value') search_fields = ('key', 'value') def perform_update(self, serializer): serializer.save() cache.delete(f"datadict:{serializer.data['key']}:0") cache.delete(f"datadict:{serializer.data['key']}:1") @action(methods=['GET'], url_path='user', detail=False) def get_user(self, request): """ 获取用户列表 ### 传递参数 force: 0|1 force为1时强制刷新 """ _force = request.query_params.get('force', None) position = request.query_params.get('position', None) _key = str( f'project:users:{self.request.user.id}-{self.request.query_params}') try: data = cache.get(_key) except BaseException as e: cache.delete(_key) data = None if not data or _force: if position: users = UserProfile.objects.exclude( username='thirdparty').filter(position=position) else: users = UserProfile.objects.exclude(username='thirdparty') data = [{'id': i.id, 'first_name': i.first_name, 'username': i.username, 'name': i.name, 'title': i.title, 'position': i.position} for i in users] cache.set(_key, data, timeout=60 * 60 * 24) return Response({'code': 20000, 'data': data}) @action(methods=['GET'], url_path='extra', detail=False) def get_by_key(self, request): """ 通过指定key名获取 参数: key """ key_name = request.query_params.get('key', None) instance = self.queryset.get(key=key_name) serializer = self.get_serializer(instance) data = {'data': serializer.data, 'code': 20000, 'status': 'success'} return Response(data) class AuditLogViewSet(CustomModelViewSet): """ 审计日志视图 ### 审计日志权限 {'get': ('audit_list', '查看审计日志')} """ perms_map = ( {'*': ('admin', '管理员')}, {'get': ('audit_list', '查看审计日志')} ) queryset = AuditLog.objects.all() serializer_class = AuditLogSerializers filter_backends = (django_filters.rest_framework.DjangoFilterBackend, CustomSearchFilter, OrderingFilter) filter_class = AuditLogFilter filter_fields = ('user', 'type', 'action', 'action_ip', 'operator') search_fields = ('user', 'type', 'action', 'action_ip', 'content') def create(self, request, *args, **kwargs): pass def update(self, request, *args, **kwargs): pass def destroy(self, request, *args, **kwargs): pass class MenuViewSet(CustomModelParentViewSet): """ 菜单视图 ### 菜单权限 {'*': ('menu_all', '菜单管理')}, {'get': ('menu_list', '查看菜单')}, {'post': ('menu_create', '创建菜单')}, {'put': ('menu_edit', '编辑菜单')}, {'patch': ('menu_edit', '编辑菜单')}, {'delete': ('menu_delete', '删除菜单')} """ perms_map = ( {'*': ('admin', '管理员')}, {'*': ('menu_all', '菜单管理')}, {'get': ('menu_list', '查看菜单')}, {'post': ('menu_create', '创建菜单')}, {'put': ('menu_edit', '编辑菜单')}, {'patch': ('menu_edit', '编辑菜单')}, {'delete': ('menu_delete', '删除菜单')} )
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author : Charles Lai @Contact : qqing_lai@hotmail.com @Time : 2020/9/15 下午4:08 @FileName: views.py @Blog :https://imaojia.com """ logger = logging.getLogger('drf') DEFAULT_SESSION_TIMEOUT = None class DataDictViewSet(CustomModelParentViewSet): """ 数据字典视图 ### 数据字典权限 {'*': ('data_all', '数据字典管理')}, {'get': ('data_list', '查看数据字典')}, {'post': ('data_create', '创建数据字典')}, {'put': ('data_edit', '编辑数据字典')}, {'patch': ('data_edit', '编辑数据字典')}, {'delete': ('data_delete', '删除数据字典')} """ perms_map = ( {'*': ('admin', '管理员')}, {'*': ('data_all', '数据字典管理')}, {'get': ('data_list', '查看数据字典')}, {'post': ('data_create', '创建数据字典')}, {'put': ('data_edit', '编辑数据字典')}, {'patch': ('data_edit', '编辑数据字典')}, {'delete': ('data_delete', '删除数据字典')} ) queryset = DataDict.objects.all() serializer_class = DataDictSerializers filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ('key', 'value') search_fields = ('key', 'value') def perform_update(self, serializer): serializer.save() cache.delete(f"datadict:{serializer.data['key']}:0") cache.delete(f"datadict:{serializer.data['key']}:1") @action(methods=['GET'], url_path='user', detail=False) def get_user(self, request): """ 获取用户列表 ### 传递参数 force: 0|1 force为1时强制刷新 """ _force = request.query_params.get('force', None) position = request.query_params.get('position', None) _key = str( f'project:users:{self.request.user.id}-{self.request.query_params}') try: data = cache.get(_key) except BaseException as e: cache.delete(_key) data = None if not data or _force: if position: users = UserProfile.objects.exclude( username='thirdparty').filter(position=position) else: users = UserProfile.objects.exclude(username='thirdparty') data = [{'id': i.id, 'first_name': i.first_name, 'username': i.username, 'name': i.name, 'title': i.title, 'position': i.position} for i in users] cache.set(_key, data, timeout=60 * 60 * 24) return Response({'code': 20000, 'data': data}) @action(methods=['GET'], url_path='extra', detail=False) def get_by_key(self, request): """ 通过指定key名获取 参数: key """ key_name = request.query_params.get('key', None) instance = self.queryset.get(key=key_name) serializer = self.get_serializer(instance) data = {'data': serializer.data, 'code': 20000, 'status': 'success'} return Response(data) class AuditLogViewSet(CustomModelViewSet): """ 审计日志视图 ### 审计日志权限 {'get': ('audit_list', '查看审计日志')} """ perms_map = ( {'*': ('admin', '管理员')}, {'get': ('audit_list', '查看审计日志')} ) queryset = AuditLog.objects.all() serializer_class = AuditLogSerializers filter_backends = (django_filters.rest_framework.DjangoFilterBackend, CustomSearchFilter, OrderingFilter) filter_class = AuditLogFilter filter_fields = ('user', 'type', 'action', 'action_ip', 'operator') search_fields = ('user', 'type', 'action', 'action_ip', 'content') def create(self, request, *args, **kwargs): pass def update(self, request, *args, **kwargs): pass def destroy(self, request, *args, **kwargs): pass class MenuViewSet(CustomModelParentViewSet): """ 菜单视图 ### 菜单权限 {'*': ('menu_all', '菜单管理')}, {'get': ('menu_list', '查看菜单')}, {'post': ('menu_create', '创建菜单')}, {'put': ('menu_edit', '编辑菜单')}, {'patch': ('menu_edit', '编辑菜单')}, {'delete': ('menu_delete', '删除菜单')} """ perms_map = ( {'*': ('admin', '管理员')}, {'*': ('menu_all', '菜单管理')}, {'get': ('menu_list', '查看菜单')}, {'post': ('menu_create', '创建菜单')}, {'put': ('menu_edit', '编辑菜单')}, {'patch': ('menu_edit', '编辑菜单')}, {'delete': ('menu_delete', '删除菜单')} )
queryset = Menu.objects.all()
1
2023-12-13 03:09:32+00:00
12k
AdaCheng/EgoThink
models/llava_legacy/model/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "models/llava_legacy/model/mpt/attention.py", "snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if ali...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .norm import NORM_CLASS_REGISTRY from .configuration_mpt import MPTConfig from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm from .meta_init_context import init_empty_weights from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from transformers.utils import logging
9,134
assert isinstance(prefix_mask, torch.Tensor) attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask) if self.attn_uses_sequence_id and sequence_id is not None: assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: attn_bias = attn_bias[:, :, :, -s_k:] if prefix_mask is not None and attention_mask.shape != prefix_mask.shape: raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.') min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val) return (attn_bias, None) def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor): (s_k, s_q) = attn_bias.shape[-2:] if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len: raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.') seq_len = prefix_mask.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, tok_emb: Optional[torch.FloatTensor]=None): return_dict = return_dict if return_dict is not None else self.config.return_dict use_cache = use_cache if use_cache is not None else self.config.use_cache if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False if attention_mask is not None: attention_mask = attention_mask.bool() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: raise NotImplementedError('output_attentions is not implemented yet for MPT') if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training: raise NotImplementedError('MPT does not support training with left padding.') if self.prefix_lm and prefix_mask is None: raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert tok_emb is not None S = tok_emb.size(1) if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if S + past_position > self.config.max_seq_len: raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=x.dtype, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, past_key_value) = torch.utils.checkpoint.checkpoint( block, x, past_key_value, attn_bias, attention_mask, self.is_causal ) else: (x, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal) if past_key_values is not None: past_key_values[b_idx] = past_key_value x = self.norm_f(x) return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] logger = logging.get_logger(__name__) class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' class MPTModel(MPTPreTrainedModel): def __init__(self, config: MPTConfig): config._validate_config() super().__init__(config) self.attn_impl = config.attn_config['attn_impl'] self.prefix_lm = config.attn_config['prefix_lm'] self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id'] self.alibi = config.attn_config['alibi'] self.alibi_bias_max = config.attn_config['alibi_bias_max'] if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys(): norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys()) raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).') norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()] self.embedding_fraction = config.embedding_fraction self.wte = nn.Embedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: self.wpe = nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device) self.emb_drop = nn.Dropout(config.emb_pdrop) self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)]) self.norm_f = norm_class(config.d_model, device=config.init_device) if config.init_device != 'meta': self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype) self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max) self._attn_bias_initialized = True if self.attn_impl == 'flash': return (self.attn_bias, attention_mask) if self.attn_bias is not None: self.attn_bias = self.attn_bias.to(dtype=dtype, device=device) attn_bias = self.attn_bias if self.prefix_lm: assert isinstance(attn_bias, torch.Tensor) assert isinstance(prefix_mask, torch.Tensor) attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask) if self.attn_uses_sequence_id and sequence_id is not None: assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: attn_bias = attn_bias[:, :, :, -s_k:] if prefix_mask is not None and attention_mask.shape != prefix_mask.shape: raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.') min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val) return (attn_bias, None) def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor): (s_k, s_q) = attn_bias.shape[-2:] if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len: raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.') seq_len = prefix_mask.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, tok_emb: Optional[torch.FloatTensor]=None): return_dict = return_dict if return_dict is not None else self.config.return_dict use_cache = use_cache if use_cache is not None else self.config.use_cache if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." ) use_cache = False if attention_mask is not None: attention_mask = attention_mask.bool() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: raise NotImplementedError('output_attentions is not implemented yet for MPT') if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training: raise NotImplementedError('MPT does not support training with left padding.') if self.prefix_lm and prefix_mask is None: raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert tok_emb is not None S = tok_emb.size(1) if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if S + past_position > self.config.max_seq_len: raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=x.dtype, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, past_key_value) = torch.utils.checkpoint.checkpoint( block, x, past_key_value, attn_bias, attention_mask, self.is_causal ) else: (x, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal) if past_key_values is not None: past_key_values[b_idx] = past_key_value x = self.norm_f(x) return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
10
2023-12-05 14:17:17+00:00
12k
modelscope/llmuses
llmuses/run_ms.py
[ { "identifier": "DATASET_ID", "path": "llmuses/benchmarks/ceval/ceval_adapter.py", "snippet": "DATASET_ID = 'modelscope/ceval-exam'" }, { "identifier": "DATASET_ID", "path": "llmuses/benchmarks/mmlu/mmlu_adapter.py", "snippet": "DATASET_ID = 'modelscope/mmlu'" }, { "identifier": ...
import argparse import torch from llmuses.benchmarks.ceval import DATASET_ID as CEVAL_EXAM from llmuses.benchmarks.mmlu import DATASET_ID as MMLU from llmuses.benchmarks.hellaswag import DATASET_ID as HELLA_SWAG from llmuses.benchmarks.arc import DATASET_ID as ARC from llmuses.benchmarks.truthful_qa import DATASET_ID as TRUTHFUL_QA from llmuses.constants import DEFAULT_ROOT_CACHE_DIR from llmuses.evaluator import Evaluator from llmuses.models.model_adapter import MultiChoiceModelAdapter, ContinuationLogitsModelAdapter from llmuses.utils.logger import get_logger from llmuses.models.dummy_chat_model import DummyChatModel from llmuses.benchmarks.ceval import CEVALAdapter from llmuses.benchmarks.mmlu import MMLUAdapter from llmuses.benchmarks.arc import ARCAdapter from llmuses.benchmarks.hellaswag import HellaSwagAdapter from llmuses.benchmarks.truthful_qa import TruthfulQaAdapter
7,391
# Copyright (c) Alibaba, Inc. and its affiliates. # flake8: noqa logger = get_logger() # TODO: add more precision MODEL_PRECISION_MAP = {'fp16': torch.float16, 'fp32': torch.float32, 'bf16': torch.bfloat16} """ Run evaluation process for ModelScope Leaderboard. """ def parse_args(): parser = argparse.ArgumentParser(description='Run evaluation on a model') parser.add_argument('--model', help='Model id from modelscope or huggingface.', required=True) parser.add_argument('--revision', help='Model revision.', required=False, default=None) parser.add_argument('--precision', help='Model precision.', default='bf16') parser.add_argument('--work-dir', help='root work cache dir.', default=None) parser.add_argument('--outputs-dir', help='Outputs dir.', default='outputs') parser.add_argument('--datasets-dir', help='Datasets dir.', default=DEFAULT_ROOT_CACHE_DIR) parser.add_argument('--device-map', help='device map.', default='auto') parser.add_argument('--max-eval-size', type=int, help='Max evaluation samples num for each subset', default=None) parser.add_argument('--dataset-id', help='Dataset id on modelscope', required=False, default=None) parser.add_argument('--debug', help='Debug mode, will print information for debugging.', action='store_true', default=False) parser.add_argument('--dry-run', help='Dry run in single processing mode.', action='store_true', default=False) parser.add_argument('--mem-cache', help='To use memory cache or not.', action='store_true', default=False) args = parser.parse_args() return args def main(): args = parse_args() logger.info(args) # Customize your target datasets here all_benchmarks = [CEVAL_EXAM, MMLU, ARC, HELLA_SWAG, TRUTHFUL_QA] dataset_id = args.dataset_id if dataset_id is None: datasets = all_benchmarks elif dataset_id in all_benchmarks: datasets = [dataset_id] else: raise ValueError(f'Unknown dataset: {dataset_id}, Supported datasets: {all_benchmarks}') # Get model instance if args.dry_run: model_adapter = DummyChatModel(model_cfg=dict()) # TODO model_id: str = 'dummy' model_revision: str = 'v1.0.0' model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16) else: model_id: str = args.model model_revision: str = args.revision model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16)
# Copyright (c) Alibaba, Inc. and its affiliates. # flake8: noqa logger = get_logger() # TODO: add more precision MODEL_PRECISION_MAP = {'fp16': torch.float16, 'fp32': torch.float32, 'bf16': torch.bfloat16} """ Run evaluation process for ModelScope Leaderboard. """ def parse_args(): parser = argparse.ArgumentParser(description='Run evaluation on a model') parser.add_argument('--model', help='Model id from modelscope or huggingface.', required=True) parser.add_argument('--revision', help='Model revision.', required=False, default=None) parser.add_argument('--precision', help='Model precision.', default='bf16') parser.add_argument('--work-dir', help='root work cache dir.', default=None) parser.add_argument('--outputs-dir', help='Outputs dir.', default='outputs') parser.add_argument('--datasets-dir', help='Datasets dir.', default=DEFAULT_ROOT_CACHE_DIR) parser.add_argument('--device-map', help='device map.', default='auto') parser.add_argument('--max-eval-size', type=int, help='Max evaluation samples num for each subset', default=None) parser.add_argument('--dataset-id', help='Dataset id on modelscope', required=False, default=None) parser.add_argument('--debug', help='Debug mode, will print information for debugging.', action='store_true', default=False) parser.add_argument('--dry-run', help='Dry run in single processing mode.', action='store_true', default=False) parser.add_argument('--mem-cache', help='To use memory cache or not.', action='store_true', default=False) args = parser.parse_args() return args def main(): args = parse_args() logger.info(args) # Customize your target datasets here all_benchmarks = [CEVAL_EXAM, MMLU, ARC, HELLA_SWAG, TRUTHFUL_QA] dataset_id = args.dataset_id if dataset_id is None: datasets = all_benchmarks elif dataset_id in all_benchmarks: datasets = [dataset_id] else: raise ValueError(f'Unknown dataset: {dataset_id}, Supported datasets: {all_benchmarks}') # Get model instance if args.dry_run: model_adapter = DummyChatModel(model_cfg=dict()) # TODO model_id: str = 'dummy' model_revision: str = 'v1.0.0' model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16) else: model_id: str = args.model model_revision: str = args.revision model_precision = MODEL_PRECISION_MAP.get(args.precision, torch.bfloat16)
model_adapter = MultiChoiceModelAdapter(model_id=model_id,
7
2023-12-07 06:10:49+00:00
12k
liujin112/PortraitDiffusion
main.py
[ { "identifier": "MasaCtrlPipeline", "path": "utils/pipeline.py", "snippet": "class MasaCtrlPipeline(StableDiffusionPipeline):\n\n def next_step(\n self,\n model_output: torch.FloatTensor,\n timestep: int,\n x: torch.FloatTensor,\n eta=0.,\n verbose=False\n ...
import os import sys import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import argparse import numpy as np from tqdm import tqdm from diffusers import DDIMScheduler,LCMScheduler from torchvision.utils import save_image from torchvision.io import read_image from PIL import Image from utils.pipeline import MasaCtrlPipeline from utils.masactrl_utils import AttentionBase, regiter_attention_editor_diffusers from utils.style_attn_control import MaskPromptedStyleAttentionControl
8,011
def load_image(image_path, res, device, gray=False): image = Image.open(image_path).convert('RGB') if not gray else Image.open(image_path).convert('L') image = torch.tensor(np.array(image)).float() if gray: image = image.unsqueeze(-1).repeat(1,1,3) image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) return image def load_mask(image_path, res, device): if image_path != '': image = Image.open(image_path).convert('RGB') image = torch.tensor(np.array(image)).float() image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) image = image[:, :1, :, :] else: return None return image def main(): args = argparse.ArgumentParser() args.add_argument("--step", type=int, default=0) args.add_argument("--layer", type=int, default=10) args.add_argument("--res", type=int, default=512) args.add_argument("--style_guidance", type=float, default=1.5) args.add_argument("--content", type=str, default=None) args.add_argument("--style", type=str, default=None) args.add_argument("--content_mask", type=str, default='') args.add_argument("--style_mask", type=str, default='') args.add_argument("--output", type=str, default='./results/') args.add_argument("--only_mask_region", action="store_true") args.add_argument("--model_path", type=str, default='runwayml/stable-diffusion-v1-5') args.add_argument("--SAC_step", type=int, default=35) args.add_argument("--num_inference_steps", type=int, default=50) args.add_argument("--LCM_lora", action="store_true") args = args.parse_args() STEP = args.step LAYPER = args.layer only_mask_region = args.only_mask_region out_dir = args.output style_guidance = args.style_guidance num_inference_steps = args.num_inference_steps SAC_step = args.SAC_step device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") Guidance_scale = 0.0 model_path = args.model_path model = MasaCtrlPipeline.from_pretrained(model_path).to(device) if args.LCM_lora: model.scheduler = LCMScheduler.from_config(model.scheduler.config) # load LCM-LoRA model.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") else: model.scheduler = DDIMScheduler.from_config(model.scheduler.config) source_image = load_image(args.content, args.res, device) style_image = load_image(args.style, args.res, device) style_mask = load_mask(args.style_mask, res=64, device=device) source_mask = load_mask(args.content_mask, res=args.res, device=device) with torch.no_grad(): style_content = torch.cat([style_image, source_image], dim=0) source_prompt = ['head', 'head'] prompts = source_prompt + ['head'] editor = AttentionBase()
def load_image(image_path, res, device, gray=False): image = Image.open(image_path).convert('RGB') if not gray else Image.open(image_path).convert('L') image = torch.tensor(np.array(image)).float() if gray: image = image.unsqueeze(-1).repeat(1,1,3) image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) return image def load_mask(image_path, res, device): if image_path != '': image = Image.open(image_path).convert('RGB') image = torch.tensor(np.array(image)).float() image = image.permute(2, 0, 1) image = image[:3].unsqueeze_(0).float() / 127.5 - 1. # [-1, 1] image = F.interpolate(image, (res, res)) image = image.to(device) image = image[:, :1, :, :] else: return None return image def main(): args = argparse.ArgumentParser() args.add_argument("--step", type=int, default=0) args.add_argument("--layer", type=int, default=10) args.add_argument("--res", type=int, default=512) args.add_argument("--style_guidance", type=float, default=1.5) args.add_argument("--content", type=str, default=None) args.add_argument("--style", type=str, default=None) args.add_argument("--content_mask", type=str, default='') args.add_argument("--style_mask", type=str, default='') args.add_argument("--output", type=str, default='./results/') args.add_argument("--only_mask_region", action="store_true") args.add_argument("--model_path", type=str, default='runwayml/stable-diffusion-v1-5') args.add_argument("--SAC_step", type=int, default=35) args.add_argument("--num_inference_steps", type=int, default=50) args.add_argument("--LCM_lora", action="store_true") args = args.parse_args() STEP = args.step LAYPER = args.layer only_mask_region = args.only_mask_region out_dir = args.output style_guidance = args.style_guidance num_inference_steps = args.num_inference_steps SAC_step = args.SAC_step device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") Guidance_scale = 0.0 model_path = args.model_path model = MasaCtrlPipeline.from_pretrained(model_path).to(device) if args.LCM_lora: model.scheduler = LCMScheduler.from_config(model.scheduler.config) # load LCM-LoRA model.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") else: model.scheduler = DDIMScheduler.from_config(model.scheduler.config) source_image = load_image(args.content, args.res, device) style_image = load_image(args.style, args.res, device) style_mask = load_mask(args.style_mask, res=64, device=device) source_mask = load_mask(args.content_mask, res=args.res, device=device) with torch.no_grad(): style_content = torch.cat([style_image, source_image], dim=0) source_prompt = ['head', 'head'] prompts = source_prompt + ['head'] editor = AttentionBase()
regiter_attention_editor_diffusers(model, editor)
2
2023-12-06 01:18:39+00:00
12k
MarilynKeller/aitviewer-skel
aitviewer/renderables/spheres.py
[ { "identifier": "Material", "path": "aitviewer/scene/material.py", "snippet": "class Material(object):\n \"\"\"Per object material properties.\"\"\"\n\n def __init__(\n self,\n diffuse=0.5,\n ambient=0.5,\n specular=0.5,\n color=(0.5, 0.5, 0.5, 1.0),\n ):\n ...
import moderngl import numpy as np from moderngl_window.opengl.vao import VAO from aitviewer.scene.material import Material from aitviewer.scene.node import Node from aitviewer.shaders import ( get_depth_only_program, get_fragmap_program, get_outline_program, get_sphere_instanced_program, ) from aitviewer.utils import usd from aitviewer.utils.decorators import hooked from aitviewer.utils.utils import set_lights_in_program, set_material_properties
9,397
:param radius: Radius of the spheres. :param color: Color of the spheres. :param rings: Longitudinal resolution. :param sectors: Latitudinal resolution. """ if len(positions.shape) == 2: positions = positions[np.newaxis] assert len(positions.shape) == 3 # Define a default material in case there is None. if isinstance(color, tuple) or len(color.shape) == 1: kwargs["material"] = kwargs.get("material", Material(color=color, ambient=0.2)) self.sphere_colors = kwargs["material"].color else: assert color.shape[1] == 4 and positions.shape[1] == color.shape[0] self.sphere_colors = color if "n_frames" not in kwargs: kwargs["n_frames"] = positions.shape[0] super().__init__(icon=icon, **kwargs) self._sphere_positions = positions self.radius = radius self.vertices, self.faces = _create_sphere(radius=1.0, rings=rings, sectors=sectors) self.n_vertices = self.vertices.shape[0] self.n_spheres = self.sphere_positions.shape[1] self.draw_edges = False self._need_upload = True # Render passes. self.outline = True self.fragmap = True self.depth_prepass = True self.cast_shadow = cast_shadow @property def bounds(self): bounds = self.get_bounds(self.sphere_positions) bounds[:, 0] -= self.radius bounds[:, 1] += self.radius return bounds @property def current_bounds(self): bounds = self.get_bounds(self.current_sphere_positions) bounds[:, 0] -= self.radius bounds[:, 1] += self.radius return bounds @property def vertex_colors(self): if len(self._sphere_colors.shape) == 1: return np.full((self.n_spheres * self.n_vertices, 4), self._sphere_colors) else: return np.tile(self._sphere_colors, (self.n_vertices, 1)) def color_one(self, index, color): new_colors = np.tile(np.array(self.material.color), (self.n_spheres, 1)) new_colors[index] = color self.sphere_colors = new_colors @Node.color.setter def color(self, color): self.material.color = color self.sphere_colors = color self.redraw() @property def sphere_colors(self): if len(self._sphere_colors.shape) == 1: t = np.tile(np.array(self._sphere_colors), (self.n_spheres, 1)) return t else: return self._sphere_colors @sphere_colors.setter def sphere_colors(self, color): if isinstance(color, tuple): color = np.array(color) self._sphere_colors = color self.redraw() @property def current_sphere_positions(self): idx = self.current_frame_id if self.sphere_positions.shape[0] > 1 else 0 return self.sphere_positions[idx] @current_sphere_positions.setter def current_sphere_positions(self, positions): assert len(positions.shape) == 2 idx = self.current_frame_id if self.sphere_positions.shape[0] > 1 else 0 self.sphere_positions[idx] = positions self.redraw() @property def sphere_positions(self): return self._sphere_positions @sphere_positions.setter def sphere_positions(self, pos): if len(pos.shape) == 2: pos = pos[np.newaxis] self._sphere_positions = pos self.n_frames = len(self._sphere_positions) self.redraw() def on_frame_update(self): self.redraw() def redraw(self, **kwargs): self._need_upload = True @Node.once def make_renderable(self, ctx: moderngl.Context): self.prog = get_sphere_instanced_program() vs_path = "sphere_instanced_positions.vs.glsl" self.outline_program = get_outline_program(vs_path)
# Copyright (C) 2023 ETH Zurich, Manuel Kaufmann, Velko Vechev, Dario Mylonopoulos def _create_sphere(radius=1.0, rings=16, sectors=32): """ Create a sphere centered at the origin. This is a port of moderngl-window's geometry.sphere() function, but it returns the vertices and faces explicitly instead of directly storing them in a VAO. :param radius: Radius of the sphere. :param rings: Longitudinal resolution. :param sectors: Latitudinal resolution. :return: vertices and faces of the sphere. """ R = 1.0 / (rings - 1) S = 1.0 / (sectors - 1) vertices = np.zeros((rings * sectors, 3)) v, n = 0, 0 for r in range(rings): for s in range(sectors): y = np.sin(-np.pi / 2 + np.pi * r * R) x = np.cos(2 * np.pi * s * S) * np.sin(np.pi * r * R) z = np.sin(2 * np.pi * s * S) * np.sin(np.pi * r * R) vertices[v] = np.array([x, y, z]) * radius v += 1 n += 1 faces = np.zeros([(rings - 1) * (sectors - 1) * 2, 3], dtype=np.int32) i = 0 for r in range(rings - 1): for s in range(sectors - 1): faces[i] = np.array([r * sectors + s, (r + 1) * sectors + (s + 1), r * sectors + (s + 1)]) faces[i + 1] = np.array([r * sectors + s, (r + 1) * sectors + s, (r + 1) * sectors + (s + 1)]) i += 2 return vertices, faces class Spheres(Node): """Render some simple spheres.""" def __init__( self, positions, radius=0.01, color=(0.0, 0.0, 1.0, 1.0), rings=16, sectors=32, icon="\u008d", cast_shadow=False, **kwargs, ): """ Initializer. :param positions: A numpy array of shape (F, N, 3) or (N, 3) containing N sphere positions for F time steps. :param radius: Radius of the spheres. :param color: Color of the spheres. :param rings: Longitudinal resolution. :param sectors: Latitudinal resolution. """ if len(positions.shape) == 2: positions = positions[np.newaxis] assert len(positions.shape) == 3 # Define a default material in case there is None. if isinstance(color, tuple) or len(color.shape) == 1: kwargs["material"] = kwargs.get("material", Material(color=color, ambient=0.2)) self.sphere_colors = kwargs["material"].color else: assert color.shape[1] == 4 and positions.shape[1] == color.shape[0] self.sphere_colors = color if "n_frames" not in kwargs: kwargs["n_frames"] = positions.shape[0] super().__init__(icon=icon, **kwargs) self._sphere_positions = positions self.radius = radius self.vertices, self.faces = _create_sphere(radius=1.0, rings=rings, sectors=sectors) self.n_vertices = self.vertices.shape[0] self.n_spheres = self.sphere_positions.shape[1] self.draw_edges = False self._need_upload = True # Render passes. self.outline = True self.fragmap = True self.depth_prepass = True self.cast_shadow = cast_shadow @property def bounds(self): bounds = self.get_bounds(self.sphere_positions) bounds[:, 0] -= self.radius bounds[:, 1] += self.radius return bounds @property def current_bounds(self): bounds = self.get_bounds(self.current_sphere_positions) bounds[:, 0] -= self.radius bounds[:, 1] += self.radius return bounds @property def vertex_colors(self): if len(self._sphere_colors.shape) == 1: return np.full((self.n_spheres * self.n_vertices, 4), self._sphere_colors) else: return np.tile(self._sphere_colors, (self.n_vertices, 1)) def color_one(self, index, color): new_colors = np.tile(np.array(self.material.color), (self.n_spheres, 1)) new_colors[index] = color self.sphere_colors = new_colors @Node.color.setter def color(self, color): self.material.color = color self.sphere_colors = color self.redraw() @property def sphere_colors(self): if len(self._sphere_colors.shape) == 1: t = np.tile(np.array(self._sphere_colors), (self.n_spheres, 1)) return t else: return self._sphere_colors @sphere_colors.setter def sphere_colors(self, color): if isinstance(color, tuple): color = np.array(color) self._sphere_colors = color self.redraw() @property def current_sphere_positions(self): idx = self.current_frame_id if self.sphere_positions.shape[0] > 1 else 0 return self.sphere_positions[idx] @current_sphere_positions.setter def current_sphere_positions(self, positions): assert len(positions.shape) == 2 idx = self.current_frame_id if self.sphere_positions.shape[0] > 1 else 0 self.sphere_positions[idx] = positions self.redraw() @property def sphere_positions(self): return self._sphere_positions @sphere_positions.setter def sphere_positions(self, pos): if len(pos.shape) == 2: pos = pos[np.newaxis] self._sphere_positions = pos self.n_frames = len(self._sphere_positions) self.redraw() def on_frame_update(self): self.redraw() def redraw(self, **kwargs): self._need_upload = True @Node.once def make_renderable(self, ctx: moderngl.Context): self.prog = get_sphere_instanced_program() vs_path = "sphere_instanced_positions.vs.glsl" self.outline_program = get_outline_program(vs_path)
self.depth_only_program = get_depth_only_program(vs_path)
2
2023-12-07 16:13:50+00:00
12k
nexB/dejacode
dje/api.py
[ { "identifier": "TabPermission", "path": "dje/api_custom.py", "snippet": "class TabPermission(permissions.BasePermission):\n \"\"\"\n Allow access only to superusers if the tab_permission are enabled\n for the user Dataspace.\n \"\"\"\n\n def has_permission(self, request, view):\n ...
import uuid import django_filters from contextlib import suppress from urllib.parse import urlparse from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError as DjangoValidationError from django.db import IntegrityError from django.db import models from django.urls import Resolver404 from django.urls import get_script_prefix from django.urls import resolve from django.utils.encoding import uri_to_iri from django.utils.text import get_text_list from django.utils.translation import gettext as _ from django_filters.rest_framework import FilterSet from rest_framework import mixins from rest_framework import serializers from rest_framework import status from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.exceptions import ValidationError as DRFValidationError from rest_framework.generics import get_object_or_404 from rest_framework.permissions import SAFE_METHODS from rest_framework.relations import ManyRelatedField from rest_framework.response import Response from dje.api_custom import TabPermission from dje.copier import copy_object from dje.fields import ExtendedNullBooleanSelect from dje.filters import LastModifiedDateFilter from dje.filters import MultipleUUIDFilter from dje.models import Dataspace from dje.models import ExternalReference from dje.models import History from dje.models import is_content_type_related from dje.models import is_secured from dje.notification import send_notification_email from dje.permissions import get_authorized_tabs from dje.permissions import get_protected_fields from dje.permissions import get_tabset_for_model from dje.utils import construct_changes_details_message from dje.utils import extract_name_version from dje.utils import has_permission from dje.utils import set_intermediate_explicit_m2m
8,436
for field_name, new_value in serializer.validated_data.items(): original_value = getattr(serializer.instance, field_name, None) if new_value != original_value: changed_data.append(field_name) changes_details.append((field_name, original_value, new_value)) fields_name = [field.name for field in serializer.Meta.model._meta.get_fields()] kwargs = {} if "last_modified_by" in fields_name: kwargs["last_modified_by"] = user serialized_data = None with suppress(AttributeError): serialized_data = serializer.instance.as_json() serializer.save(**kwargs) if changed_data: change_message = [_("Changed {}.").format(get_text_list(changed_data, _("and")))] change_message = " ".join(change_message) else: change_message = _("No fields changed.") History.log_change(user, serializer.instance, change_message, serialized_data) if History.CHANGE in self.email_notification_on: change_message += construct_changes_details_message( {serializer.instance: changes_details} ) send_notification_email(user, serializer.instance, History.CHANGE, change_message) class ExtraPermissionsViewSetMixin: def get_permissions(self): permission_classes = super().get_permissions() extra_permission = [permission() for permission in self.extra_permissions] return permission_classes + extra_permission class DataspacedSerializer(serializers.HyperlinkedModelSerializer): def __init__(self, *args, **kwargs): """ Add the `dataspace` attribute from the request User Dataspace. Required at save time and for validation. """ super().__init__(*args, **kwargs) request = self.context.get("request", None) self.dataspace = request.user.dataspace if request else None def save(self, **kwargs): """ Add the current user dataspace in the object data and Wrap the IntegrityError with proper DRFValidationError. Starts by popping the m2m data before the actual save() then set the m2m relations post save(). """ # Pops the m2m data from the validated_data dict before save() m2m_data = { f: self._validated_data.pop(f.name) for f in self.Meta.model._meta.get_fields() if f.many_to_many and not f.auto_created and f.name in self._validated_data } if "uuid" in self.validated_data and not self.validated_data.get("uuid"): kwargs.update({"uuid": uuid.uuid4()}) # Update the uuid in the view kwargs to allow a proper `get_object()` post update updated_uuid = self.validated_data.get("uuid") if updated_uuid: self.context["view"].kwargs["uuid"] = updated_uuid kwargs.update({"dataspace": self.dataspace}) try: instance = super().save(**kwargs) except (IntegrityError, DjangoValidationError) as e: raise DRFValidationError(str(e)) for field, data in m2m_data.items(): set_intermediate_explicit_m2m(instance, field, data) return instance def validate(self, attrs): """Add the uniqueness validation calling the logic from Model.clean().""" # Make a copy of the attrs and Remove the m2m values, # since those cannot be part of the clean() attrs_copy = attrs.copy() for f in self.Meta.model._meta.get_fields(): if f.many_to_many and not f.auto_created: attrs_copy.pop(f.name, None) if isinstance(f, models.ManyToOneRel): attrs_copy.pop(f.get_accessor_name(), None) for field_name in getattr(self.Meta, "exclude_from_validate", []): attrs_copy.pop(field_name, None) instance = self.Meta.model(**attrs_copy) instance.dataspace = self.dataspace # Set the id from the `instance` to handle create vs. edit in Model.`clean()` with suppress(AttributeError): instance.id = self.instance.id instance.clean(from_api=True) return attrs def get_fields(self): """Enable to override the UUID field. Also enabled the field level permissions.""" fields = super().get_fields() if "uuid" in fields: fields["uuid"].read_only = False fields["uuid"].allow_null = True request = self.context.get("request", None) if request: fields = self.apply_tabs_permission(fields, request.user)
# # Copyright (c) nexB Inc. and others. All rights reserved. # DejaCode is a trademark of nexB Inc. # SPDX-License-Identifier: AGPL-3.0-only # See https://github.com/nexB/dejacode for support or download. # See https://aboutcode.org for more information about AboutCode FOSS projects. # REFERENCE_VAR = "reference" class CreateRetrieveUpdateListViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet, ): """Provide default `create`, `retrieve`, `update`, `partial_update`, and `list` actions.""" email_notification_on = [] allow_reference_access = False def get_queryset(self): """ Allow to access the reference data if the `self.allow_reference_access` is True. The `REFERENCE_VAR` needs to be provided as a GET parameter `?reference=1` in the URL. The special value `combine` can be provided as value for the `reference` parameter, `?reference=combine`, to return records from both the user dataspace and the reference one. The special `merge` value value will include the reference records excluding the objects `uuid` already present in the user dataspace. The reference data access is only available on `SAFE_METHODS` ('GET', 'HEAD', 'OPTIONS'). """ user_dataspace = self.request.user.dataspace base_qs = super().get_queryset() user_qs = base_qs.scope(user_dataspace) reference_params_value = self.request.GET.get(REFERENCE_VAR) reference_access = all( [ self.allow_reference_access, reference_params_value, self.request.method in SAFE_METHODS, ] ) if not reference_access: return user_qs reference_dataspace = Dataspace.objects.get_reference() if not reference_dataspace: return user_qs if reference_params_value not in ["combine", "merge"]: reference_qs = base_qs.scope(reference_dataspace) return reference_qs combined_qs = base_qs.scope(user_dataspace, include_reference=True) if reference_params_value == "merge": return combined_qs.exclude( uuid__in=models.Subquery(user_qs.values("uuid")), dataspace=reference_dataspace, ) return combined_qs @action(detail=True, methods=["post"]) def copy_to_my_dataspace(self, request, uuid): reference_dataspace = Dataspace.objects.get_reference() permission_error = {"error": "You do not have rights to execute this action."} reference_access = all( [ self.allow_reference_access, reference_dataspace, ] ) if not reference_access: return Response(permission_error, status=status.HTTP_400_BAD_REQUEST) queryset = self.queryset.scope(reference_dataspace) reference_object = get_object_or_404(queryset, uuid=uuid) user = request.user target_dataspace = user.dataspace model_class = reference_object.__class__ if not has_permission(reference_object, user, "add"): return Response(permission_error, status=status.HTTP_400_BAD_REQUEST) if target_dataspace.is_reference: data = {"error": "Target dataspace cannot be the reference one."} return Response(data, status=status.HTTP_400_BAD_REQUEST) object_exists_in_target_dataspace = ( model_class._default_manager.scope(target_dataspace) .filter(uuid=reference_object.uuid) .exists() ) if object_exists_in_target_dataspace: data = {"error": "The object already exists in your local Dataspace."} return Response(data, status=status.HTTP_400_BAD_REQUEST) copied_object = copy_object(reference_object, target_dataspace, user) if not copied_object: data = {"error": "The object could not be copied."} return Response(data, status=status.HTTP_400_BAD_REQUEST) serializer = self.get_serializer(copied_object) return Response(serializer.data) def perform_create(self, serializer): """Add the Addition History.""" user = self.request.user fields_name = [field.name for field in serializer.Meta.model._meta.get_fields()] kwargs = {} if "created_by" in fields_name: kwargs["created_by"] = user if "last_modified_by" in fields_name: kwargs["last_modified_by"] = user serializer.save(**kwargs) History.log_addition(user, serializer.instance) if History.ADDITION in self.email_notification_on: send_notification_email(user, serializer.instance, History.ADDITION) def perform_update(self, serializer): """Add the CHANGE History.""" changed_data = [] changes_details = [] user = self.request.user for field_name, new_value in serializer.validated_data.items(): original_value = getattr(serializer.instance, field_name, None) if new_value != original_value: changed_data.append(field_name) changes_details.append((field_name, original_value, new_value)) fields_name = [field.name for field in serializer.Meta.model._meta.get_fields()] kwargs = {} if "last_modified_by" in fields_name: kwargs["last_modified_by"] = user serialized_data = None with suppress(AttributeError): serialized_data = serializer.instance.as_json() serializer.save(**kwargs) if changed_data: change_message = [_("Changed {}.").format(get_text_list(changed_data, _("and")))] change_message = " ".join(change_message) else: change_message = _("No fields changed.") History.log_change(user, serializer.instance, change_message, serialized_data) if History.CHANGE in self.email_notification_on: change_message += construct_changes_details_message( {serializer.instance: changes_details} ) send_notification_email(user, serializer.instance, History.CHANGE, change_message) class ExtraPermissionsViewSetMixin: def get_permissions(self): permission_classes = super().get_permissions() extra_permission = [permission() for permission in self.extra_permissions] return permission_classes + extra_permission class DataspacedSerializer(serializers.HyperlinkedModelSerializer): def __init__(self, *args, **kwargs): """ Add the `dataspace` attribute from the request User Dataspace. Required at save time and for validation. """ super().__init__(*args, **kwargs) request = self.context.get("request", None) self.dataspace = request.user.dataspace if request else None def save(self, **kwargs): """ Add the current user dataspace in the object data and Wrap the IntegrityError with proper DRFValidationError. Starts by popping the m2m data before the actual save() then set the m2m relations post save(). """ # Pops the m2m data from the validated_data dict before save() m2m_data = { f: self._validated_data.pop(f.name) for f in self.Meta.model._meta.get_fields() if f.many_to_many and not f.auto_created and f.name in self._validated_data } if "uuid" in self.validated_data and not self.validated_data.get("uuid"): kwargs.update({"uuid": uuid.uuid4()}) # Update the uuid in the view kwargs to allow a proper `get_object()` post update updated_uuid = self.validated_data.get("uuid") if updated_uuid: self.context["view"].kwargs["uuid"] = updated_uuid kwargs.update({"dataspace": self.dataspace}) try: instance = super().save(**kwargs) except (IntegrityError, DjangoValidationError) as e: raise DRFValidationError(str(e)) for field, data in m2m_data.items(): set_intermediate_explicit_m2m(instance, field, data) return instance def validate(self, attrs): """Add the uniqueness validation calling the logic from Model.clean().""" # Make a copy of the attrs and Remove the m2m values, # since those cannot be part of the clean() attrs_copy = attrs.copy() for f in self.Meta.model._meta.get_fields(): if f.many_to_many and not f.auto_created: attrs_copy.pop(f.name, None) if isinstance(f, models.ManyToOneRel): attrs_copy.pop(f.get_accessor_name(), None) for field_name in getattr(self.Meta, "exclude_from_validate", []): attrs_copy.pop(field_name, None) instance = self.Meta.model(**attrs_copy) instance.dataspace = self.dataspace # Set the id from the `instance` to handle create vs. edit in Model.`clean()` with suppress(AttributeError): instance.id = self.instance.id instance.clean(from_api=True) return attrs def get_fields(self): """Enable to override the UUID field. Also enabled the field level permissions.""" fields = super().get_fields() if "uuid" in fields: fields["uuid"].read_only = False fields["uuid"].allow_null = True request = self.context.get("request", None) if request: fields = self.apply_tabs_permission(fields, request.user)
protected_fields = get_protected_fields(self.Meta.model, request.user)
12
2023-12-07 16:57:42+00:00
12k
wusize/CLIM
src/open_clip/eva_clip/factory.py
[ { "identifier": "OPENAI_DATASET_MEAN", "path": "src/open_clip/eva_clip/constants.py", "snippet": "OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)" }, { "identifier": "OPENAI_DATASET_STD", "path": "src/open_clip/eva_clip/constants.py", "snippet": "OPENAI_DATASET_STD = (0.2686295...
import json import logging import os import pathlib import re import torch from copy import deepcopy from pathlib import Path from typing import Optional, Tuple, Union, Dict, Any from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD from .model import CLIP, CustomCLIP, convert_weights_to_lp, convert_to_custom_text_state_dict,\ get_cast_dtype from .openai import load_openai_model from .pretrained import is_pretrained_cfg, get_pretrained_cfg, download_pretrained, list_pretrained_tags_by_model from .transform import image_transform from .tokenizer import HFTokenizer, tokenize from .utils import resize_clip_pos_embed, resize_evaclip_pos_embed, resize_visual_pos_embed, resize_eva_pos_embed
9,537
device = torch.device(device) if pretrained and pretrained.lower() == 'openai': logging.info(f'Loading pretrained {model_name} from OpenAI.') model = load_openai_model( model_name, precision=precision, device=device, jit=jit, cache_dir=cache_dir, ) else: model_cfg = get_model_config(model_name) if model_cfg is not None: logging.info(f'Loaded {model_name} model config.') else: logging.error(f'Model config for {model_name} not found; available models {list_models()}.') raise RuntimeError(f'Model config for {model_name} not found.') if 'rope' in model_cfg.get('vision_cfg', {}): if model_cfg['vision_cfg']['rope']: os.environ['RoPE'] = "1" else: os.environ['RoPE'] = "0" if force_quick_gelu: # override for use of QuickGELU on non-OpenAI transformer models model_cfg["quick_gelu"] = True if force_patch_dropout is not None: # override the default patch dropout value model_cfg['vision_cfg']["patch_dropout"] = force_patch_dropout cast_dtype = get_cast_dtype(precision) custom_clip = model_cfg.pop('custom_text', False) or force_custom_clip or ('hf_model_name' in model_cfg['text_cfg']) if custom_clip: if 'hf_model_name' in model_cfg.get('text_cfg', {}): model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf model = CustomCLIP(**model_cfg, cast_dtype=cast_dtype) else: model = CLIP(**model_cfg, cast_dtype=cast_dtype) pretrained_cfg = {} if pretrained: checkpoint_path = '' pretrained_cfg = get_pretrained_cfg(model_name, pretrained) if pretrained_cfg: checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir) elif os.path.exists(pretrained): checkpoint_path = pretrained if checkpoint_path: logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=False ) else: error_str = ( f'Pretrained weights ({pretrained}) not found for model {model_name}.' f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.') logging.warning(error_str) raise RuntimeError(error_str) else: visual_checkpoint_path = '' text_checkpoint_path = '' if pretrained_image: pretrained_visual_model = pretrained_visual_model.replace('/', '-') # for callers using old naming with / in ViT names pretrained_image_cfg = get_pretrained_cfg(pretrained_visual_model, pretrained_image) if 'timm_model_name' in model_cfg.get('vision_cfg', {}): # pretrained weight loading for timm models set via vision_cfg model_cfg['vision_cfg']['timm_model_pretrained'] = True elif pretrained_image_cfg: visual_checkpoint_path = download_pretrained(pretrained_image_cfg, cache_dir=cache_dir) elif os.path.exists(pretrained_image): visual_checkpoint_path = pretrained_image else: logging.warning(f'Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.') raise RuntimeError(f'Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.') if pretrained_text: pretrained_text_model = pretrained_text_model.replace('/', '-') # for callers using old naming with / in ViT names pretrained_text_cfg = get_pretrained_cfg(pretrained_text_model, pretrained_text) if pretrained_image_cfg: text_checkpoint_path = download_pretrained(pretrained_text_cfg, cache_dir=cache_dir) elif os.path.exists(pretrained_text): text_checkpoint_path = pretrained_text else: logging.warning(f'Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.') raise RuntimeError(f'Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.') if visual_checkpoint_path: logging.info(f'Loading pretrained {model_name}.visual weights ({visual_checkpoint_path}).') if text_checkpoint_path: logging.info(f'Loading pretrained {model_name}.text weights ({text_checkpoint_path}).') if visual_checkpoint_path or text_checkpoint_path: load_pretrained_checkpoint( model, visual_checkpoint_path, text_checkpoint_path, strict=False, visual_model=pretrained_visual_model, text_model=pretrained_text_model, model_key="model|module|state_dict", skip_list=skip_list ) if "fp16" in precision or "bf16" in precision: logging.info(f'convert precision to {precision}') model = model.to(torch.bfloat16) if 'bf16' in precision else model.to(torch.float16) model.to(device=device) # set image / mean metadata from pretrained_cfg if available, or use default model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN
_MODEL_CONFIG_PATHS = [Path(__file__).parent / f"model_configs/"] _MODEL_CONFIGS = {} # directory (model_name: config) of model architecture configs def _natural_key(string_): return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_.lower())] def _rescan_model_configs(): global _MODEL_CONFIGS config_ext = ('.json',) config_files = [] for config_path in _MODEL_CONFIG_PATHS: if config_path.is_file() and config_path.suffix in config_ext: config_files.append(config_path) elif config_path.is_dir(): for ext in config_ext: config_files.extend(config_path.glob(f'*{ext}')) for cf in config_files: with open(cf, "r", encoding="utf8") as f: model_cfg = json.load(f) if all(a in model_cfg for a in ('embed_dim', 'vision_cfg', 'text_cfg')): _MODEL_CONFIGS[cf.stem] = model_cfg _MODEL_CONFIGS = dict(sorted(_MODEL_CONFIGS.items(), key=lambda x: _natural_key(x[0]))) _rescan_model_configs() # initial populate of model config registry def list_models(): """ enumerate available model architectures based on config files """ return list(_MODEL_CONFIGS.keys()) def add_model_config(path): """ add model config path or file and update registry """ if not isinstance(path, Path): path = Path(path) _MODEL_CONFIG_PATHS.append(path) _rescan_model_configs() def get_model_config(model_name): if model_name in _MODEL_CONFIGS: return deepcopy(_MODEL_CONFIGS[model_name]) else: return None def get_tokenizer(model_name): config = get_model_config(model_name) tokenizer = HFTokenizer(config['text_cfg']['hf_tokenizer_name']) if 'hf_tokenizer_name' in config['text_cfg'] else tokenize return tokenizer # loading openai CLIP weights when is_openai=True for training def load_state_dict(checkpoint_path: str, map_location: str='cpu', model_key: str='model|module|state_dict', is_openai: bool=False, skip_list: list=[]): if is_openai: model = torch.jit.load(checkpoint_path, map_location="cpu").eval() state_dict = model.state_dict() for key in ["input_resolution", "context_length", "vocab_size"]: state_dict.pop(key, None) else: checkpoint = torch.load(checkpoint_path, map_location=map_location) for mk in model_key.split('|'): if isinstance(checkpoint, dict) and mk in checkpoint: state_dict = checkpoint[mk] break else: state_dict = checkpoint if next(iter(state_dict.items()))[0].startswith('module'): state_dict = {k[7:]: v for k, v in state_dict.items()} for k in skip_list: if k in list(state_dict.keys()): logging.info(f"Removing key {k} from pretrained checkpoint") del state_dict[k] if os.getenv('RoPE') == '1': for k in list(state_dict.keys()): if 'freqs_cos' in k or 'freqs_sin' in k: del state_dict[k] return state_dict def load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=True): state_dict = load_state_dict(checkpoint_path, model_key=model_key, is_openai=False) # detect old format and make compatible with new format if 'positional_embedding' in state_dict and not hasattr(model, 'positional_embedding'): state_dict = convert_to_custom_text_state_dict(state_dict) if 'text.logit_scale' in state_dict and hasattr(model, 'logit_scale'): state_dict['logit_scale'] = state_dict['text.logit_scale'] del state_dict['text.logit_scale'] # resize_clip_pos_embed for CLIP and open CLIP if 'visual.positional_embedding' in state_dict: resize_clip_pos_embed(state_dict, model) # specified to eva_vit_model elif 'visual.pos_embed' in state_dict: resize_evaclip_pos_embed(state_dict, model) # resize_clip_pos_embed(state_dict, model) incompatible_keys = model.load_state_dict(state_dict, strict=strict) logging.info(f"incompatible_keys.missing_keys: {incompatible_keys.missing_keys}") return incompatible_keys def load_clip_visual_state_dict(checkpoint_path: str, map_location: str='cpu', is_openai: bool=False, skip_list:list=[]): state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list) for k in list(state_dict.keys()): if not k.startswith('visual.'): del state_dict[k] for k in list(state_dict.keys()): if k.startswith('visual.'): new_k = k[7:] state_dict[new_k] = state_dict[k] del state_dict[k] return state_dict def load_clip_text_state_dict(checkpoint_path: str, map_location: str='cpu', is_openai: bool=False, skip_list:list=[]): state_dict = load_state_dict(checkpoint_path, map_location=map_location, is_openai=is_openai, skip_list=skip_list) for k in list(state_dict.keys()): if k.startswith('visual.'): del state_dict[k] return state_dict def get_pretrained_tag(pretrained_model): pretrained_model = pretrained_model.lower() if "laion" in pretrained_model or "open_clip" in pretrained_model: return "open_clip" elif "openai" in pretrained_model: return "clip" elif "eva" in pretrained_model and "clip" in pretrained_model: return "eva_clip" else: return "other" def load_pretrained_checkpoint( model, visual_checkpoint_path, text_checkpoint_path, strict=True, visual_model=None, text_model=None, model_key="model|module|state_dict", skip_list=[]): visual_tag = get_pretrained_tag(visual_model) text_tag = get_pretrained_tag(text_model) logging.info(f"num of model state_dict keys: {len(model.state_dict().keys())}") visual_incompatible_keys, text_incompatible_keys = None, None if visual_checkpoint_path: if visual_tag == "eva_clip" or visual_tag == "open_clip": visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=False, skip_list=skip_list) elif visual_tag == "clip": visual_state_dict = load_clip_visual_state_dict(visual_checkpoint_path, is_openai=True, skip_list=skip_list) else: visual_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list) # resize_clip_pos_embed for CLIP and open CLIP if 'positional_embedding' in visual_state_dict: resize_visual_pos_embed(visual_state_dict, model) # specified to EVA model elif 'pos_embed' in visual_state_dict: resize_eva_pos_embed(visual_state_dict, model) visual_incompatible_keys = model.visual.load_state_dict(visual_state_dict, strict=strict) logging.info(f"num of loaded visual_state_dict keys: {len(visual_state_dict.keys())}") logging.info(f"visual_incompatible_keys.missing_keys: {visual_incompatible_keys.missing_keys}") if text_checkpoint_path: if text_tag == "eva_clip" or text_tag == "open_clip": text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=False, skip_list=skip_list) elif text_tag == "clip": text_state_dict = load_clip_text_state_dict(text_checkpoint_path, is_openai=True, skip_list=skip_list) else: text_state_dict = load_state_dict(visual_checkpoint_path, model_key=model_key, is_openai=False, skip_list=skip_list) text_incompatible_keys = model.text.load_state_dict(text_state_dict, strict=strict) logging.info(f"num of loaded text_state_dict keys: {len(text_state_dict.keys())}") logging.info(f"text_incompatible_keys.missing_keys: {text_incompatible_keys.missing_keys}") return visual_incompatible_keys, text_incompatible_keys def create_model( model_name: str, pretrained: Optional[str] = None, precision: str = 'fp32', device: Union[str, torch.device] = 'cpu', jit: bool = False, force_quick_gelu: bool = False, force_custom_clip: bool = False, force_patch_dropout: Optional[float] = None, pretrained_image: str = '', pretrained_text: str = '', pretrained_hf: bool = True, pretrained_visual_model: str = None, pretrained_text_model: str = None, cache_dir: Optional[str] = None, skip_list: list = [], ): model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names if isinstance(device, str): device = torch.device(device) if pretrained and pretrained.lower() == 'openai': logging.info(f'Loading pretrained {model_name} from OpenAI.') model = load_openai_model( model_name, precision=precision, device=device, jit=jit, cache_dir=cache_dir, ) else: model_cfg = get_model_config(model_name) if model_cfg is not None: logging.info(f'Loaded {model_name} model config.') else: logging.error(f'Model config for {model_name} not found; available models {list_models()}.') raise RuntimeError(f'Model config for {model_name} not found.') if 'rope' in model_cfg.get('vision_cfg', {}): if model_cfg['vision_cfg']['rope']: os.environ['RoPE'] = "1" else: os.environ['RoPE'] = "0" if force_quick_gelu: # override for use of QuickGELU on non-OpenAI transformer models model_cfg["quick_gelu"] = True if force_patch_dropout is not None: # override the default patch dropout value model_cfg['vision_cfg']["patch_dropout"] = force_patch_dropout cast_dtype = get_cast_dtype(precision) custom_clip = model_cfg.pop('custom_text', False) or force_custom_clip or ('hf_model_name' in model_cfg['text_cfg']) if custom_clip: if 'hf_model_name' in model_cfg.get('text_cfg', {}): model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf model = CustomCLIP(**model_cfg, cast_dtype=cast_dtype) else: model = CLIP(**model_cfg, cast_dtype=cast_dtype) pretrained_cfg = {} if pretrained: checkpoint_path = '' pretrained_cfg = get_pretrained_cfg(model_name, pretrained) if pretrained_cfg: checkpoint_path = download_pretrained(pretrained_cfg, cache_dir=cache_dir) elif os.path.exists(pretrained): checkpoint_path = pretrained if checkpoint_path: logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') load_checkpoint(model, checkpoint_path, model_key="model|module|state_dict", strict=False ) else: error_str = ( f'Pretrained weights ({pretrained}) not found for model {model_name}.' f'Available pretrained tags ({list_pretrained_tags_by_model(model_name)}.') logging.warning(error_str) raise RuntimeError(error_str) else: visual_checkpoint_path = '' text_checkpoint_path = '' if pretrained_image: pretrained_visual_model = pretrained_visual_model.replace('/', '-') # for callers using old naming with / in ViT names pretrained_image_cfg = get_pretrained_cfg(pretrained_visual_model, pretrained_image) if 'timm_model_name' in model_cfg.get('vision_cfg', {}): # pretrained weight loading for timm models set via vision_cfg model_cfg['vision_cfg']['timm_model_pretrained'] = True elif pretrained_image_cfg: visual_checkpoint_path = download_pretrained(pretrained_image_cfg, cache_dir=cache_dir) elif os.path.exists(pretrained_image): visual_checkpoint_path = pretrained_image else: logging.warning(f'Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.') raise RuntimeError(f'Pretrained weights ({visual_checkpoint_path}) not found for model {model_name}.visual.') if pretrained_text: pretrained_text_model = pretrained_text_model.replace('/', '-') # for callers using old naming with / in ViT names pretrained_text_cfg = get_pretrained_cfg(pretrained_text_model, pretrained_text) if pretrained_image_cfg: text_checkpoint_path = download_pretrained(pretrained_text_cfg, cache_dir=cache_dir) elif os.path.exists(pretrained_text): text_checkpoint_path = pretrained_text else: logging.warning(f'Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.') raise RuntimeError(f'Pretrained weights ({text_checkpoint_path}) not found for model {model_name}.text.') if visual_checkpoint_path: logging.info(f'Loading pretrained {model_name}.visual weights ({visual_checkpoint_path}).') if text_checkpoint_path: logging.info(f'Loading pretrained {model_name}.text weights ({text_checkpoint_path}).') if visual_checkpoint_path or text_checkpoint_path: load_pretrained_checkpoint( model, visual_checkpoint_path, text_checkpoint_path, strict=False, visual_model=pretrained_visual_model, text_model=pretrained_text_model, model_key="model|module|state_dict", skip_list=skip_list ) if "fp16" in precision or "bf16" in precision: logging.info(f'convert precision to {precision}') model = model.to(torch.bfloat16) if 'bf16' in precision else model.to(torch.float16) model.to(device=device) # set image / mean metadata from pretrained_cfg if available, or use default model.visual.image_mean = pretrained_cfg.get('mean', None) or OPENAI_DATASET_MEAN
model.visual.image_std = pretrained_cfg.get('std', None) or OPENAI_DATASET_STD
1
2023-12-09 05:43:08+00:00
12k
moonshot-admin/moonshot
third-party/pathspec-0.12.1/pathspec/gitignore.py
[ { "identifier": "PathSpec", "path": "third-party/pathspec-0.12.1/pathspec/pathspec.py", "snippet": "class PathSpec(object):\n\t\"\"\"\n\tThe :class:`PathSpec` class is a wrapper around a list of compiled\n\t:class:`.Pattern` instances.\n\t\"\"\"\n\n\tdef __init__(self, patterns: Iterable[Pattern]) -> No...
from typing import ( AnyStr, Callable, # Replaced by `collections.abc.Callable` in 3.9. Iterable, # Replaced by `collections.abc.Iterable` in 3.9. Optional, # Replaced by `X | None` in 3.10. Tuple, # Replaced by `tuple` in 3.9. Type, # Replaced by `type` in 3.9. TypeVar, Union, # Replaced by `X | Y` in 3.10. cast, overload) from .pathspec import ( PathSpec) from .pattern import ( Pattern) from .patterns.gitwildmatch import ( GitWildMatchPattern, _DIR_MARK) from .util import ( _is_iterable)
8,772
""" This module provides :class:`.GitIgnoreSpec` which replicates *.gitignore* behavior. """ Self = TypeVar("Self", bound="GitIgnoreSpec") """ :class:`GitIgnoreSpec` self type hint to support Python v<3.11 using PEP 673 recommendation. """ class GitIgnoreSpec(PathSpec): """ The :class:`GitIgnoreSpec` class extends :class:`pathspec.pathspec.PathSpec` to replicate *.gitignore* behavior. """ def __eq__(self, other: object) -> bool: """ Tests the equality of this gitignore-spec with *other* (:class:`GitIgnoreSpec`) by comparing their :attr:`~pathspec.pattern.Pattern` attributes. A non-:class:`GitIgnoreSpec` will not compare equal. """ if isinstance(other, GitIgnoreSpec): return super().__eq__(other) elif isinstance(other, PathSpec): return False else: return NotImplemented # Support reversed order of arguments from PathSpec. @overload @classmethod def from_lines( cls: Type[Self], pattern_factory: Union[str, Callable[[AnyStr], Pattern]], lines: Iterable[AnyStr], ) -> Self: ... @overload @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: ... @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: """ Compiles the pattern lines. *lines* (:class:`~collections.abc.Iterable`) yields each uncompiled pattern (:class:`str`). This simply has to yield each line so it can be a :class:`io.TextIOBase` (e.g., from :func:`open` or :class:`io.StringIO`) or the result from :meth:`str.splitlines`. *pattern_factory* can be :data:`None`, the name of a registered pattern factory (:class:`str`), or a :class:`~collections.abc.Callable` used to compile patterns. The callable must accept an uncompiled pattern (:class:`str`) and return the compiled pattern (:class:`pathspec.pattern.Pattern`). Default is :data:`None` for :class:`.GitWildMatchPattern`). Returns the :class:`GitIgnoreSpec` instance. """ if pattern_factory is None: pattern_factory = GitWildMatchPattern
""" This module provides :class:`.GitIgnoreSpec` which replicates *.gitignore* behavior. """ Self = TypeVar("Self", bound="GitIgnoreSpec") """ :class:`GitIgnoreSpec` self type hint to support Python v<3.11 using PEP 673 recommendation. """ class GitIgnoreSpec(PathSpec): """ The :class:`GitIgnoreSpec` class extends :class:`pathspec.pathspec.PathSpec` to replicate *.gitignore* behavior. """ def __eq__(self, other: object) -> bool: """ Tests the equality of this gitignore-spec with *other* (:class:`GitIgnoreSpec`) by comparing their :attr:`~pathspec.pattern.Pattern` attributes. A non-:class:`GitIgnoreSpec` will not compare equal. """ if isinstance(other, GitIgnoreSpec): return super().__eq__(other) elif isinstance(other, PathSpec): return False else: return NotImplemented # Support reversed order of arguments from PathSpec. @overload @classmethod def from_lines( cls: Type[Self], pattern_factory: Union[str, Callable[[AnyStr], Pattern]], lines: Iterable[AnyStr], ) -> Self: ... @overload @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: ... @classmethod def from_lines( cls: Type[Self], lines: Iterable[AnyStr], pattern_factory: Union[str, Callable[[AnyStr], Pattern], None] = None, ) -> Self: """ Compiles the pattern lines. *lines* (:class:`~collections.abc.Iterable`) yields each uncompiled pattern (:class:`str`). This simply has to yield each line so it can be a :class:`io.TextIOBase` (e.g., from :func:`open` or :class:`io.StringIO`) or the result from :meth:`str.splitlines`. *pattern_factory* can be :data:`None`, the name of a registered pattern factory (:class:`str`), or a :class:`~collections.abc.Callable` used to compile patterns. The callable must accept an uncompiled pattern (:class:`str`) and return the compiled pattern (:class:`pathspec.pattern.Pattern`). Default is :data:`None` for :class:`.GitWildMatchPattern`). Returns the :class:`GitIgnoreSpec` instance. """ if pattern_factory is None: pattern_factory = GitWildMatchPattern
elif (isinstance(lines, (str, bytes)) or callable(lines)) and _is_iterable(pattern_factory):
4
2023-12-14 07:43:03+00:00
12k
pan-x-c/EE-LLM
tests/unit_tests/transformer/test_spec_customization.py
[ { "identifier": "get_bias_dropout_add", "path": "megatron/core/fusions/fused_bias_dropout.py", "snippet": "def get_bias_dropout_add(training, fused):\n if fused:\n # jit scripting for a nn.module (with dropout) is not\n # triggering the fusion kernel. For now, we use two\n # diff...
from dataclasses import dataclass, fields from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add from megatron.core.tensor_parallel.random import model_parallel_cuda_manual_seed from megatron.core.transformer.attention import SelfAttention, SelfAttentionSubmodules from megatron.core.transformer.custom_layers.transformer_engine import ( TEDotProductAttention, TELayerNormColumnParallelLinear, TENorm, TERowParallelLinear, ) from megatron.core.transformer.enums import AttnMaskType from megatron.core.transformer.identity_op import IdentityFuncOp, IdentityOp from megatron.core.transformer.spec_utils import ModuleSpec, build_module, import_module from megatron.core.transformer.transformer_config import TransformerConfig from megatron.core.transformer.transformer_layer import TransformerLayerSubmodules from tests.unit_tests.test_utilities import Utils import pytest import torch import transformer_engine as te
8,079
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. class TestSpecCustomization: def setup_method(self, method): Utils.initialize_model_parallel(1, 1) model_parallel_cuda_manual_seed(123) self.config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True ) # specify Transformer Layer spec with all identity ops self.transformer_layer_spec = TransformerLayerSubmodules() # specify attention spec using already imported class self.attention_spec = ModuleSpec( module=SelfAttention, params={"attn_mask_type": AttnMaskType.causal}, submodules=SelfAttentionSubmodules( linear_qkv=TELayerNormColumnParallelLinear, dot_product_attention=TEDotProductAttention, linear_proj=TERowParallelLinear ), ) # specify layernorm spec with module path to test dynamic importing self.layernorm_spec = ModuleSpec( module=("megatron.core.transformer.custom_layers.transformer_engine", "TENorm"), ) # specify bias dropout add with module path self.bda_spec = ModuleSpec( module=("megatron.core.fusions.fused_bias_dropout", "get_bias_dropout_add") ) def teardown_method(self, method): Utils.destroy_model_parallel() def test_import_module(self): self_attention_cls = import_module( module_path=('megatron.core.transformer.attention', 'SelfAttention') ) assert id(self_attention_cls) == id(SelfAttention) layernorm_cls = import_module(module_path=self.layernorm_spec.module) assert id(layernorm_cls) == id(TENorm) def test_build_module(self): # Check NoOp TransformerLayer random_input = 12 noop_transformer_layer = [ build_module(getattr(self.transformer_layer_spec, field.name)) for field in fields(self.transformer_layer_spec) ] x = random_input for mod in noop_transformer_layer: # checking for `IdentityFuncOp` before `IdentityOp` because former # is derived from the latter and so the second if statement will # always be `True`. if isinstance(mod, IdentityFuncOp): x = mod()(x)
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. class TestSpecCustomization: def setup_method(self, method): Utils.initialize_model_parallel(1, 1) model_parallel_cuda_manual_seed(123) self.config = TransformerConfig( num_layers=2, hidden_size=12, num_attention_heads=4, use_cpu_initialization=True ) # specify Transformer Layer spec with all identity ops self.transformer_layer_spec = TransformerLayerSubmodules() # specify attention spec using already imported class self.attention_spec = ModuleSpec( module=SelfAttention, params={"attn_mask_type": AttnMaskType.causal}, submodules=SelfAttentionSubmodules( linear_qkv=TELayerNormColumnParallelLinear, dot_product_attention=TEDotProductAttention, linear_proj=TERowParallelLinear ), ) # specify layernorm spec with module path to test dynamic importing self.layernorm_spec = ModuleSpec( module=("megatron.core.transformer.custom_layers.transformer_engine", "TENorm"), ) # specify bias dropout add with module path self.bda_spec = ModuleSpec( module=("megatron.core.fusions.fused_bias_dropout", "get_bias_dropout_add") ) def teardown_method(self, method): Utils.destroy_model_parallel() def test_import_module(self): self_attention_cls = import_module( module_path=('megatron.core.transformer.attention', 'SelfAttention') ) assert id(self_attention_cls) == id(SelfAttention) layernorm_cls = import_module(module_path=self.layernorm_spec.module) assert id(layernorm_cls) == id(TENorm) def test_build_module(self): # Check NoOp TransformerLayer random_input = 12 noop_transformer_layer = [ build_module(getattr(self.transformer_layer_spec, field.name)) for field in fields(self.transformer_layer_spec) ] x = random_input for mod in noop_transformer_layer: # checking for `IdentityFuncOp` before `IdentityOp` because former # is derived from the latter and so the second if statement will # always be `True`. if isinstance(mod, IdentityFuncOp): x = mod()(x)
elif isinstance(mod, IdentityOp):
10
2023-12-07 08:29:38+00:00
12k
mitrefireline/simharness
simharness2/environments/reactive_marl.py
[ { "identifier": "ReactiveHarnessAnalytics", "path": "simharness2/analytics/harness_analytics.py", "snippet": "class ReactiveHarnessAnalytics(RLHarnessAnalytics):\n \"\"\"TODO Add description.\"\"\"\n\n def __init__(\n self,\n *,\n sim: FireSimulation,\n sim_analytics_pa...
import logging import os import math import copy import numpy as np from collections import OrderedDict as ordered_dict from functools import partial from typing import Any, Dict, List, Optional, OrderedDict, Tuple from gymnasium import spaces from gymnasium.envs.registration import EnvSpec from ray.rllib.env.env_context import EnvContext from simfire.enums import BurnStatus from simfire.utils.config import Config from simharness2.analytics.harness_analytics import ReactiveHarnessAnalytics from simharness2.environments.rl_harness import RLHarness from simharness2.rewards.base_reward import BaseReward from simharness2.agents import ReactiveAgent
10,603
# Generate random agent locations for the start of the episode. elif method == "random": # Create a boolean mask of valid positions (i.e., inside the boundaries). mask = np.ones(self.sim.fire_map.shape, dtype=bool) # Agent (s) can only be spawned on an unburning square # NOTE: Any other "prohibited" agent start locations can be specified here. mask[np.where(self.sim.fire_map != BurnStatus.UNBURNED)] = False # Randomly select unique positions from the valid ones. idx = np.random.choice(range(mask.sum()), size=self.num_agents, replace=False) flat_idx = np.argwhere(mask.flatten())[idx].flatten() agent_locs = np.vstack(np.unravel_index(flat_idx, mask.shape)).T # Populate the `self.agents` dict with `ReactiveAgent` object (s). agent_ids = sorted(self._agent_ids, key=lambda x: int(x.split("_")[-1])) sim_ids = self._sim_agent_ids for agent_str, sim_id, loc in zip(agent_ids, sim_ids, agent_locs): agent = ReactiveAgent(agent_str, sim_id, tuple(loc)) self.agents[agent_str] = agent # This should be caught within the init. To be safe, also raise error here. else: raise NotImplementedError(f"Agent spawn method {method} not implemented.") def _configure_env_rendering(self, should_render: bool) -> None: """Configure the environment's `FireSimulation` to be rendered (or not). If the simulation should be rendered, then the `headless` parameter in the simulation's config (file) should be set to `False`, enabling the usage of pygame. Additionally, the environment's `_should_render` attribute is set to ensure that rendering is active when desired. This is especially important when the number of eval episodes, specified via `evaluation.evaluation_duration`, is >1. """ sim_data = self.sim.config.yaml_data sim_data["simulation"]["headless"] = not should_render # Update simulation's config attribute. logger.info("Updating the `self.sim.config` with new `Config` object...") self.sim.config = Config(config_dict=sim_data) # Reset the simulation to ensure that the new config is used. logger.info(f"Resetting `self.sim` to configure rendering == {should_render}.") self.sim.reset() # Update the simulation's rendering attribute to match the provided value. if should_render: logger.info("Setting SDL_VIDEODRIVER environment variable to 'dummy'...") os.environ["SDL_VIDEODRIVER"] = "dummy" self.sim.rendering = should_render # Indicate whether the environment's `FireSimulation` should be rendered. self._should_render = should_render def _increment_evaluation_iterations(self) -> None: """Increment the number of evaluation iterations that have been run.""" self._num_eval_iters += 1 # def _set_agent_pos_for_episode_start(self): # """Set the agent's initial position in the map for the start of the episode.""" # for agent_id in self._agent_ids: # valid_pos = False # # Keep looping until we get a valid position # while not valid_pos: # random_pos = self.np_random.integers( # 0, self.sim.config.area.screen_size, size=2, dtype=int # ) # valid_pos = self._check_start_pos(random_pos) # self.agent_pos[agent_id] = random_pos def _log_env_init(self): """Log information about the environment that is being initialized.""" if self._is_eval_env: i, j = self.worker_idx, self.vector_idx logger.warning(f"Object {hex(id(self))}: index (i+1)*(j+1) == {(i+1)*(j+1)}") if not self._debug_mode: return # TODO: What log level should we use here? logger.info(f"Object {hex(id(self))}: worker_index: {self.worker_idx}") logger.info(f"Object {hex(id(self))}: vector_index: {self.vector_idx}") logger.info(f"Object {hex(id(self))}: num_workers: {self.num_workers}") logger.info(f"Object {hex(id(self))}: is_remote: {self.is_remote}") def _log_env_reset(self): """Log information about the environment that is being reset.""" if not self._debug_mode or self._episodes_debugged > self._debug_duration: return # TODO: What log level should we use here? for idx, feat in enumerate(self.attributes): low, high = self._low[..., idx].min(), self._high[..., idx].max() obs_min = round(self.state[..., idx].min(), 2) obs_max = round(self.state[..., idx].max(), 2) # Log lower bound of the (obs space) and max returned obs for each attribute. logger.info(f"{feat} LB: {low}, obs min: {obs_min}") # Log upper (lower) bounds of the returned observations for each attribute. logger.info(f"{feat} UB: {high}, obs max: {obs_max}") # Increment the number of episodes that have been debugged. self._episodes_debugged += 1 def _setup_harness_analytics(self, analytics_partial: partial) -> None: """Instantiates the `harness_analytics` used to monitor this `ReactiveHarness` obj. Arguments: analytics_partial: A `functools.partial` object that indicates the top-level class that will be used to monitor the `ReactiveHarness` object. The user is expected to provide the `sim_data_partial` keyword argument, along with a valid value. Raises: TypeError: If `harness_analytics_partial.keywords` does not contain a `sim_data_partial` key with value of type `functools.partial`. """
"""ReactiveHarness with support for mutiple agents operating simulanteously. This file contains the environment file for `MARLReactiveHarness` which is an environment with multiple agents operating at the same time within the same environment. The code is very similar to the single agent case, just multiplied for each agents action. Agents can be monogomous or heterogenous depending on the training run - meaning agents can have the same speed/abilities or different. The reward function used is configurable depending on the fire manager intent displayed within the training config and corresponding reward class. """ # FIXME: Update logger configuration. logger = logging.getLogger(__name__) handler = logging.StreamHandler() handler.setFormatter( logging.Formatter("%(asctime)s\t%(levelname)s %(filename)s:%(lineno)s -- %(message)s") ) logger.addHandler(handler) logger.propagate = False class MARLReactiveHarness(RLHarness): # noqa: D205,D212,D415 """ ### Description Environment which potrays the case where a fire has already started and we are deploying our resources to best mitigate the damage. Multiple agents are interacting at once with the environment in a collaborative manner. ### Action Space The action space type is `MultiDiscrete`, and `sample()` returns an `np.ndarray` of shape `(M+1,I+1)`, where `M == movements` and `I == interactions`. - Movements refer to actions where the agent **traverses** the environment. - For example, possible movements could be: ["up", "down", "left", "right"]. - Interactions refer to actions where the agent **interacts** with the environment. - For example, if the sim IS-A `FireSimulation`, possible interactions could be: ["fireline", "scratchline", "wetline"]. To learn more, see [simulation.py](https://gitlab.mitre.org/fireline/simulators/simfire/-/blob/main/simfire/sim/simulation.py#L269-280). - Actions are determined based on the provided (harness) config file. - When `super()._init__()` is called, the option "none" is inserted to element 0 of both `movements` and `interactions`, representing "don't move" and "don't interact", respectively (this is the intuition for the +1 in the shape). ### Observation Space The observation space type is `Box`, and `sample()` returns an `np.ndarray` of shape `(A,X,X)`, where `A == len(ReactiveHarness.attributes)` and `X == ReactiveHarness.sim.config.area.screen_size`. - The value of `ReactiveHarness.sim.config.area.screen_size` is determined based on the value of the `screen_size` attribute (within the `area` section) of the (simulation) config file. See `simharness2/sim_registry.py` to find more info about the `register_simulation()` method, which is used to register the simulation class and set the config file path associated with a given simulation. - The number of `attributes` is determined by the `attributes` attribute (within the `RLHARNESS` section) of the (harness) config file. Each attribute must be contained in the observation space returned for the respective `Simulation` class. The locations within the observation are based ontheir corresponding location within the array. ### Rewards The agent is rewarded for saving the most land and reducing the amount of affected area. - TODO(afennelly) add more details about the reward function. - TODO(afennelly) implement modular reward function configuration. ### Starting State The initial map is set by data given from the Simulation. - TODO(afennelly) add more details about the starting state. ### Episode Termination The episode ends once the disaster is finished and it cannot spread any more. - TODO(afennelly) add more details about the episode termination. """ def __init__(self, config: EnvContext) -> None: """See RLHarness (parent/base class).""" # NOTE: We don't set a default value in `config.get` for required arguments. # FIXME Most, if not all, of these can be moved into the RLHarness. # TODO Should we make an RLlibHarness class to handle all these extras? # Indicates that environment information should be logged at various points. self._set_debug_options(config) self._store_env_context(config) # FIXME: Perform env setup depending on if the env is used for eval/train. # Indicates whether the environment was created for evaluation purposes. self._is_eval_env = config.get("is_evaluation_env", False) if self._is_eval_env: self._prepare_eval_env(config) else: self._prepare_train_env(config) # Set the max number of steps that the environment can take before truncation # self.spec.max_episode_steps = 1000 self.spec = EnvSpec( id="MARLReactiveHarness-v0", entry_point="simharness2.environments.reactive_marl:MARLReactiveHarness", max_episode_steps=2000, ) # Track the number of timesteps that have occurred within an episode. self.timesteps: int = 0 action_space_partial: partial = config.get("action_space_partial") # Ensure the provided `action_space_partial` has a `func` attribute. if not isinstance(action_space_partial, partial): raise TypeError( f"Expected `action_space_partial` to be an instance of " f"`functools.partial`, but got {type(action_space_partial)}." ) super().__init__( sim=config.get("sim"), movements=config.get("movements"), interactions=config.get("interactions"), attributes=config.get("attributes"), normalized_attributes=config.get("normalized_attributes"), action_space_cls=action_space_partial.func, deterministic=config.get("deterministic"), benchmark_sim=config.get("benchmark_sim"), num_agents=config.get("num_agents", 1), ) self._log_env_init() # Spawn the agent (s) that will interact with the simulation logger.debug(f"Creating {self.num_agents} agent (s)...") agent_init_method = config.get("agent_initialization_method", "automatic") if agent_init_method == "manual": agent_init_positions = config.get("initial_agent_positions", None) if agent_init_positions is None: raise ValueError( "Must provide 'initial_agent_positions' when using 'manual' agent initialization method." ) self._create_agents(method="manual", pos_list=agent_init_positions) elif agent_init_method == "automatic": self._create_agents(method="random") else: raise ValueError( "Invalid agent initialization method. Must be either 'automatic' or 'manual'." ) # NOTE: only used in `_do_one_simulation_step`, so keep as harness attr self.agent_speed: int = config.get("agent_speed") # If provided, construct the class used to monitor this `ReactiveHarness` object. # FIXME Move into RLHarness analytics_partial = config.get("harness_analytics_partial") self._setup_harness_analytics(analytics_partial) # If provided, construct the class used to perform reward calculation. self._setup_reward_cls(reward_cls_partial=config.get("reward_cls_partial")) # If the agent(s) places an effective mitigation (not placed in already damaged/mitigated square), this is set to True. # FIXME Have this tracked across all of the agents self.true_mitigation_placed: bool = False # Bool to toggle the ability to terminate the agent simulation early if at the current timestep of the agent simulation # , the agents have caused more burn damage (burned + burning) than the final state of the benchmark fire map # FIXME Have this value set in the configs self._terminate_if_greater_damage = True if self.benchmark_sim: #Validate that benchmark and sim match seeds assert self.sim.get_seeds() == self.benchmark_sim.get_seeds() #create static list to store the episode benchsim firemaps self.max_bench_length = 600 self.bench_firemaps = [0] * self.max_bench_lenght #run the first benchmark sim to generate the benchmark sim firemaps and metrics for this episode self._run_benchmark() def _set_debug_options(self, config: EnvContext): """Set the debug options for the environment.""" self._debug_mode = config.get("debug_mode", False) self._debug_duration = config.get("debug_duration", 1) # unit == episodes self._episodes_debugged = 0 logger.debug(f"Initializing environment {hex(id(self))}") def _store_env_context(self, config: EnvContext): """Store the environment context for later use.""" # When there are multiple workers created, this uniquely identifies the worker # the env is created in. 0 for local worker, >0 for remote workers. self.worker_idx = config.worker_index # When there are multiple envs per worker, this uniquely identifies the env index # within the worker. Starts from 0. self.vector_idx = config.vector_index # Whether individual sub-envs (in a vectorized env) are @ray.remote actors. self.is_remote = config.remote # Total number of (remote) workers in the set. 0 if only a local worker exists. self.num_workers = config.num_workers def _prepare_eval_env(self, config: EnvContext): """Prepare the environment for evaluation purposes.""" eval_duration = config.get("evaluation_duration") if self.num_workers != 0: if eval_duration and not (eval_duration / self.num_workers).is_integer(): raise ValueError( f"The `evaluation_duration` ({eval_duration}) must be evenly " f"divisible by the `num_workers` ({self.num_workers}.)" ) # Indicates how many rounds of evaluation will be run using this environment. self._total_eval_rounds = ( eval_duration / self.num_workers if eval_duration else 0 ) else: # Eval will be run in the algorithm process, so no need to divide. self._total_eval_rounds = eval_duration if eval_duration else 0 self._current_eval_round = 1 # Incremented on each call to `RenderEnv.on_evaluate_start()` callback, via the # `_increment_evaluation_iterations()` helper method. self._num_eval_iters = 0 self.fire_scenarios = config.get("scenarios", None) def _prepare_train_env(self, config: EnvContext): """Prepare the environment for training purposes.""" # TODO Add any training-specific logic here pass def set_trial_results_path(self, path: str) -> None: """Set the path to the directory where (tune) trial results will be stored.""" self._trial_results_path = path def step( self, action_dict: Dict[Any, np.ndarray] ) -> Tuple[ Dict[Any, np.ndarray], Dict[Any, float], Dict[Any, bool], Dict[Any, bool], Dict[Any, Dict[Any, Any]], ]: # noqa FIXME # TODO: Refactor to better utilize `RLHarness` ABC, or update the API. # TODO: Can we parallelize this method? If so, how? I'm not sure if that # will make sense wrt updating the sim, etc.? for agent_id, agent in self.agents.items(): self._do_one_agent_step(agent, action_dict[agent_id]) if self.harness_analytics: self.harness_analytics.update_after_one_agent_step( timestep=self.timesteps, agents=self.agents, true_mitigation_placed = self.true_mitigation_placed ) # NOTE: `sim_run` indicates if `FireSimulation.run()` was called. This helps # indicate how to calculate the reward for the current timestep. sim_run = self._do_one_simulation_step() # alternatively, self._step_simulation() if sim_run and self.harness_analytics: self.harness_analytics.update_after_one_simulation_step( timestep=self.timesteps ) # TODO(afennelly): Need to handle truncation properly. For now, we assume that # the episode will never be truncated, but this isn't necessarily true. truncated = False # The simulation has not yet been run via `run()` if self.sim.elapsed_steps == 0: terminated = False else: terminated = not self.sim.active # Calculate the reward for the current timestep # TODO pass `terminated` into `get_reward` method # FIXME: Update reward for MARL case!! # TODO: Give each agent the "same" simple reward for now. reward = self.reward_cls.get_reward(self.timesteps, sim_run) # Terminate episode early if burn damage in Agent Sim is larger than final bench fire map if self.benchmark_sim: if self._terminate_if_greater_damage: total_area = self.harness_analytics.sim_analytics.sim.config.area.screen_size[0] ** 2 sim_damaged_total = self.harness_analytics.sim_analytics.data.burned + self.harness_analytics.sim_analytics.data.burning benchsim_damaged_total = total_area - self.harness_analytics.benchmark_sim_analytics.data.unburned if sim_damaged_total > benchsim_damaged_total: terminated = True # TODO potentially add a static negative penalty for making the fire worse # TODO account for below updates in the reward_cls.calculate_reward() method # "End of episode" reward #if terminated: #reward += 10 if self.harness_analytics: self.harness_analytics.update_after_one_harness_step( sim_run, terminated, reward, timestep=self.timesteps ) new_obs, rewards, truncateds, terminateds, infos = {}, {}, {}, {}, {} truncs = set() terms = set() for agent_id, agent in self.agents.items(): new_obs[agent_id] = self.state rewards[agent_id] = reward # FIXME !! truncateds[agent_id] = truncated terminateds[agent_id] = terminated infos[agent_id] = {} if truncated: truncs.add(agent_id) if terminated: terms.add(agent_id) terminateds["__all__"] = len(truncs) == self.num_agents truncateds["__all__"] = len(terms) == self.num_agents self.timesteps += 1 # increment AFTER method logic is performed (convention). return new_obs, rewards, terminateds, truncateds, infos # NOTE: if passing `agent` doesn't persist updates, pass `agent_id` instead. def _do_one_agent_step(self, agent: ReactiveAgent, action: np.ndarray) -> None: """Move the agent and interact with the environment. FIXME: Below details need to be changed to reflect API updates!! Within this method, the movement and interaction that the agent takes are stored in `self.latest_movements` and `self.latest_interactions`, respectively. If this movement is not "none", then the agent's position on the map is updated and stored in `self.agent_pos`. Given some arbitrary method that defines whether a space in the simulation is empty or not (see `_agent_pos_is_empty_space()`), the value of `self.agent_pos_is_empty_space` is updated accordingly. If the space occupied by the agent (`self.agent_pos`) is *empty* and the interaction is not "none", then the agent will place a mitigation on the map and `self.mitigation_placed` is set to True. Otherwise, `self.mitigation_placed` is set to False. Data that we want to store after each AGENT step: - interaction (via `_parse_action`) - connected_mitigation (via `_update_mitigation`) - movement (via `_parse_action`) - moved_off_map (via `_update_agent_position`) - near_fire (calculated within `AgentAnalytics.update`) - burn_status (calculated within `AgentAnalytics.update`) Additional data needed ONLY when storing all episode data: - agent_pos (via `_update_agent_position`) - timestep (via `self.timesteps`) It seems like an efficient way to store the timestep data would be with a namedtuple. I'm looking into more details now. Args: agent_id_num (int): _description_ action (np.ndarray): _description_ Returns: _type_: _description_ """ # Parse the movement and interaction from the action, and store them. agent.latest_movement, agent.latest_interaction = self._parse_action(action) interact = self.interactions[agent.latest_interaction] != "none" # Ensure that mitigations are only placed on squares with `UNBURNED` status if self._agent_pos_is_unburned(agent) and interact: # NOTE: `self.mitigation_placed` is updated in `_update_mitigation()`. self._update_mitigation(agent) elif (not self._agent_pos_is_unburned()) and interact: #set true_mitigation_placed to False if agent has placed mitigation in damaged/mitigated square #FIXME: do for each agent self.true_mitigation_placed = False else: # Overwrite value from previous timestep. agent.mitigation_placed = False # Update agent location on map if self.movements[agent.latest_movement] != "none": # NOTE: `agent.current_position` is updated in `_update_agent_position()`. self._update_agent_position(agent) def _parse_action(self, action: np.ndarray) -> Tuple[int, int]: """Parse the action into movement and interaction.""" # NOTE: Assuming that all agents are homogeneous if isinstance(self.action_space, spaces.Dict): unique_spaces = set([type(v) for v in self.action_space.values()]) if len(unique_spaces) != 1: raise ValueError("Only homogeneous agents are currently supported.") act_space = unique_spaces.pop() # Handle the MultiDiscrete case if issubclass(act_space, spaces.MultiDiscrete): return action[0], action[1] # Handle the Discrete case elif issubclass(act_space, spaces.Discrete): return action % len(self.movements), int(action / len(self.movements)) else: raise NotImplementedError(f"{self.action_space} is not supported.") # FIXME: Decide what to do with the SARL action parsing; keep for now. # Handle the MultiDiscrete case elif isinstance(self.action_space, spaces.MultiDiscrete): return action[0], action[1] # Handle the Discrete case elif isinstance(self.action_space, spaces.Discrete): return action % len(self.movements), int(action / len(self.movements)) else: raise NotImplementedError(f"{self.action_space} is not supported.") def _update_agent_position(self, agent: ReactiveAgent) -> None: """Update the agent's position on the map by performing the provided movement.""" # Store agent's current position in a temporary variable to avoid overwriting it. map_boundary = self.sim.fire_map.shape[0] - 1 # Update the agent's position based on the provided movement. movement_str = self.movements[agent.latest_movement] # First, check that the movement string is valid. if movement_str not in ["up", "down", "left", "right"]: raise ValueError(f"Invalid movement string provided: {movement_str}.") # Then, ensure that the agent will not move off the map. elif movement_str == "up" and not agent.row == 0: agent.row -= 1 elif movement_str == "down" and not agent.row == map_boundary: agent.row += 1 elif movement_str == "left" and not agent.col == 0: agent.col -= 1 elif movement_str == "right" and not agent.col == map_boundary: agent.col += 1 # Movement invalid from current pos, so the agent movement will be ignored. # Depending on `self.reward_cls`, the agent may receive a small penalty. else: # Inform caller that the agent cannot move in the provided direction. logger.debug(f"Agent `sim_id`={agent.sim_id}") logger.debug( f"Agent can't move {movement_str} from row={agent.row}, col={agent.col}." ) logger.debug("Setting `agent.moved_off_map = True` for agent...") agent.moved_off_map = True # Update the Simulation with new agent position (s). point = [agent.col, agent.row, agent.sim_id] self.sim.update_agent_positions([point]) def _agent_pos_is_unburned(self, agent: ReactiveAgent) -> bool: """Returns true if the space occupied by the agent has `BurnStatus.UNBURNED`.""" return self.sim.fire_map[agent.row, agent.col] == BurnStatus.UNBURNED def _update_mitigation(self, agent: ReactiveAgent) -> None: """Interact with the environment by performing the provided interaction.""" sim_interaction = self.harness_to_sim[agent.latest_interaction] mitigation_update = (agent.col, agent.row, sim_interaction) self.sim.update_mitigation([mitigation_update]) agent.mitigation_placed = True # Store indicator that a true mitigation was placed, which will be set back to False in self._do_one_agent_step if agent was in an already damaged/mitigated square self.true_mitigation_placed = False def _do_one_simulation_step(self) -> bool: """Check if the simulation should be run, and then run it if necessary.""" run_sim = self.timesteps % self.agent_speed == 0 # The simulation WILL NOT be run every step, unless `self.agent_speed` == 1. if run_sim: self._run_simulation() # Prepare the observation that is returned in the `self.step()` method. self._update_state() return run_sim def _run_simulation(self): """Run the simulation (s) for one timestep.""" self.sim.run(1) def _run_benchmark(self): """Runs the entire benchmark sim and stores the data needed for the rewards and bench fire maps within each episode""" #use timesteps_copy to track the matching timestep that each benchsim fire map will match with the sim fire map timesteps_copy = 0 #if the benchmark simulation has not been updated yet if self.benchmark_sim.elapsed_steps == 0: self.benchmark_sim.run(1) #update the benchsim metrics at this timesteps_copy in the harness analytics if self.harness_analytics: self.harness_analytics.update_bench_after_one_simulation_step( timestep=timesteps_copy ) #update timesteps_copy to next time the simulation with the agent will update timesteps_copy = timesteps_copy + self.agent_speed #store the bench fire map at the sim step self.bench_firemaps[(self.harness_analytics.benchmark_sim_analytics.num_sim_steps) - 1] = np.copy(self.benchmark_sim.fire_map) #continue to run the benchmark simulation and update the benchsim data/metrics after each sim step while self.benchmark_sim.active == True: self.benchmark_sim.run(1) #update the benchsim metrics at this timesteps_copy in the harness analytics if self.harness_analytics: self.harness_analytics.update_bench_after_one_simulation_step( timestep=timesteps_copy ) #update timesteps_copy to next time the simulation with the agent will update timesteps_copy = timesteps_copy + self.agent_speed #update the size of self.bench_firemaps if this benchmark simulation has lasted longer than any previous benchmark simulations if ((self.harness_analytics.benchmark_sim_analytics.num_sim_steps) - 1) > (self.max_bench_length - 1): #append the bench fire map to the self.bench_firemaps self.bench_firemaps.append(np.copy(self.benchmark_sim.fire_map)) #update the max length of the benchsim when defining future lists for self.bench_firemaps self.max_bench_length = self.max_bench_length + 1 #else store the bench fire map at the sim step else: self.bench_firemaps[(self.harness_analytics.benchmark_sim_analytics.num_sim_steps) - 1] = np.copy(self.benchmark_sim.fire_map) def _update_state(self): """Modify environment's state to contain updates from the current timestep.""" # Copy the fire map from the simulation so we don't overwrite it. fire_map = np.copy(self.sim.fire_map) # Update the fire map with the numeric identifier for the agent. for agent in self.agents.values(): fire_map[agent.row, agent.col] = agent.sim_id # Modify the state to contain the updated fire map self.state[..., self.attributes.index("fire_map")] = fire_map #Modify the state to contain the bench fire map at that sim step if "bench_fire_map" in self.attributes: bench_fire_map_idx = self.attributes.index("bench_fire_map") #if the simulation has lasted longer that the benchmark sim, use the final state of the benchsim fire map if (self.harness_analytics.benchmark_sim_analytics.num_sim_steps < self.harness_analytics.sim_analytics.num_sim_steps): self.state[..., (bench_fire_map_idx)] = self.bench_firemaps[(self.harness_analytics.benchmark_sim_analytics.num_sim_steps) - 1] #else get the benchmark sim fire map from the same sim step as the simulation fire map else: self.state[..., (bench_fire_map_idx)] = self.bench_firemaps[(self.harness_analytics.sim_analytics.num_sim_steps) - 1] #Modify the state to contain the final state of bench fire map if "bench_fire_map_final" in self.attributes: bench_fire_map_final_idx = self.attributes.index("bench_fire_map_final") self.state[..., (bench_fire_map_final_idx)] = self.bench_firemaps[(self.harness_analytics.benchmark_sim_analytics.num_sim_steps) - 1] def reset( self, *, seed: Optional[int] = None, options: Optional[Dict[Any, Any]] = None, ) -> Tuple[Dict[Any, np.ndarray], Dict[Any, Dict[Any, Any]]]: # log.info("Resetting environment") # Use the following line to seed `self.np_random` super().reset(seed=seed) # Reset the `Simulation` to initial conditions. In particular, this resets the # `fire_map`, `terrain`, `fire_manager`, and all mitigations. logger.debug("Resetting `self.sim`...") self.sim.reset() bench_exists = False if self.benchmark_sim: logger.debug("Resetting `self.benchmark_sim`...") # set the benchmark seeds to match the sim seeds self.benchmark_sim.set_seeds(seed_dict) # reset benchmark simulation self.benchmark_sim.reset() bench_exists = True # Reset the agent's contained within the `FireSimulation`. logger.debug("Resetting `self.agents`...") for agent_id, agent in self.agents.items(): self.agents[agent_id].reset() # Reset `ReactiveHarnessAnalytics` to initial conditions, if it exists. if self.harness_analytics: logger.debug("Resetting `self.harness_analytics`...") self.harness_analytics.reset(benchmark_exists=bench_exists) # Get the initial state of the `FireSimulation`, after it has been reset (above). sim_observations = super()._select_from_dict( self.sim.get_attribute_data(), self.sim_attributes ) nonsim_observations = super()._select_from_dict( self.get_nonsim_attribute_data(), self.nonsim_attributes ) if len(nonsim_observations) != len(self.nonsim_attributes): raise AssertionError( f"Data for {len(nonsim_observations)} nonsim attributes were given but " f"there are {len(self.nonsim_attributes)} nonsim attributes." ) logger.debug(f"Normalizing obs for attributes: {self.normalized_attributes}") observations = super()._normalize_obs({**sim_observations, **nonsim_observations}) obs = [observations[attribute] for attribute in self.attributes] self.state = np.stack(obs, axis=-1).astype(np.float32) # Update the `FireSimulation` with the (new) initial agent positions. # NOTE: This is slightly redundant, since we can build the list of points within # `_create_fire_map()`. For now, it's okay to iterate over `self.agents` twice. points = [] for agent in self.agents.values(): points.append([agent.col, agent.row, agent.sim_id]) logger.debug(f"Updating `self.sim` with (new) initial agent positions...") self.sim.update_agent_positions(points) self.timesteps = 0 self._log_env_reset() # FIXME: Will need to update creation of `marl_obs`` to handle POMDP. marl_obs = {ag_id: self.state for ag_id in self._agent_ids} infos = {ag_id: {} for ag_id in self._agent_ids} # If the agent(s) places an effective mitigation (not placed in already damaged/mitigated square), this is set to True. # FIXME Have this tracked across all of the agents self.true_mitigation_placed: bool = False #Run the new benchsim to obtain the benchsim data used to generate the rewards and policy if self.benchmark_sim: #run benchmark sim to generate the benchmark sim firemaps and metrics for this episode self._run_benchmark() return marl_obs, infos def get_nonsim_attribute_bounds(self) -> OrderedDict[str, Dict[str, int]]: # noqa nonsim_min_maxes = ordered_dict() # The values in "fire_map" are: # - 0: BurnStatus.UNBURNED # - 1: BurnStatus.BURNING # - 2: BurnStatus.BURNED # - 3: BurnStatus.FIRELINE (if "fireline" in self.interactions) # - 4: BurnStatus.SCRATCHLINE (if "scratchline" in self.interactions) # - 5: BurnStatus.WETLINE (if "wetline" in self.interactions) # - X: self._min_sim_agent_id + self.num_agents (value is set in RLHarness.__init__) nonsim_min_maxes["fire_map"] = { "min": 0, "max": max(self._sim_agent_ids), } nonsim_min_maxes["bench_fire_map"] = { "min": 0, "max": max(self._sim_agent_ids), } nonsim_min_maxes["bench_fire_map_final"] = { "min": 0, "max": max(self._sim_agent_ids), } return nonsim_min_maxes def get_nonsim_attribute_data(self) -> OrderedDict[str, np.ndarray]: # noqa nonsim_data = ordered_dict() nonsim_data["fire_map"] = self._create_fire_map() nonsim_data["bench_fire_map"] = np.zeros( ( self.sim.config.area.screen_size[0], self.sim.config.area.screen_size[0], ) ) nonsim_data["bench_fire_map_final"] = np.zeros( ( self.sim.config.area.screen_size[0], self.sim.config.area.screen_size[0], ) ) return nonsim_data def render(self): # noqa self.sim.rendering = True # TODO: Finish code to allow manually specifying agent positions. # def _check_start_pos(self, start_pos: Tuple[int, int]) -> bool: # # Check that value is in the correct range # if ( # start_pos[0] < 0 # or start_pos[0] >= self.sim.config.area.screen_size[0] # or start_pos[1] < 0 # or start_pos[1] >= self.sim.config.area.screen_size[0] # ): # return False # for pos in self.agent_pos: # if np.array_equal(pos, start_pos): # return False # return True # def _validate_position(self, x, y): # """Check whether (x,y) is within the bounds of the environment.""" # return all([x >= 0, x < self.width, y >= 0, y < self.height]) # def _check_collision(self, pos1, pos2): # """Check whether two positions overlap.""" # return pos1[0] == pos2[0] and pos1[1] == pos2[1] # def _create_agents(self, method='random', pos_list=None): # """Spawn agents according to the given method and position list.""" # # Initialize empty lists for holding agent objects and positions # self.agents = [] # self.agent_positions = {} # if method == 'manual': # # Validate and assign positions from the input list # assert len(pos_list) == len(self.agent_ids), \ # f"Number of positions ({len(pos_list)}) does not match number of agents ({len(self.agent_ids)})." # for i, pos in enumerate(pos_list): # assert len(pos) == 3, f"Position {i} has invalid length ({len(pos)}, expected 3)" # agent_id, x, y = pos # assert agent_id in self.agent_ids, f"Agent ID '{agent_id}' is not recognized." # assert self._validate_position(x, y), f"Position {pos} is out of bounds." # for j in range(i+1, len(pos_list)): # assert not self._check_collision(pos, pos_list[j]), f"Position collision detected between {pos} and {pos_list[j]}." # self.agents.append(ReactiveAgent(agent_id)) # self.agent_positions[agent_id] = (x, y) # if method == "manual": # if len(pos_list) < self.num_agents: # # Pad with default positions # num_missing = self.num_agents - len(pos_list) # logger.warning( # "%d manual agent position(s) provided; padding with %d defaults.", # len(pos_list), # num_missing, # ) # pos_list += [(f"default{i}", 0, 0) for i in range(num_missing)] # elif len(pos_list) > self.num_agents: # # Truncate the list # num_extra = len(pos_list) - self.num_agents # logger.warning( # "%d manual agent position(s) provided; ignoring %d extra.", # len(pos_list), # num_extra, # ) # pos_list = pos_list[: self.num_agents] def _create_fire_map(self) -> np.ndarray: """Prepare the inital copy of `self.sim.fire_map`. Creates an ndarray of entirely `BurnStatus.UNBURNED`, except for: - The initial fire postion, which is set to `BurnStatus.BURNING`. - Each respective agent position is set to the agent's `sim_id`. """ fire_map = np.full(self.sim.fire_map.shape, BurnStatus.UNBURNED) # TODO: Potential place to update the initial fire pos to a new value? x, y = self.sim.config.fire.fire_initial_position logger.debug(f"Placing initial fire position at row={y}, col={x}.") fire_map[y, x] = BurnStatus.BURNING # array should be indexed via (row, col) for agent in self.agents.values(): # Enforce resetting `self.agents` before calling `_create_fire_map()`. if agent.initial_position != agent.current_position: msg = f"The init and curr pos for agent {agent.agent_id} are different!" raise RuntimeError(msg) logger.debug(f"Placing {agent.sim_id} at row={agent.row}, col={agent.col}.") fire_map[agent.row, agent.col] = agent.sim_id return fire_map def _create_agents(self, method: str = "random", pos_list: List = None): """Create the `ReactiveAgent` objects that will interact with the `FireSimulation`. This method will create and populate the `agents` attribute. Arguments: method: TODO pos_list: TODO """ self.agents: Dict[str, ReactiveAgent] = {} # Use the user-provided agent positions to initialize the agents on the map. if method == "manual": # NOTE: The provided pos_list must be the same length as the number of agents # TODO: Allow option to randomly generate any "missing" agent positions. if len(pos_list) != self.num_agents: raise ValueError( f"Expected {self.num_agents} agent positions; got {len(pos_list)}." ) # FIXME: We assume provided pos are valid wrt map dims and agent collisions. # FIXME: Finish logic HERE to create `self.agents` dict raise NotImplementedError # adding so I don't forget! # for agent_info, sim_id in zip(pos_list, sim_agent_ids): # agent_str, x, y = agent_info # agent = ReactiveAgent(agent_str, sim_id, (x, y)) # self.agents[agent_str] = agent # Generate random agent locations for the start of the episode. elif method == "random": # Create a boolean mask of valid positions (i.e., inside the boundaries). mask = np.ones(self.sim.fire_map.shape, dtype=bool) # Agent (s) can only be spawned on an unburning square # NOTE: Any other "prohibited" agent start locations can be specified here. mask[np.where(self.sim.fire_map != BurnStatus.UNBURNED)] = False # Randomly select unique positions from the valid ones. idx = np.random.choice(range(mask.sum()), size=self.num_agents, replace=False) flat_idx = np.argwhere(mask.flatten())[idx].flatten() agent_locs = np.vstack(np.unravel_index(flat_idx, mask.shape)).T # Populate the `self.agents` dict with `ReactiveAgent` object (s). agent_ids = sorted(self._agent_ids, key=lambda x: int(x.split("_")[-1])) sim_ids = self._sim_agent_ids for agent_str, sim_id, loc in zip(agent_ids, sim_ids, agent_locs): agent = ReactiveAgent(agent_str, sim_id, tuple(loc)) self.agents[agent_str] = agent # This should be caught within the init. To be safe, also raise error here. else: raise NotImplementedError(f"Agent spawn method {method} not implemented.") def _configure_env_rendering(self, should_render: bool) -> None: """Configure the environment's `FireSimulation` to be rendered (or not). If the simulation should be rendered, then the `headless` parameter in the simulation's config (file) should be set to `False`, enabling the usage of pygame. Additionally, the environment's `_should_render` attribute is set to ensure that rendering is active when desired. This is especially important when the number of eval episodes, specified via `evaluation.evaluation_duration`, is >1. """ sim_data = self.sim.config.yaml_data sim_data["simulation"]["headless"] = not should_render # Update simulation's config attribute. logger.info("Updating the `self.sim.config` with new `Config` object...") self.sim.config = Config(config_dict=sim_data) # Reset the simulation to ensure that the new config is used. logger.info(f"Resetting `self.sim` to configure rendering == {should_render}.") self.sim.reset() # Update the simulation's rendering attribute to match the provided value. if should_render: logger.info("Setting SDL_VIDEODRIVER environment variable to 'dummy'...") os.environ["SDL_VIDEODRIVER"] = "dummy" self.sim.rendering = should_render # Indicate whether the environment's `FireSimulation` should be rendered. self._should_render = should_render def _increment_evaluation_iterations(self) -> None: """Increment the number of evaluation iterations that have been run.""" self._num_eval_iters += 1 # def _set_agent_pos_for_episode_start(self): # """Set the agent's initial position in the map for the start of the episode.""" # for agent_id in self._agent_ids: # valid_pos = False # # Keep looping until we get a valid position # while not valid_pos: # random_pos = self.np_random.integers( # 0, self.sim.config.area.screen_size, size=2, dtype=int # ) # valid_pos = self._check_start_pos(random_pos) # self.agent_pos[agent_id] = random_pos def _log_env_init(self): """Log information about the environment that is being initialized.""" if self._is_eval_env: i, j = self.worker_idx, self.vector_idx logger.warning(f"Object {hex(id(self))}: index (i+1)*(j+1) == {(i+1)*(j+1)}") if not self._debug_mode: return # TODO: What log level should we use here? logger.info(f"Object {hex(id(self))}: worker_index: {self.worker_idx}") logger.info(f"Object {hex(id(self))}: vector_index: {self.vector_idx}") logger.info(f"Object {hex(id(self))}: num_workers: {self.num_workers}") logger.info(f"Object {hex(id(self))}: is_remote: {self.is_remote}") def _log_env_reset(self): """Log information about the environment that is being reset.""" if not self._debug_mode or self._episodes_debugged > self._debug_duration: return # TODO: What log level should we use here? for idx, feat in enumerate(self.attributes): low, high = self._low[..., idx].min(), self._high[..., idx].max() obs_min = round(self.state[..., idx].min(), 2) obs_max = round(self.state[..., idx].max(), 2) # Log lower bound of the (obs space) and max returned obs for each attribute. logger.info(f"{feat} LB: {low}, obs min: {obs_min}") # Log upper (lower) bounds of the returned observations for each attribute. logger.info(f"{feat} UB: {high}, obs max: {obs_max}") # Increment the number of episodes that have been debugged. self._episodes_debugged += 1 def _setup_harness_analytics(self, analytics_partial: partial) -> None: """Instantiates the `harness_analytics` used to monitor this `ReactiveHarness` obj. Arguments: analytics_partial: A `functools.partial` object that indicates the top-level class that will be used to monitor the `ReactiveHarness` object. The user is expected to provide the `sim_data_partial` keyword argument, along with a valid value. Raises: TypeError: If `harness_analytics_partial.keywords` does not contain a `sim_data_partial` key with value of type `functools.partial`. """
self.harness_analytics: ReactiveHarnessAnalytics
0
2023-12-08 19:13:31+00:00
12k
racinette/querky
querky/querky.py
[ { "identifier": "one_", "path": "querky/result_shape.py", "snippet": "def one_(typename: str | None, *, optional: bool = True) -> typing.Callable[[Query], ResultShape]:\n def late_binding(query: Query) -> One:\n return One(query, typename, optional=optional)\n return late_binding" }, { ...
import importlib import types import typing import inspect import os import logging from types import ModuleType from os import path from querky.result_shape import one_, all_, value_, status_, column_, One, All, ResultShape from querky.conn_param_config import ConnParamConfig, First from querky.annotation_generator import AnnotationGenerator from querky.type_constructor import TypeConstructor from querky.module_constructor import ModuleConstructor from querky.base_types import TypeMetaData from querky.query import Query from querky.contract import Contract
7,304
self.imports = imports or set() self.indent = indent self.annotation_generator = annotation_generator self.module_ctors: dict[types.ModuleType, ModuleConstructor] = dict() self.type_factory = type_factory if conn_param_config is None: conn_param_config = First(name='__conn', positional=True) self.conn_param_config = conn_param_config self.contract = contract self.subdir = subdir if self.subdir and not str.isidentifier(self.subdir): raise ValueError("subdir must be a valid python identifier") self.file_signature = "# ~ AUTOGENERATED BY QUERKY ~ #" def get_indent(self, i: int): return self.indent * i def create_query( self, fn: typing.Callable[[...], str], shape: typing.Callable[[Query], ResultShape], conn_param_config: ConnParamConfig | None, explicit_name: str | None, parent_query: typing.Optional[Query], kwargs: typing.Optional[typing.Dict[str, typing.Any]] ) -> Query: module = inspect.getmodule(fn) if module in self.module_ctors: module_ctor = self.module_ctors[module] else: filename = self.generate_filename(module) if not str.isidentifier(filename): raise ValueError(f"Generated a filename which is not a valid python identifier: {filename}") filedir = path.dirname(module.__file__) new_module_name = module.__name__.rsplit('.', maxsplit=1)[0] if self.subdir: filedir = path.join(filedir, self.subdir) new_module_name = f"{new_module_name}.{self.subdir}" fullpath = path.join(filedir, f'{filename}.py') new_module_name = f"{new_module_name}.{filename}" module_ctor = ModuleConstructor(self, module, fullpath, new_module_name, filedir) self.module_ctors[module] = module_ctor return self.query_class( fn, shape, module_ctor, self.conn_param_config or conn_param_config, explicit_name, parent_query, kwargs ) def query( self, arg: str | TypeMetaData | Query | typing.Callable[[...], str] | None = None, *, shape: ShapeStringRepr = 'status', optional: bool | None = None, **kwargs ) -> QueryDef | Query: def wrapper(fn: typing.Callable[[...], str]) -> Query: nonlocal optional if shape in ['many', 'one']: if isinstance(arg, TypeMetaData): raise ValueError( "TypeMetaData is not supported for `many` or `one` constructors. " "Use it only for `one` and `column` constructors." ) if not isinstance(arg, Query): if arg is None: # if we don't have a name provided for us, we're gonna create it out of the function name type_name = to_camel_case(fn.__name__) else: type_name = arg if not type_name.isidentifier(): raise ValueError(f"Name type should be a valid python identifier. You provided: {type_name}") else: type_name = None type_name: str | None if shape == 'many': if optional is not None: raise TypeError( 'ALL constructor does not accept `optional` flag -- ' 'at least an empty set will always be returned' ) created_shape = all_(type_name) else: if optional is None: optional = True created_shape = one_(type_name, optional=optional) elif shape in ['value', 'column']: if arg is None: annotation = None else: annotation = arg if shape == 'value': if optional is None: optional = True created_shape = value_(annotation, optional=optional) else: if optional is None: optional = False
from __future__ import annotations logger = logging.getLogger("querky") def to_camel_case(snake_str): return "".join(x.capitalize() for x in snake_str.lower().split("_")) ShapeStringRepr = typing.Literal["one", "many", "column", "value", "status"] QueryDef = typing.Callable[[typing.Callable[[...], str]], Query] class Querky: def __init__( self, basedir: str | None = None, annotation_generator: AnnotationGenerator | None = None, contract: Contract | None = None, conn_param_config: ConnParamConfig | None = None, type_factory: typing.Callable[[Query, str], TypeConstructor] | None = None, subdir: str | None = "queries", on_before_func_code_emit: typing.Optional[typing.Callable[[typing.List[str], Query], typing.List[str]]] = None, on_before_type_code_emit: typing.Optional[typing.Callable[[typing.List[str], Query], typing.List[str]]] = None, imports: typing.Optional[typing.Set[str]] = None, indent: str = ' ', query_class: typing.Type[Query] = Query ): self.basedir = basedir self.on_before_func_code_emit = on_before_func_code_emit self.on_before_type_code_emit = on_before_type_code_emit self.query_class = query_class self.imports = imports or set() self.indent = indent self.annotation_generator = annotation_generator self.module_ctors: dict[types.ModuleType, ModuleConstructor] = dict() self.type_factory = type_factory if conn_param_config is None: conn_param_config = First(name='__conn', positional=True) self.conn_param_config = conn_param_config self.contract = contract self.subdir = subdir if self.subdir and not str.isidentifier(self.subdir): raise ValueError("subdir must be a valid python identifier") self.file_signature = "# ~ AUTOGENERATED BY QUERKY ~ #" def get_indent(self, i: int): return self.indent * i def create_query( self, fn: typing.Callable[[...], str], shape: typing.Callable[[Query], ResultShape], conn_param_config: ConnParamConfig | None, explicit_name: str | None, parent_query: typing.Optional[Query], kwargs: typing.Optional[typing.Dict[str, typing.Any]] ) -> Query: module = inspect.getmodule(fn) if module in self.module_ctors: module_ctor = self.module_ctors[module] else: filename = self.generate_filename(module) if not str.isidentifier(filename): raise ValueError(f"Generated a filename which is not a valid python identifier: {filename}") filedir = path.dirname(module.__file__) new_module_name = module.__name__.rsplit('.', maxsplit=1)[0] if self.subdir: filedir = path.join(filedir, self.subdir) new_module_name = f"{new_module_name}.{self.subdir}" fullpath = path.join(filedir, f'{filename}.py') new_module_name = f"{new_module_name}.{filename}" module_ctor = ModuleConstructor(self, module, fullpath, new_module_name, filedir) self.module_ctors[module] = module_ctor return self.query_class( fn, shape, module_ctor, self.conn_param_config or conn_param_config, explicit_name, parent_query, kwargs ) def query( self, arg: str | TypeMetaData | Query | typing.Callable[[...], str] | None = None, *, shape: ShapeStringRepr = 'status', optional: bool | None = None, **kwargs ) -> QueryDef | Query: def wrapper(fn: typing.Callable[[...], str]) -> Query: nonlocal optional if shape in ['many', 'one']: if isinstance(arg, TypeMetaData): raise ValueError( "TypeMetaData is not supported for `many` or `one` constructors. " "Use it only for `one` and `column` constructors." ) if not isinstance(arg, Query): if arg is None: # if we don't have a name provided for us, we're gonna create it out of the function name type_name = to_camel_case(fn.__name__) else: type_name = arg if not type_name.isidentifier(): raise ValueError(f"Name type should be a valid python identifier. You provided: {type_name}") else: type_name = None type_name: str | None if shape == 'many': if optional is not None: raise TypeError( 'ALL constructor does not accept `optional` flag -- ' 'at least an empty set will always be returned' ) created_shape = all_(type_name) else: if optional is None: optional = True created_shape = one_(type_name, optional=optional) elif shape in ['value', 'column']: if arg is None: annotation = None else: annotation = arg if shape == 'value': if optional is None: optional = True created_shape = value_(annotation, optional=optional) else: if optional is None: optional = False
created_shape = column_(annotation, elem_optional=optional)
4
2023-12-13 15:16:34+00:00
12k
javrtg/C2P
tests/test_constraints.py
[ { "identifier": "constraints", "path": "nonmin_pose/constraints/constraints.py", "snippet": "def assert_smaller_idxes(param1i, param2i):\n def __init__(self, name: str, block: int, block_ids: List[int]):\n def __init__(\n self,\n params: dict,\n idx_first_el: int,\n idx...
import numpy as np from nonmin_pose.constraints import constraints from nonmin_pose.constraints.constraints import Parameter from tests.testing_utils import ( SyntheticData, adjoint_of_3x3_mat, sdpa2mat, skew, so3_orbitope, )
7,275
CFG_DATASET = { "seed": 0, "min_depth": 4.0, "max_depth": 8.0, "focal": 800.0, } CFG_DATA = { "transl_magnitude": 1.0, "euler_ang_magnitude": 0.5, "max_npoints": 100, "noise_level": 0.0, } def create_parameters(): params = [ Parameter("E", 1, list(range(1, 10))), Parameter("t", 1, list(range(10, 13))), Parameter("q", 1, list(range(13, 16))), Parameter("h", 1, [16]), Parameter("R", 1, list(range(17, 26))), Parameter("sct", 1, [26]), Parameter("scr", 1, [27]), Parameter("scr2", 1, [28]), Parameter("scm1", 1, [29]), Parameter("scm2", 1, [30]), Parameter("Zc", 1, list(range(31, 47))), ] return {p.name: p for p in params} def sample_data(): dataset = SyntheticData(**CFG_DATASET) data = dataset.generate_data(**CFG_DATA) h, sct, scr, scr2, scm1, scm2 = 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 q = data["R01"].T @ data["t01_unit"] x = np.concatenate( ( data["E01"].ravel(), data["t01_unit"].ravel(), q.ravel(), [h], data["R01"].ravel(), [sct, scr, scr2, scm1, scm2], so3_orbitope(data["R01"]).ravel(), ) ) return x[:, None], data def gather_errors(x, A, constraint, constraint_num, is_inequality): values = constraint.values if is_inequality: cond_sdpa_sdpa = np.allclose(values, np.zeros_like(values)) cond_data_sdpa = np.allclose((x.T @ A @ x).squeeze(), constraint_num) else: cond_sdpa_sdpa = np.allclose((x.T @ A @ x).squeeze(), values) cond_data_sdpa = np.allclose(constraint_num, values) errors = [] if not cond_sdpa_sdpa: if is_inequality: errors.append("SDPA coefficients are not zero.") else: errors.append("SDPA coefficients lead to different SDPA values.") if not cond_data_sdpa: errors.append( "SDPA values are different than those derived from data." f"\n{(x.T @ A @ x).squeeze()}\n{constraint_num}" ) success = len(errors) == 0 err_msg = "Errors:\n{}".format("\n".join(errors)) return success, err_msg def obtain_errors(constraint_class, x, constraint_num, f0=None, f1=None): params = create_parameters() constraint = constraint_class(params, 0, 0, None) is_inequality = constraint.__class__.__name__.startswith("Cheirality") if is_inequality: constraint.compute_coeffs(constraint.coeffs, f0, f1)
CFG_DATASET = { "seed": 0, "min_depth": 4.0, "max_depth": 8.0, "focal": 800.0, } CFG_DATA = { "transl_magnitude": 1.0, "euler_ang_magnitude": 0.5, "max_npoints": 100, "noise_level": 0.0, } def create_parameters(): params = [ Parameter("E", 1, list(range(1, 10))), Parameter("t", 1, list(range(10, 13))), Parameter("q", 1, list(range(13, 16))), Parameter("h", 1, [16]), Parameter("R", 1, list(range(17, 26))), Parameter("sct", 1, [26]), Parameter("scr", 1, [27]), Parameter("scr2", 1, [28]), Parameter("scm1", 1, [29]), Parameter("scm2", 1, [30]), Parameter("Zc", 1, list(range(31, 47))), ] return {p.name: p for p in params} def sample_data(): dataset = SyntheticData(**CFG_DATASET) data = dataset.generate_data(**CFG_DATA) h, sct, scr, scr2, scm1, scm2 = 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 q = data["R01"].T @ data["t01_unit"] x = np.concatenate( ( data["E01"].ravel(), data["t01_unit"].ravel(), q.ravel(), [h], data["R01"].ravel(), [sct, scr, scr2, scm1, scm2], so3_orbitope(data["R01"]).ravel(), ) ) return x[:, None], data def gather_errors(x, A, constraint, constraint_num, is_inequality): values = constraint.values if is_inequality: cond_sdpa_sdpa = np.allclose(values, np.zeros_like(values)) cond_data_sdpa = np.allclose((x.T @ A @ x).squeeze(), constraint_num) else: cond_sdpa_sdpa = np.allclose((x.T @ A @ x).squeeze(), values) cond_data_sdpa = np.allclose(constraint_num, values) errors = [] if not cond_sdpa_sdpa: if is_inequality: errors.append("SDPA coefficients are not zero.") else: errors.append("SDPA coefficients lead to different SDPA values.") if not cond_data_sdpa: errors.append( "SDPA values are different than those derived from data." f"\n{(x.T @ A @ x).squeeze()}\n{constraint_num}" ) success = len(errors) == 0 err_msg = "Errors:\n{}".format("\n".join(errors)) return success, err_msg def obtain_errors(constraint_class, x, constraint_num, f0=None, f1=None): params = create_parameters() constraint = constraint_class(params, 0, 0, None) is_inequality = constraint.__class__.__name__.startswith("Cheirality") if is_inequality: constraint.compute_coeffs(constraint.coeffs, f0, f1)
A = sdpa2mat(constraint, block_sizes=[len(x)], ndim=len(x))
4
2023-12-10 18:25:10+00:00
12k
Jack24658735/FedLGT
fed_main.py
[ { "identifier": "get_data", "path": "load_data.py", "snippet": "def get_data(args, curr_user=None):\n dataset = args.dataset\n data_root = args.dataroot\n batch_size = args.batch_size\n\n rescale = args.scale_size\n random_crop = args.crop_size\n attr_group_dict = args.attr_group_dict\...
import torch import argparse import numpy as np import utils.evaluate as evaluate import utils.logger as logger import logging import datetime import os import random import clip import json from load_data import get_data from models import CTranModel from config_args import get_args from optim_schedule import WarmupLinearSchedule from run_epoch import run_epoch from tqdm import tqdm from scipy.special import softmax
10,157
def init_nets(args, is_global=False, state_weight=None, label_weight=None): if is_global: n_parties = 1 else: n_parties = args.n_parties nets = {net_i: None for net_i in range(n_parties)} ### FLAIR for net_i in range(n_parties): model = CTranModel(args.num_labels,args.use_lmt,args.pos_emb,args.layers,args.heads,args.dropout,args.no_x_features, state_weight=state_weight, label_weight=label_weight) nets[net_i] = model model_meta_data = [] layer_type = [] for (k, v) in nets[0].state_dict().items(): model_meta_data.append(v.shape) layer_type.append(k) return nets, model_meta_data, layer_type def local_train_net(nets, args, u_id, test_dl = None, device="cpu", g_model=None, emb_feat=None, clip_model=None): data_pts = 0 net_dataidx_map = {} loss_based_agg_list = [] for net_id, net in nets.items(): net.to(device) # TODO: for COCO-dataset, just use indexing of the original dataset to have new subset dataset # TODO: VOC dataset is similar if args.dataset == 'coco' or args.dataset == 'voc': sub_dst = torch.utils.data.Subset(train_dl_global.dataset, partition_idx_map[net_id]) train_dl_local = torch.utils.data.DataLoader(sub_dst, batch_size=args.batch_size,shuffle=True, num_workers=args.workers,drop_last=False) net_dataidx_map[net_id] = len(sub_dst) data_pts += len(sub_dst) else: train_dl_local, test_dl, _, train_dataset = get_data(args, curr_user=u_id[net_id]) # for fedavg net_dataidx_map[net_id] = len(train_dataset) data_pts += len(train_dataset) n_epoch = args.epochs train_metrics, testacc = train_net(net_id, net, train_dl_local, test_dl, n_epoch, args, device=device, g_model=g_model, emb_feat=emb_feat, clip_model=clip_model) # for loss-based agg. loss_based_agg_list.append(train_metrics['loss']) return data_pts, net_dataidx_map, loss_based_agg_list def train_net(net_id, model, train_dataloader, valid_dataloader, epochs, args, device="cpu", g_model=None, emb_feat=None, clip_model=None): fl_logger.info('Training network %s' % str(net_id)) loss_logger = logger.LossLogger(args.model_name) if args.optim == 'adam': optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr)#, weight_decay=0.0004) elif args.optim == 'adamw': optimizer = torch.optim.AdamW(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr) else: optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, momentum=0.9, weight_decay=1e-4) if args.warmup_scheduler: step_scheduler = None scheduler_warmup = WarmupLinearSchedule(optimizer, 1, 300000) else: scheduler_warmup = None if args.scheduler_type == 'plateau': step_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,mode='min',factor=0.1,patience=5) elif args.scheduler_type == 'step': step_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.scheduler_step, gamma=args.scheduler_gamma) else: step_scheduler = None test_loader = None for epoch in range(epochs):
def init_nets(args, is_global=False, state_weight=None, label_weight=None): if is_global: n_parties = 1 else: n_parties = args.n_parties nets = {net_i: None for net_i in range(n_parties)} ### FLAIR for net_i in range(n_parties): model = CTranModel(args.num_labels,args.use_lmt,args.pos_emb,args.layers,args.heads,args.dropout,args.no_x_features, state_weight=state_weight, label_weight=label_weight) nets[net_i] = model model_meta_data = [] layer_type = [] for (k, v) in nets[0].state_dict().items(): model_meta_data.append(v.shape) layer_type.append(k) return nets, model_meta_data, layer_type def local_train_net(nets, args, u_id, test_dl = None, device="cpu", g_model=None, emb_feat=None, clip_model=None): data_pts = 0 net_dataidx_map = {} loss_based_agg_list = [] for net_id, net in nets.items(): net.to(device) # TODO: for COCO-dataset, just use indexing of the original dataset to have new subset dataset # TODO: VOC dataset is similar if args.dataset == 'coco' or args.dataset == 'voc': sub_dst = torch.utils.data.Subset(train_dl_global.dataset, partition_idx_map[net_id]) train_dl_local = torch.utils.data.DataLoader(sub_dst, batch_size=args.batch_size,shuffle=True, num_workers=args.workers,drop_last=False) net_dataidx_map[net_id] = len(sub_dst) data_pts += len(sub_dst) else: train_dl_local, test_dl, _, train_dataset = get_data(args, curr_user=u_id[net_id]) # for fedavg net_dataidx_map[net_id] = len(train_dataset) data_pts += len(train_dataset) n_epoch = args.epochs train_metrics, testacc = train_net(net_id, net, train_dl_local, test_dl, n_epoch, args, device=device, g_model=g_model, emb_feat=emb_feat, clip_model=clip_model) # for loss-based agg. loss_based_agg_list.append(train_metrics['loss']) return data_pts, net_dataidx_map, loss_based_agg_list def train_net(net_id, model, train_dataloader, valid_dataloader, epochs, args, device="cpu", g_model=None, emb_feat=None, clip_model=None): fl_logger.info('Training network %s' % str(net_id)) loss_logger = logger.LossLogger(args.model_name) if args.optim == 'adam': optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr)#, weight_decay=0.0004) elif args.optim == 'adamw': optimizer = torch.optim.AdamW(filter(lambda p: p.requires_grad, model.parameters()),lr=args.lr) else: optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, momentum=0.9, weight_decay=1e-4) if args.warmup_scheduler: step_scheduler = None scheduler_warmup = WarmupLinearSchedule(optimizer, 1, 300000) else: scheduler_warmup = None if args.scheduler_type == 'plateau': step_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer,mode='min',factor=0.1,patience=5) elif args.scheduler_type == 'step': step_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.scheduler_step, gamma=args.scheduler_gamma) else: step_scheduler = None test_loader = None for epoch in range(epochs):
all_preds, all_targs, all_masks, all_ids, train_loss, train_loss_unk = run_epoch(args,model,train_dataloader,optimizer,epoch,'Training',train=True,warmup_scheduler=scheduler_warmup,global_model=g_model,emb_feat=emb_feat, clip_model=clip_model)
4
2023-12-09 09:16:59+00:00
12k
AgriCodeHub/dairy-django-backend
health/views.py
[ { "identifier": "WeightRecordFilterSet", "path": "health/filters.py", "snippet": "class WeightRecordFilterSet(filters.FilterSet):\n \"\"\"\n Filter set for querying WeightRecord instances based on specific criteria.\n\n Filters:\n - `cow`: A filter for the cow associated with the weight reco...
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, status from rest_framework.exceptions import MethodNotAllowed from rest_framework.filters import OrderingFilter from rest_framework.response import Response from health.filters import ( WeightRecordFilterSet, CullingRecordFilterSet, QuarantineRecordFilterSet, DiseaseFilterSet, RecoveryFilterSet, TreatmentFilterSet, ) from health.models import ( DiseaseCategory, Symptoms, WeightRecord, CullingRecord, QuarantineRecord, Pathogen, Disease, Recovery, Treatment, ) from health.serializers import ( DiseaseCategorySerializer, SymptomsSerializer, WeightRecordSerializer, CullingRecordSerializer, QuarantineRecordSerializer, PathogenSerializer, DiseaseSerializer, RecoverySerializer, TreatmentSerializer, ) from users.permissions import IsFarmManager, IsFarmOwner, IsAssistantFarmManager
9,181
class WeightRecordViewSet(viewsets.ModelViewSet): """ ViewSet to handle operations related to weight records. Provides CRUD functionality for weight records. Actions: - list: Get a list of weight records based on applied filters. Returns a 404 response if no weight records match the provided filters, and a 200 response with an empty list if there are no weight records in the database. - retrieve: Retrieve details of a specific weight record. - create: Create a new weight record. - update: Update an existing weight record. - partial_update: Partially update an existing weight record. - destroy: Delete an existing weight record. Serializer class used for request/response data: WeightRecordSerializer. Permissions: - For 'list', 'retrieve': Accessible to assistant farm managers, farm managers, and farm owners only. - For 'create': Accessible to farm workers, assistant farm managers, farm managers, and farm owners. - For 'update', 'partial_update', 'destroy': Accessible to farm managers and farm owners only. """ queryset = WeightRecord.objects.all() serializer_class = WeightRecordSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = WeightRecordFilterSet ordering_fields = ["-date_taken"] permission_classes = [IsAssistantFarmManager | IsFarmManager | IsFarmOwner] def list(self, request, *args, **kwargs): """ List weight records based on applied filters. Returns a 404 response if no weight records match the provided filters, and a 200 response with an empty list if there are no weight records in the database. """ queryset = self.filter_queryset(self.get_queryset()) if not queryset.exists(): if request.query_params: return Response( { "detail": "No Weight records found matching the provided filters." }, status=status.HTTP_404_NOT_FOUND, ) else: return Response( {"detail": "No Weight records found."}, status=status.HTTP_200_OK ) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) class CullingRecordViewSet(viewsets.ModelViewSet): """ ViewSet to handle operations related to culling records. Provides CRUD functionality for culling records. Actions: - list: Get a list of culling records based on applied filters. Returns a 404 response if no culling records match the provided filters, and a 200 response with an empty list if there are no culling records in the database. - retrieve: Retrieve details of a specific culling record. - create: Create a new culling record. - partial_update: Not allowed. - update: Not allowed. - destroy: Delete an existing culling record. Serializer class used for request/response data: CullingRecordSerializer. Permissions: - For 'list', 'retrieve': Accessible to farm managers and farm owners only. - For 'create': Accessible to farm managers and farm owners only. - For 'partial_update', 'update', 'destroy': Accessible to farm managers and farm owners only. """ queryset = CullingRecord.objects.all() serializer_class = CullingRecordSerializer filter_backends = [DjangoFilterBackend, OrderingFilter]
class WeightRecordViewSet(viewsets.ModelViewSet): """ ViewSet to handle operations related to weight records. Provides CRUD functionality for weight records. Actions: - list: Get a list of weight records based on applied filters. Returns a 404 response if no weight records match the provided filters, and a 200 response with an empty list if there are no weight records in the database. - retrieve: Retrieve details of a specific weight record. - create: Create a new weight record. - update: Update an existing weight record. - partial_update: Partially update an existing weight record. - destroy: Delete an existing weight record. Serializer class used for request/response data: WeightRecordSerializer. Permissions: - For 'list', 'retrieve': Accessible to assistant farm managers, farm managers, and farm owners only. - For 'create': Accessible to farm workers, assistant farm managers, farm managers, and farm owners. - For 'update', 'partial_update', 'destroy': Accessible to farm managers and farm owners only. """ queryset = WeightRecord.objects.all() serializer_class = WeightRecordSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = WeightRecordFilterSet ordering_fields = ["-date_taken"] permission_classes = [IsAssistantFarmManager | IsFarmManager | IsFarmOwner] def list(self, request, *args, **kwargs): """ List weight records based on applied filters. Returns a 404 response if no weight records match the provided filters, and a 200 response with an empty list if there are no weight records in the database. """ queryset = self.filter_queryset(self.get_queryset()) if not queryset.exists(): if request.query_params: return Response( { "detail": "No Weight records found matching the provided filters." }, status=status.HTTP_404_NOT_FOUND, ) else: return Response( {"detail": "No Weight records found."}, status=status.HTTP_200_OK ) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) class CullingRecordViewSet(viewsets.ModelViewSet): """ ViewSet to handle operations related to culling records. Provides CRUD functionality for culling records. Actions: - list: Get a list of culling records based on applied filters. Returns a 404 response if no culling records match the provided filters, and a 200 response with an empty list if there are no culling records in the database. - retrieve: Retrieve details of a specific culling record. - create: Create a new culling record. - partial_update: Not allowed. - update: Not allowed. - destroy: Delete an existing culling record. Serializer class used for request/response data: CullingRecordSerializer. Permissions: - For 'list', 'retrieve': Accessible to farm managers and farm owners only. - For 'create': Accessible to farm managers and farm owners only. - For 'partial_update', 'update', 'destroy': Accessible to farm managers and farm owners only. """ queryset = CullingRecord.objects.all() serializer_class = CullingRecordSerializer filter_backends = [DjangoFilterBackend, OrderingFilter]
filterset_class = CullingRecordFilterSet
1
2023-12-09 06:56:42+00:00
12k
facebookresearch/chat2map-official
chat2map/mapping/passive_mapping/policy.py
[ { "identifier": "VisualEnc", "path": "chat2map/mapping/mapping_models/visual_cnn.py", "snippet": "class VisualEnc(nn.Module):\n \"\"\"Visual encoder\"\"\"\n\n def __init__(self, cfg=None):\n \"\"\"Takes in RGB images and 90 degree FoV local egocentric map inputs and encodes them\"\"\"\n ...
import os import pickle import math import numpy as np import torch import torch.nn as nn from torchsummary import summary from chat2map.mapping.mapping_models.visual_cnn import VisualEnc, OccMapDec from chat2map.mapping.mapping_models.audio_cnn import AudioEnc from chat2map.mapping.mapping_models.modality_tag_type_net import ModalityTagTypeNet from chat2map.mapping.mapping_models.positional_net import PositionalNet, PatchPositionalNet from chat2map.mapping.mapping_models.fusion_net import FusionNet from chat2map.mapping.mapping_models.memory_net import TransformerMemory
10,187
context_key_padding_mask = torch.cat(context_key_padding_mask, dim=-1) memory_key_padding_mask = context_key_padding_mask.clone() # --------------------------------------------- query encoding -------------------------------------------------- query_feats = [] """pose encoder""" assert "query_views_pose" in observations query_views_pose = observations["query_views_pose"] # B x max_query_length x ... -> (B * max_query_length) x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_views_pose = query_views_pose.reshape((-1, *query_views_pose.size()[2:])) query_views_poseFeats = self.pose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_poseFeats) query_views_posePatchFeats = self.patchPose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_posePatchFeats) """fusion net""" query_fusedFeats = self.fusion_net(query_feats) query_fusedFeats = query_fusedFeats.permute((0, 2, 3, 1)) query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length, query_fusedFeats.size(1), query_fusedFeats.size(2), query_fusedFeats.size(3))) assert query_fusedFeats.size(2) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] assert query_fusedFeats.size(3) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length *\ query_fusedFeats.size(2) *\ query_fusedFeats.size(3), -1)) # B x max_query_length x ... -> max_query_length x B x -1; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_fusedFeats = query_fusedFeats.permute(1, 0, 2) """query key padding mask""" assert "query_views_mask" in observations query_key_padding_mask = observations["query_views_mask"] assert len(query_key_padding_mask.size()) == 2 query_key_padding_mask = query_key_padding_mask.unsqueeze(-1).unsqueeze(-1) query_key_padding_mask = query_key_padding_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) query_key_padding_mask = query_key_padding_mask.reshape((query_key_padding_mask.size(0), query_key_padding_mask.size(1) *\ query_key_padding_mask.size(2) *\ query_key_padding_mask.size(3))) """memory encoding: context aggregation""" memory_outFeats =\ self.memory_net( { "src_feats": context_fusedFeats, "tgt_feats": query_fusedFeats, "src_key_padding_mask": context_key_padding_mask, "tgt_key_padding_mask": query_key_padding_mask, "memory_key_padding_mask": memory_key_padding_mask, } ) # max_query_length x B x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) memory_outFeats = memory_outFeats.permute(1, 0, 2) memory_outFeats = memory_outFeats.reshape((B, self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1], memory_outFeats.size(2))) memory_outFeats = memory_outFeats.reshape((B * self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] *\ self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] *\ memory_outFeats.size(4))) """query occMap decoder""" query_occMap_pred = self.query_occMap_dec({"memory_outFeats": memory_outFeats}) # (B * max_query_length) x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_occMap_pred = query_occMap_pred.reshape((B, self.max_query_length, *query_occMap_pred.size()[1:])) return query_occMap_pred class PassiveMappingPolicy(Policy): """ Model for passive mapping """ def __init__( self, cfg, ): passive_mapping_cfg = cfg.PassiveMapping task_cfg = cfg.TASK_CONFIG sim_cfg = task_cfg.SIMULATOR # --------------------------------------------- context encoders ----------------------------------------------- """pose net""" pose_net = PositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) patchPose_net = PatchPositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) """modality tag type lookup table""" modality_tag_type_lookup_dict = ModalityTagTypeNet( n_modality_tag_types=3, passive_mapping_cfg=passive_mapping_cfg, ) """views encoder"""
# 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 Policy(nn.Module): """ Parent class of model for passive mapping """ def __init__(self, context_views_enc, context_audio_enc, pose_net, patchPose_net, modality_tag_type_lookup_dict, fusion_net, memory_net, query_occMap_dec, cfg ): """Given the audio streams and sampled frames during a conversation, the model predicts estimates of target occupancy maps""" super().__init__() self.context_views_enc = context_views_enc self.context_audio_enc = context_audio_enc self.pose_net = pose_net self.patchPose_net = patchPose_net self.modality_tag_type_lookup_dict = modality_tag_type_lookup_dict self.fusion_net = fusion_net self.memory_net = memory_net self.query_occMap_dec = query_occMap_dec self._cfg = cfg self._task_cfg = cfg.TASK_CONFIG self._env_cfg = self._task_cfg.ENVIRONMENT self._sim_cfg = self._task_cfg.SIMULATOR self._audio_cfg = self._sim_cfg.AUDIO self._passive_mapping_cfg = cfg.PassiveMapping self.max_context_length = self._env_cfg.MAX_CONTEXT_LENGTH self.max_query_length = self._env_cfg.MAX_QUERY_LENGTH def forward(self, observations): """Given the audio streams and sampled frames during a conversation, predicts estimates of target occupancy maps""" # --------------------------------------------- context encoding ------------------------------------------------ context_feats = [] for feat_idx in range(3): context_feats.append([]) context_key_padding_mask = [] """views encoder""" assert "context_maps" in observations context_maps = observations["context_maps"] assert "context_views_pose" in observations context_views_pose = observations["context_views_pose"] assert "context_views_mask" in observations context_views_mask = observations["context_views_mask"] assert len(context_views_mask.size()) == 3 B = context_maps.size(0) num_agents = context_maps.size(1) context_maps = context_maps.reshape((-1, *context_maps.size()[3:])) context_views_dct = {"occ_map": context_maps} if "RGB_SENSOR" in self._cfg.SENSORS: assert "context_rgbs" in observations context_rgbs = observations["context_rgbs"] context_rgbs = context_rgbs.reshape((-1, *context_rgbs.size()[3:])) context_views_dct["rgb"] = context_rgbs context_views_feats = self.context_views_enc(context_views_dct) context_feats[0].append(context_views_feats) # B x num_agents x max_context_length x ... -> (B * num_agents * max_context_length) x ...; B: batch size, # max_context_length: transformer source sequence length S (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) context_views_pose = context_views_pose.reshape((-1, *context_views_pose.size()[3:])) context_views_poseFeats = self.pose_net({"positional_obs": context_views_pose}) context_feats[0].append(context_views_poseFeats) context_views_posePatchFeats = self.patchPose_net({"positional_obs": context_views_pose}) context_feats[0].append(context_views_posePatchFeats) context_views_modalityType = torch.LongTensor([0]).to(context_views_poseFeats.device) context_views_modalityTypeFeats = self.modality_tag_type_lookup_dict(context_views_modalityType) context_views_modalityTypeFeats =\ context_views_modalityTypeFeats.repeat((context_views_posePatchFeats.size(0), 1, 1, 1)) context_feats[0].append(context_views_modalityTypeFeats) # B x num_agents x max_context_length -> B x (num_agents * max_context_length); B: batch size, context_views_mask = context_views_mask.reshape((context_views_mask.size(0), -1)) context_views_mask = context_views_mask.unsqueeze(-1).unsqueeze(-1) context_views_mask = context_views_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) context_views_mask = context_views_mask.reshape((context_views_mask.size(0), context_views_mask.size(1) *\ context_views_mask.size(2) *\ context_views_mask.size(3))) context_key_padding_mask.append(context_views_mask) """self audio encoder""" assert "context_selfAudio" in observations context_selfAudio = observations["context_selfAudio"] assert "context_selfAudio_pose" in observations context_selfAudio_pose = observations["context_selfAudio_pose"] assert "context_selfAudio_mask" in observations context_selfAudio_mask = observations["context_selfAudio_mask"] assert len(context_selfAudio_mask.size()) == 3 assert "context_otherAudio" in observations context_otherAudio = observations["context_otherAudio"] context_selfAudio = context_selfAudio.reshape((-1, *context_selfAudio.size()[3:])) context_otherAudio = context_otherAudio.reshape((-1, *context_otherAudio.size()[3:])) context_audio = torch.cat([context_selfAudio, context_otherAudio], dim=0) context_audio_feats = self.context_audio_enc({"audio": context_audio}) context_selfAudio_feats = context_audio_feats[:context_selfAudio.size(0)] context_feats[1].append(context_selfAudio_feats) # B x num_agents x max_context_length x ... -> (B * num_agents * max_context_length) x ...; B: batch size, # max_context_length: transformer source sequence length S (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) context_selfAudio_pose = context_selfAudio_pose.reshape((-1, *context_selfAudio_pose.size()[3:])) context_selfAudio_poseFeats = self.pose_net({"positional_obs": context_selfAudio_pose}) context_feats[1].append(context_selfAudio_poseFeats) context_selfAudio_posePatchFeats = self.patchPose_net({"positional_obs": context_selfAudio_pose}) context_feats[1].append(context_selfAudio_posePatchFeats) context_selfAudio_modalityType = torch.LongTensor([1]).to(context_selfAudio_poseFeats.device) context_selfAudio_modalityTypeFeats = self.modality_tag_type_lookup_dict(context_selfAudio_modalityType) context_selfAudio_modalityTypeFeats =\ context_selfAudio_modalityTypeFeats.repeat((context_selfAudio_modalityTypeFeats.size(0), 1, 1, 1)) context_feats[1].append(context_selfAudio_modalityTypeFeats) # B x num_agents x max_context_length -> B x (num_agents * max_context_length); B: batch size, context_selfAudio_mask = context_selfAudio_mask.reshape((context_selfAudio_mask.size(0), -1)) context_selfAudio_mask = context_selfAudio_mask.unsqueeze(-1).unsqueeze(-1) context_selfAudio_mask = context_selfAudio_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) context_selfAudio_mask = context_selfAudio_mask.reshape((context_selfAudio_mask.size(0), context_selfAudio_mask.size(1) *\ context_selfAudio_mask.size(2) *\ context_selfAudio_mask.size(3))) context_key_padding_mask.append(context_selfAudio_mask) """audio from other ego encoder""" context_otherAudio_feats = context_audio_feats[context_otherAudio.size(0):] assert "context_otherAudio_pose" in observations context_otherAudio_pose = observations["context_otherAudio_pose"] assert "context_otherAudio_mask" in observations context_otherAudio_mask = observations["context_otherAudio_mask"] assert len(context_otherAudio_mask.size()) == 3 context_feats[2].append(context_otherAudio_feats) # B x num_agents x max_context_length x ... -> (B * num_agents * max_context_length) x ...; B: batch size, # max_context_length: transformer source sequence length S (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) context_otherAudio_pose = context_otherAudio_pose.reshape((-1, *context_otherAudio_pose.size()[3:])) context_otherAudio_poseFeats = self.pose_net({"positional_obs": context_otherAudio_pose}) context_feats[2].append(context_otherAudio_poseFeats) context_otherAudio_posePatchFeats = self.patchPose_net({"positional_obs": context_otherAudio_pose}) context_feats[2].append(context_otherAudio_posePatchFeats) context_otherAudio_modalityType =\ torch.LongTensor([2]).to(context_otherAudio_poseFeats.device) context_otherAudio_modalityTypeFeats = self.modality_tag_type_lookup_dict(context_otherAudio_modalityType) context_otherAudio_modalityTypeFeats =\ context_otherAudio_modalityTypeFeats.repeat((context_otherAudio_modalityTypeFeats.size(0), 1, 1, 1)) context_feats[2].append(context_otherAudio_modalityTypeFeats) # B x num_agents x max_context_length -> B x (num_agents * max_context_length); B: batch size, context_otherAudio_mask = context_otherAudio_mask.reshape((context_otherAudio_mask.size(0), -1)) context_otherAudio_mask = context_otherAudio_mask.unsqueeze(-1).unsqueeze(-1) context_otherAudio_mask = context_otherAudio_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) context_otherAudio_mask = context_otherAudio_mask.reshape((context_otherAudio_mask.size(0), context_otherAudio_mask.size(1) *\ context_otherAudio_mask.size(2) *\ context_otherAudio_mask.size(3))) context_key_padding_mask.append(context_otherAudio_mask) """fusion net""" context_fusedFeats = [] for idx_contextFeats in range(len(context_feats)): temp_context_fusedFeats = self.fusion_net(context_feats[idx_contextFeats]) temp_context_fusedFeats = temp_context_fusedFeats.permute((0, 2, 3, 1)) temp_context_fusedFeats = temp_context_fusedFeats.reshape((B, num_agents * self.max_context_length, temp_context_fusedFeats.size(1), temp_context_fusedFeats.size(2), temp_context_fusedFeats.size(3))) assert temp_context_fusedFeats.size(2) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] assert temp_context_fusedFeats.size(3) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] temp_context_fusedFeats = temp_context_fusedFeats.reshape((B, num_agents * self.max_context_length *\ temp_context_fusedFeats.size(2) *\ temp_context_fusedFeats.size(3), -1)) temp_context_fusedFeats = temp_context_fusedFeats.permute(1, 0, 2) context_fusedFeats.append(temp_context_fusedFeats) context_fusedFeats = torch.cat(context_fusedFeats, dim=0) """context and memory key padding masks""" context_key_padding_mask = torch.cat(context_key_padding_mask, dim=-1) memory_key_padding_mask = context_key_padding_mask.clone() # --------------------------------------------- query encoding -------------------------------------------------- query_feats = [] """pose encoder""" assert "query_views_pose" in observations query_views_pose = observations["query_views_pose"] # B x max_query_length x ... -> (B * max_query_length) x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_views_pose = query_views_pose.reshape((-1, *query_views_pose.size()[2:])) query_views_poseFeats = self.pose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_poseFeats) query_views_posePatchFeats = self.patchPose_net({"positional_obs": query_views_pose}) query_feats.append(query_views_posePatchFeats) """fusion net""" query_fusedFeats = self.fusion_net(query_feats) query_fusedFeats = query_fusedFeats.permute((0, 2, 3, 1)) query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length, query_fusedFeats.size(1), query_fusedFeats.size(2), query_fusedFeats.size(3))) assert query_fusedFeats.size(2) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] assert query_fusedFeats.size(3) == self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] query_fusedFeats = query_fusedFeats.reshape((B, self.max_query_length *\ query_fusedFeats.size(2) *\ query_fusedFeats.size(3), -1)) # B x max_query_length x ... -> max_query_length x B x -1; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_fusedFeats = query_fusedFeats.permute(1, 0, 2) """query key padding mask""" assert "query_views_mask" in observations query_key_padding_mask = observations["query_views_mask"] assert len(query_key_padding_mask.size()) == 2 query_key_padding_mask = query_key_padding_mask.unsqueeze(-1).unsqueeze(-1) query_key_padding_mask = query_key_padding_mask.repeat((1, 1, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1])) query_key_padding_mask = query_key_padding_mask.reshape((query_key_padding_mask.size(0), query_key_padding_mask.size(1) *\ query_key_padding_mask.size(2) *\ query_key_padding_mask.size(3))) """memory encoding: context aggregation""" memory_outFeats =\ self.memory_net( { "src_feats": context_fusedFeats, "tgt_feats": query_fusedFeats, "src_key_padding_mask": context_key_padding_mask, "tgt_key_padding_mask": query_key_padding_mask, "memory_key_padding_mask": memory_key_padding_mask, } ) # max_query_length x B x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) memory_outFeats = memory_outFeats.permute(1, 0, 2) memory_outFeats = memory_outFeats.reshape((B, self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0], self._passive_mapping_cfg.PositionalNet.patch_hwCh[1], memory_outFeats.size(2))) memory_outFeats = memory_outFeats.reshape((B * self.max_query_length, self._passive_mapping_cfg.PositionalNet.patch_hwCh[0] *\ self._passive_mapping_cfg.PositionalNet.patch_hwCh[1] *\ memory_outFeats.size(4))) """query occMap decoder""" query_occMap_pred = self.query_occMap_dec({"memory_outFeats": memory_outFeats}) # (B * max_query_length) x ... -> B x max_query_length x ...; B: batch size, # max_query_length: transformer target sequence length T (https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Transformer) query_occMap_pred = query_occMap_pred.reshape((B, self.max_query_length, *query_occMap_pred.size()[1:])) return query_occMap_pred class PassiveMappingPolicy(Policy): """ Model for passive mapping """ def __init__( self, cfg, ): passive_mapping_cfg = cfg.PassiveMapping task_cfg = cfg.TASK_CONFIG sim_cfg = task_cfg.SIMULATOR # --------------------------------------------- context encoders ----------------------------------------------- """pose net""" pose_net = PositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) patchPose_net = PatchPositionalNet( passive_mapping_cfg=passive_mapping_cfg, ) """modality tag type lookup table""" modality_tag_type_lookup_dict = ModalityTagTypeNet( n_modality_tag_types=3, passive_mapping_cfg=passive_mapping_cfg, ) """views encoder"""
context_views_enc = VisualEnc(
0
2023-12-06 01:20:37+00:00
12k
PeriniM/Rotary-Pendulum-RL
control/reinforcement_learning/src/main.py
[ { "identifier": "RealPendulumEnv", "path": "control/reinforcement_learning/Environments/RealPendulumEnv.py", "snippet": "class RealPendulumEnv(gym.Env):\n \"\"\"\n Real rotary pendulum with ESP32\n \"\"\"\n\n metadata = {\"render_modes\": [\"human\"]}\n\n def __init__(self, port, baudrate...
from ..Environments import RealPendulumEnv as real from ..Environments import PyBulletPendulumEnv as pb from ..Environments import FakeEnv as fake from ..DQN.Agent import Agent
10,453
isFake = False isPyBullet = True isReal = False train = True plot_colormaps = False # select the environment if isFake: env = fake.FakeEnv(1) elif isPyBullet: env = pb.PyBulletPendulumEnv(render_mode='human') elif isReal:
isFake = False isPyBullet = True isReal = False train = True plot_colormaps = False # select the environment if isFake: env = fake.FakeEnv(1) elif isPyBullet: env = pb.PyBulletPendulumEnv(render_mode='human') elif isReal:
env = real.RealPendulumEnv("COM3", 115200)
0
2023-12-09 11:22:54+00:00
12k
tommy-xq/SA2VP
vpt_main/src/models/build_model.py
[ { "identifier": "ResNet", "path": "vpt_main/src/models/resnet.py", "snippet": "class ResNet(nn.Module):\n \"\"\"ResNet model.\"\"\"\n\n def __init__(self, cfg):\n super(ResNet, self).__init__()\n self.cfg = cfg\n\n model_type = cfg.DATA.FEATURE\n model = self.get_pretra...
from tabnanny import verbose from .resnet import ResNet from .convnext import ConvNeXt from .vit_models import ViT, Swin, SSLViT from ..utils import logging import torch
10,118
#!/usr/bin/env python3 """ Model construction functions. """ logger = logging.get_logger("visual_prompt") # Supported model types _MODEL_TYPES = { "resnet": ResNet, "convnext": ConvNeXt, "vit": ViT,
#!/usr/bin/env python3 """ Model construction functions. """ logger = logging.get_logger("visual_prompt") # Supported model types _MODEL_TYPES = { "resnet": ResNet, "convnext": ConvNeXt, "vit": ViT,
"swin": Swin,
3
2023-12-12 13:19:17+00:00
12k
KULL-Centre/_2023_Blaabjerg_SSEmb
src/models/msa_transformer/modules.py
[ { "identifier": "MultiheadAttention", "path": "src/models/msa_transformer/multihead_attention.py", "snippet": "class MultiheadAttention(nn.Module):\n \"\"\"Multi-headed attention.\n\n See \"Attention Is All You Need\" for more details.\n \"\"\"\n\n def __init__(\n self,\n embed...
import math import torch import torch.nn as nn import torch.nn.functional as F from typing import Tuple, Optional from .multihead_attention import MultiheadAttention # noqa from .axial_attention import ColumnSelfAttention, RowSelfAttention from apex.normalization import FusedLayerNorm as _FusedLayerNorm from torch.nn import LayerNorm as ESM1bLayerNorm
7,964
class ESM1LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12, affine=True): """Construct a layernorm layer in the TF style (eps inside the sqrt).""" super().__init__() self.hidden_size = (hidden_size,) if isinstance(hidden_size, int) else tuple(hidden_size) self.eps = eps self.affine = bool(affine) if self.affine: self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) else: self.weight, self.bias = None, None def forward(self, x): dims = tuple(-(i + 1) for i in range(len(self.hidden_size))) means = x.mean(dims, keepdim=True) x_zeromean = x - means variances = x_zeromean.pow(2).mean(dims, keepdim=True) x = x_zeromean / torch.sqrt(variances + self.eps) if self.affine: x = (self.weight * x) + self.bias return x try: class ESM1bLayerNorm(_FusedLayerNorm): @torch.jit.unused def forward(self, x): if not x.is_cuda: return super().forward(x) else: with torch.cuda.device(x.device): return super().forward(x) except ImportError: class TransformerLayer(nn.Module): """Transformer layer block.""" def __init__( self, embed_dim, ffn_embed_dim, attention_heads, add_bias_kv=True, use_esm1b_layer_norm=False, use_rotary_embeddings: bool = False, ): super().__init__() self.embed_dim = embed_dim self.ffn_embed_dim = ffn_embed_dim self.attention_heads = attention_heads self.use_rotary_embeddings = use_rotary_embeddings self._init_submodules(add_bias_kv, use_esm1b_layer_norm) def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm): BertLayerNorm = ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm self.self_attn = MultiheadAttention( self.embed_dim, self.attention_heads, add_bias_kv=add_bias_kv, add_zero_attn=False, use_rotary_embeddings=self.use_rotary_embeddings, ) self.self_attn_layer_norm = BertLayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, self.ffn_embed_dim) self.fc2 = nn.Linear(self.ffn_embed_dim, self.embed_dim) self.final_layer_norm = BertLayerNorm(self.embed_dim) def forward( self, x, self_attn_mask=None, self_attn_padding_mask=None, need_head_weights=False ): residual = x x = self.self_attn_layer_norm(x) x, attn = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, need_weights=True, need_head_weights=need_head_weights, attn_mask=self_attn_mask, ) x = residual + x residual = x x = self.final_layer_norm(x) x = gelu(self.fc1(x)) x = self.fc2(x) x = residual + x return x, attn class AxialTransformerLayer(nn.Module): """Implements an Axial MSA Transformer block.""" def __init__( self, embedding_dim: int = 768, ffn_embedding_dim: int = 3072, num_attention_heads: int = 8, dropout: float = 0.1, attention_dropout: float = 0.1, activation_dropout: float = 0.1, max_tokens_per_msa: int = 2**14, ) -> None: super().__init__() # Initialize parameters self.embedding_dim = embedding_dim self.dropout_prob = dropout
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. def gelu(x): """Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) def symmetrize(x): "Make layer symmetric in final two dimensions, used for contact prediction." return x + x.transpose(-1, -2) def apc(x): "Perform average product correct, used for contact prediction." a1 = x.sum(-1, keepdims=True) a2 = x.sum(-2, keepdims=True) a12 = x.sum((-1, -2), keepdims=True) avg = a1 * a2 avg.div_(a12) # in-place to reduce memory normalized = x - avg return normalized class ESM1LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12, affine=True): """Construct a layernorm layer in the TF style (eps inside the sqrt).""" super().__init__() self.hidden_size = (hidden_size,) if isinstance(hidden_size, int) else tuple(hidden_size) self.eps = eps self.affine = bool(affine) if self.affine: self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) else: self.weight, self.bias = None, None def forward(self, x): dims = tuple(-(i + 1) for i in range(len(self.hidden_size))) means = x.mean(dims, keepdim=True) x_zeromean = x - means variances = x_zeromean.pow(2).mean(dims, keepdim=True) x = x_zeromean / torch.sqrt(variances + self.eps) if self.affine: x = (self.weight * x) + self.bias return x try: class ESM1bLayerNorm(_FusedLayerNorm): @torch.jit.unused def forward(self, x): if not x.is_cuda: return super().forward(x) else: with torch.cuda.device(x.device): return super().forward(x) except ImportError: class TransformerLayer(nn.Module): """Transformer layer block.""" def __init__( self, embed_dim, ffn_embed_dim, attention_heads, add_bias_kv=True, use_esm1b_layer_norm=False, use_rotary_embeddings: bool = False, ): super().__init__() self.embed_dim = embed_dim self.ffn_embed_dim = ffn_embed_dim self.attention_heads = attention_heads self.use_rotary_embeddings = use_rotary_embeddings self._init_submodules(add_bias_kv, use_esm1b_layer_norm) def _init_submodules(self, add_bias_kv, use_esm1b_layer_norm): BertLayerNorm = ESM1bLayerNorm if use_esm1b_layer_norm else ESM1LayerNorm self.self_attn = MultiheadAttention( self.embed_dim, self.attention_heads, add_bias_kv=add_bias_kv, add_zero_attn=False, use_rotary_embeddings=self.use_rotary_embeddings, ) self.self_attn_layer_norm = BertLayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, self.ffn_embed_dim) self.fc2 = nn.Linear(self.ffn_embed_dim, self.embed_dim) self.final_layer_norm = BertLayerNorm(self.embed_dim) def forward( self, x, self_attn_mask=None, self_attn_padding_mask=None, need_head_weights=False ): residual = x x = self.self_attn_layer_norm(x) x, attn = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, need_weights=True, need_head_weights=need_head_weights, attn_mask=self_attn_mask, ) x = residual + x residual = x x = self.final_layer_norm(x) x = gelu(self.fc1(x)) x = self.fc2(x) x = residual + x return x, attn class AxialTransformerLayer(nn.Module): """Implements an Axial MSA Transformer block.""" def __init__( self, embedding_dim: int = 768, ffn_embedding_dim: int = 3072, num_attention_heads: int = 8, dropout: float = 0.1, attention_dropout: float = 0.1, activation_dropout: float = 0.1, max_tokens_per_msa: int = 2**14, ) -> None: super().__init__() # Initialize parameters self.embedding_dim = embedding_dim self.dropout_prob = dropout
row_self_attention = RowSelfAttention(
2
2023-12-09 11:42:34+00:00
12k
ChatClue/ChatClue
osiris.py
[ { "identifier": "OSHelper", "path": "utils/os/helpers.py", "snippet": "class OSHelper:\n \"\"\"\n Provides utility methods for operating system level operations, particularly file management.\n\n This class includes static methods for performing various file system tasks such as cleaning up orp...
from config import CELERY_CONFIG, LOG_LEVEL, VIDEO_SETTINGS from utils.os.helpers import OSHelper from celery import Celery from celery_config import get_celery_app from database.setup import DatabaseSetup from broadcast.broadcaster import broadcaster from audio.audio_processor import AudioProcessor from video.video_processor import VideoProcessor from audio.audio_out import get_audio_out from utils.os.helpers import OSHelper from utils.text.welcome import welcome_message from utils.logging.colors import ColorFormatter from background.memory.tasks import * from tools import * # Import all openai tool functions import logging import subprocess import atexit import sys import threading import time import cv2 import queue
7,353
# Configure basic logging for the application logging.basicConfig(level=LOG_LEVEL) root_logger = logging.getLogger() for handler in root_logger.handlers: handler.setFormatter(ColorFormatter('%(asctime)s - %(levelname)s - %(message)s')) # Ensure the necessary tmp/ directories exist OSHelper.configure_tmp_directories() # Configure background processor / subconcious systems celery_app = get_celery_app() # Configure audio output audio_out = get_audio_out() def start_celery_worker(): """ Starts a Celery worker as a subprocess. This method initiates a Celery worker using the subprocess module. The worker runs asynchronously and executes tasks defined in the Celery application. The worker is configured to log at the 'info' level for better visibility of its operations. The function also ensures that the Celery worker is terminated gracefully when the Python script exits. This is achieved using the `atexit` module, which registers a function to terminate the worker as part of the script's cleanup process. Returns: subprocess.Popen: The subprocess object representing the Celery worker. """ # Get the log level from configuration, default to 'info' log_level = CELERY_CONFIG.get('LOCAL_LOG_LEVEL', 'info') # Start Celery worker celery_worker = subprocess.Popen(['celery', '-A', 'osiris.celery_app', 'worker', f'--loglevel={log_level}']) # Register function to terminate worker on exit atexit.register(lambda: celery_worker.terminate()) return celery_worker def stop_celery_worker(celery_worker): """ Stops the Celery worker gracefully. Args: celery_worker (subprocess.Popen): The subprocess object representing the Celery worker. """ if celery_worker: # Send SIGTERM signal to gracefully terminate the worker celery_worker.terminate() # Wait for the worker to exit try: celery_worker.wait(timeout=0.5) # Adjust the timeout as needed except subprocess.TimeoutExpired: # If the worker doesn't terminate within the timeout, kill it logging.info("Forcibly terminating the Celery worker.") celery_worker.kill() def main(): """ Main function to initialize the application. Configures celery background worker, database, broadcaster, and audio settings. """ welcome_message() # Optionally start Celery worker celery_worker = None if CELERY_CONFIG.get("RUN_LOCALLY_AUTOMATICALLY", True): logging.info("ROBOT THOUGHT: Starting subconscious systems locally") celery_worker = start_celery_worker() logging.info("ROBOT THOUGHT: Subconscious systems activated") # Setup the database
# Configure basic logging for the application logging.basicConfig(level=LOG_LEVEL) root_logger = logging.getLogger() for handler in root_logger.handlers: handler.setFormatter(ColorFormatter('%(asctime)s - %(levelname)s - %(message)s')) # Ensure the necessary tmp/ directories exist OSHelper.configure_tmp_directories() # Configure background processor / subconcious systems celery_app = get_celery_app() # Configure audio output audio_out = get_audio_out() def start_celery_worker(): """ Starts a Celery worker as a subprocess. This method initiates a Celery worker using the subprocess module. The worker runs asynchronously and executes tasks defined in the Celery application. The worker is configured to log at the 'info' level for better visibility of its operations. The function also ensures that the Celery worker is terminated gracefully when the Python script exits. This is achieved using the `atexit` module, which registers a function to terminate the worker as part of the script's cleanup process. Returns: subprocess.Popen: The subprocess object representing the Celery worker. """ # Get the log level from configuration, default to 'info' log_level = CELERY_CONFIG.get('LOCAL_LOG_LEVEL', 'info') # Start Celery worker celery_worker = subprocess.Popen(['celery', '-A', 'osiris.celery_app', 'worker', f'--loglevel={log_level}']) # Register function to terminate worker on exit atexit.register(lambda: celery_worker.terminate()) return celery_worker def stop_celery_worker(celery_worker): """ Stops the Celery worker gracefully. Args: celery_worker (subprocess.Popen): The subprocess object representing the Celery worker. """ if celery_worker: # Send SIGTERM signal to gracefully terminate the worker celery_worker.terminate() # Wait for the worker to exit try: celery_worker.wait(timeout=0.5) # Adjust the timeout as needed except subprocess.TimeoutExpired: # If the worker doesn't terminate within the timeout, kill it logging.info("Forcibly terminating the Celery worker.") celery_worker.kill() def main(): """ Main function to initialize the application. Configures celery background worker, database, broadcaster, and audio settings. """ welcome_message() # Optionally start Celery worker celery_worker = None if CELERY_CONFIG.get("RUN_LOCALLY_AUTOMATICALLY", True): logging.info("ROBOT THOUGHT: Starting subconscious systems locally") celery_worker = start_celery_worker() logging.info("ROBOT THOUGHT: Subconscious systems activated") # Setup the database
DatabaseSetup.initial_setup()
2
2023-12-06 09:10:06+00:00
12k
lumina-test/lumina
lumina/e2e_test/test_cnp.py
[ { "identifier": "get_qp_info_list", "path": "lumina/analyzer/main.py", "snippet": "LOG_FILENAME = \"analysis.log\"\nRESULT_FILENAME = \"result.out\"\ndef get_qp_info_list(switch_msg_snapshot):\ndef main(args):\ndef parse_args():" }, { "identifier": "Orchestrator", "path": "lumina/orchestrato...
import argparse, os, glob, logging, time import lumina.analyzer.checker.integrity_check as integrity_check import lumina.analyzer.checker.host_check as host_check import lumina.analyzer.checker.cnp_check as cnp_check import lumina.orchestrator.host as host import lumina.orchestrator.switch as switch from lumina.analyzer.main import get_qp_info_list, get_packet_list from lumina.orchestrator.main import Orchestrator from lumina.analyzer.counter.switch_counter import SwitchCounter from lumina.analyzer.counter.host_counter import MLNXHostCounter, IntelHostCounter from lumina.analyzer.pcap_processor.pcap_process import get_packet_list from lumina.utils.config_loggers import config_stream_handler, config_file_handler
9,750
def verify_results(orchestrator, rdma_verb=None, qp_index_list=None): """ Verify experiment results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations rdma_verb (str): RDMA verb to verify (default: None) qp_index_list (list): List of QP indices to verify (default: None) Returns: N/A """ result_dir = orchestrator.result_path num_repeats = orchestrator.num_repeats aggregate_pcap_filename = orchestrator.aggregate_pcap_filename if rdma_verb == None: rdma_verb = orchestrator.traffic_conf['rdma-verb'].lower().strip() if rdma_verb not in host.VALID_IB_VERB_LIST_LOWER: logging.error("Invalid RDMA verb: %s" % rdma_verb) return ## A mix of RDMA SEND and READ. Need to verify both SEND and READ if rdma_verb == 'send_read': num_qps_send, num_qps_read = [int(x) for x in orchestrator.traffic_conf['num-qps'].split(',')] verify_results(orchestrator=orchestrator, rdma_verb='send', qp_index_list=list(range(num_qps_send))) verify_results(orchestrator=orchestrator, rdma_verb='read', qp_index_list=list(range(num_qps_send, num_qps_send+num_qps_read))) return elif rdma_verb == "read": receiver_nic_type = orchestrator.requester.conf['nic']['type'] if orchestrator.requester.is_intel_nic(): receiver_np_enable = orchestrator.requester.conf['roce-parameters']['dcqcn-enable'] receiver_slow_restart = False min_time_between_cnps_us = 0 elif orchestrator.requester.is_mlnx_nic(): receiver_np_enable = orchestrator.requester.conf['roce-parameters']['dcqcn-np-enable'] receiver_slow_restart = orchestrator.requester.conf['roce-parameters']['slow-restart'] min_time_between_cnps_us = orchestrator.requester.conf['roce-parameters']['min-time-between-cnps'] else: receiver_np_enable = False receiver_slow_restart = False min_time_between_cnps_us = 0 else: receiver_nic_type = orchestrator.responder.conf['nic']['type'] if orchestrator.responder.is_intel_nic(): receiver_np_enable = orchestrator.responder.conf['roce-parameters']['dcqcn-enable'] receiver_slow_restart = False min_time_between_cnps_us = 0 elif orchestrator.responder.is_mlnx_nic(): receiver_np_enable = orchestrator.responder.conf['roce-parameters']['dcqcn-np-enable'] receiver_slow_restart = orchestrator.responder.conf['roce-parameters']['slow-restart'] min_time_between_cnps_us = orchestrator.responder.conf['roce-parameters']['min-time-between-cnps'] else: receiver_np_enable = False receiver_slow_restart = False min_time_between_cnps_us = 0 nack_trigger_cnp = cnp_check.check_nack_trigger_cnp(receiver_nic_type, receiver_np_enable, receiver_slow_restart) port_map = {'requester': orchestrator.requester.conf['nic']['switch-port'], 'responder': orchestrator.responder.conf['nic']['switch-port'], 'requester-mirror': orchestrator.requester_mirror.conf['nic']['switch-port'], 'responder-mirror': orchestrator.responder_mirror.conf['nic']['switch-port']} requester_ip_list = orchestrator.get_requester_ip_list() responder_ip_list = orchestrator.get_responder_ip_list() for iter in range(num_repeats): iter = str(iter) result_logger = logging.getLogger('Iter %s Verb %s' % (iter, rdma_verb)) result_logger.handlers.clear() config_file_handler(logger=result_logger, log_file=os.path.join(result_dir, iter, RESULT_FILENAME), no_format=True) result_logger.info("=" * 100) result_logger.info("Iteration %s Verb %s" % (iter, rdma_verb)) switch_msg_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_MESSAGE_SNAPSHOT) switch_state_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_STATE_SNAPSHOT) pcap_filename = os.path.join(result_dir, iter, host.PCAP_RESULT_DIR, aggregate_pcap_filename) requester_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_START_COUNTER_FILE_NAME) requester_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_FINISH_COUNTER_FILE_NAME) responder_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_START_COUNTER_FILE_NAME) responder_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_FINISH_COUNTER_FILE_NAME) switch_counter = SwitchCounter(switch_state_snapshot, port_map) if orchestrator.requester.is_mlnx_nic(): requester_counter = MLNXHostCounter(requester_counter_start, requester_counter_finish) elif orchestrator.requester.is_intel_nic():
## All logs will be logged into file LOG_FILENAME LOG_FILENAME = "test_cnp.log" ## Results (checkers and measurements) will also be dumped into file RESULT_FILENAME RESULT_FILENAME = "result.log" ## Max # of retries for each experiment iteration MAX_NB_EXP_RETRIES = 3 def setup_root_logger(orchestrator): """ Setup the root logger Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations """ root_logger = logging.getLogger() root_logger.handlers.clear() config_stream_handler(root_logger) config_file_handler(logger=root_logger, log_file=os.path.join(orchestrator.result_path, LOG_FILENAME), no_format=False) def run_traffic(orchestrator): """ Run the traffic and collect results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: bool: True if successful, False otherwise """ orchestrator.rm_old_files() if orchestrator.sync_and_compile() == False: logging.error("Failed to sync and compile the code") sys.exit(-1) logging.info("Sync and compile completed") if orchestrator.generate_switch_config_file() == False: logging.error("Failed to generate switch configuration file") sys.exit(-1) num_repeats = orchestrator.get_num_repeats() for i in range(num_repeats): logging.info("=" * 100) nb_retry = 0 iter_result = False while nb_retry < MAX_NB_EXP_RETRIES: if orchestrator.run_experiment() == False: logging.error("Iteration %d: Failed to complete experiment" % i) logging.error("Iteration %d: Rerun experiment (retry: %d)" % i, nb_retry) nb_retry += 1 orchestrator.clean_up() time.sleep(5) continue logging.info("Iteration %d: Completed experiment" % i) try: orchestrator.clean_up() orchestrator.fetch_results(i) logging.info("Iteration %d: Fetch experiment results" % i) orchestrator.merge_traces(i) logging.info("Iteration %d: Merge the pcap files" % i) except: logging.error("Iteration %d: Result collection failed" % (i)) logging.error("Iteration %d: Rerun experiment (retry: %d)" % (i, nb_retry)) nb_retry += 1 time.sleep(5) continue if orchestrator.check_integrity(i) == False: logging.error("Iteration %d: Integrity check failed" % (i)) logging.error("Iteration %d: Rerun experiment (retry: %d)" % (i, nb_retry)) nb_retry += 1 time.sleep(5) continue iter_result = True break if iter_result is False: logging.error("Iteration %d: Still failed after %d retries" % (i, nb_retry)) return False return True def verify_results(orchestrator, rdma_verb=None, qp_index_list=None): """ Verify experiment results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations rdma_verb (str): RDMA verb to verify (default: None) qp_index_list (list): List of QP indices to verify (default: None) Returns: N/A """ result_dir = orchestrator.result_path num_repeats = orchestrator.num_repeats aggregate_pcap_filename = orchestrator.aggregate_pcap_filename if rdma_verb == None: rdma_verb = orchestrator.traffic_conf['rdma-verb'].lower().strip() if rdma_verb not in host.VALID_IB_VERB_LIST_LOWER: logging.error("Invalid RDMA verb: %s" % rdma_verb) return ## A mix of RDMA SEND and READ. Need to verify both SEND and READ if rdma_verb == 'send_read': num_qps_send, num_qps_read = [int(x) for x in orchestrator.traffic_conf['num-qps'].split(',')] verify_results(orchestrator=orchestrator, rdma_verb='send', qp_index_list=list(range(num_qps_send))) verify_results(orchestrator=orchestrator, rdma_verb='read', qp_index_list=list(range(num_qps_send, num_qps_send+num_qps_read))) return elif rdma_verb == "read": receiver_nic_type = orchestrator.requester.conf['nic']['type'] if orchestrator.requester.is_intel_nic(): receiver_np_enable = orchestrator.requester.conf['roce-parameters']['dcqcn-enable'] receiver_slow_restart = False min_time_between_cnps_us = 0 elif orchestrator.requester.is_mlnx_nic(): receiver_np_enable = orchestrator.requester.conf['roce-parameters']['dcqcn-np-enable'] receiver_slow_restart = orchestrator.requester.conf['roce-parameters']['slow-restart'] min_time_between_cnps_us = orchestrator.requester.conf['roce-parameters']['min-time-between-cnps'] else: receiver_np_enable = False receiver_slow_restart = False min_time_between_cnps_us = 0 else: receiver_nic_type = orchestrator.responder.conf['nic']['type'] if orchestrator.responder.is_intel_nic(): receiver_np_enable = orchestrator.responder.conf['roce-parameters']['dcqcn-enable'] receiver_slow_restart = False min_time_between_cnps_us = 0 elif orchestrator.responder.is_mlnx_nic(): receiver_np_enable = orchestrator.responder.conf['roce-parameters']['dcqcn-np-enable'] receiver_slow_restart = orchestrator.responder.conf['roce-parameters']['slow-restart'] min_time_between_cnps_us = orchestrator.responder.conf['roce-parameters']['min-time-between-cnps'] else: receiver_np_enable = False receiver_slow_restart = False min_time_between_cnps_us = 0 nack_trigger_cnp = cnp_check.check_nack_trigger_cnp(receiver_nic_type, receiver_np_enable, receiver_slow_restart) port_map = {'requester': orchestrator.requester.conf['nic']['switch-port'], 'responder': orchestrator.responder.conf['nic']['switch-port'], 'requester-mirror': orchestrator.requester_mirror.conf['nic']['switch-port'], 'responder-mirror': orchestrator.responder_mirror.conf['nic']['switch-port']} requester_ip_list = orchestrator.get_requester_ip_list() responder_ip_list = orchestrator.get_responder_ip_list() for iter in range(num_repeats): iter = str(iter) result_logger = logging.getLogger('Iter %s Verb %s' % (iter, rdma_verb)) result_logger.handlers.clear() config_file_handler(logger=result_logger, log_file=os.path.join(result_dir, iter, RESULT_FILENAME), no_format=True) result_logger.info("=" * 100) result_logger.info("Iteration %s Verb %s" % (iter, rdma_verb)) switch_msg_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_MESSAGE_SNAPSHOT) switch_state_snapshot = os.path.join(result_dir, iter, switch.SWITCH_RESULT_DIR, switch.SWITCH_STATE_SNAPSHOT) pcap_filename = os.path.join(result_dir, iter, host.PCAP_RESULT_DIR, aggregate_pcap_filename) requester_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_START_COUNTER_FILE_NAME) requester_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.REQ_FINISH_COUNTER_FILE_NAME) responder_counter_start = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_START_COUNTER_FILE_NAME) responder_counter_finish = os.path.join(result_dir, iter, host.RDMA_RESULT_DIR, host.RSP_FINISH_COUNTER_FILE_NAME) switch_counter = SwitchCounter(switch_state_snapshot, port_map) if orchestrator.requester.is_mlnx_nic(): requester_counter = MLNXHostCounter(requester_counter_start, requester_counter_finish) elif orchestrator.requester.is_intel_nic():
requester_counter = IntelHostCounter(requester_counter_start, requester_counter_finish)
4
2023-12-09 08:21:14+00:00
12k
Tlntin/booking_simulator
apps/agentfabric/user_core.py
[ { "identifier": "parse_configuration", "path": "config_utils.py", "snippet": "def parse_configuration(uuid_str=''):\n \"\"\"parse configuration\n\n Args:\n\n Returns:\n dict: parsed configuration\n\n \"\"\"\n model_cfg_file = os.getenv('MODEL_CONFIG_FILE', DEFAULT_MODEL_CONFIG_FILE...
import copy import os import gradio as gr from config_utils import parse_configuration from custom_prompt import (DEFAULT_EXEC_TEMPLATE, DEFAULT_SYSTEM_TEMPLATE, DEFAULT_USER_TEMPLATE, CustomPromptGenerator, parse_role_config) from langchain.embeddings import ModelScopeEmbeddings from langchain.vectorstores import FAISS from modelscope_agent.agent import AgentExecutor from modelscope_agent.agent_types import AgentType from modelscope_agent.llm import LLMFactory from modelscope_agent.retrieve import KnowledgeRetrieval from modelscope_agent.tools.openapi_plugin import OpenAPIPluginTool
8,548
# init user chatbot_agent def init_user_chatbot_agent(uuid_str=''): builder_cfg, model_cfg, tool_cfg, available_tool_list, plugin_cfg, available_plugin_list = parse_configuration( uuid_str) # set top_p and stop_words for role play model_cfg[builder_cfg.model]['generate_cfg']['top_p'] = 0.5 model_cfg[builder_cfg.model]['generate_cfg']['stop'] = 'Observation' # build model print(f'using model {builder_cfg.model}') print(f'model config {model_cfg[builder_cfg.model]}') # # check configuration # if builder_cfg.model in ['qwen-max', 'qwen-72b-api', 'qwen-14b-api', 'qwen-plus']: # if 'DASHSCOPE_API_KEY' not in os.environ: # raise gr.Error('DASHSCOPE_API_KEY should be set via setting environment variable') try: llm = LLMFactory.build_llm(builder_cfg.model, model_cfg) except Exception as e: raise gr.Error(str(e)) # build prompt with zero shot react template
# init user chatbot_agent def init_user_chatbot_agent(uuid_str=''): builder_cfg, model_cfg, tool_cfg, available_tool_list, plugin_cfg, available_plugin_list = parse_configuration( uuid_str) # set top_p and stop_words for role play model_cfg[builder_cfg.model]['generate_cfg']['top_p'] = 0.5 model_cfg[builder_cfg.model]['generate_cfg']['stop'] = 'Observation' # build model print(f'using model {builder_cfg.model}') print(f'model config {model_cfg[builder_cfg.model]}') # # check configuration # if builder_cfg.model in ['qwen-max', 'qwen-72b-api', 'qwen-14b-api', 'qwen-plus']: # if 'DASHSCOPE_API_KEY' not in os.environ: # raise gr.Error('DASHSCOPE_API_KEY should be set via setting environment variable') try: llm = LLMFactory.build_llm(builder_cfg.model, model_cfg) except Exception as e: raise gr.Error(str(e)) # build prompt with zero shot react template
instruction_template = parse_role_config(builder_cfg)
5
2023-12-12 04:24:00+00:00
12k
boweniac/autogan
autogan/agents/universal_agent.py
[ { "identifier": "AgentSwitch", "path": "autogan/agents/agent_switch.py", "snippet": "class AgentSwitch:\n def __init__(\n self,\n organizational_structure: List,\n task_tag: Optional[str] = \"/task\",\n opening_speaker: Optional[any] = None,\n de...
import re from collections import defaultdict from typing import Optional, Dict, Any from autogan.agents.agent_switch import AgentSwitch from autogan.utils.compressed_messages_utils import compressed_messages from autogan.utils.compressed_text_utils import compressed_text_universal from autogan.oai.config_utils import AgentConfig from autogan.oai.count_tokens_utils import count_text_tokens from autogan.oai.generate_utils import generate_chat_completion from autogan.utils.environment_utils import environment_info from autogan.utils.response import default_response_func from termcolor import colored
9,319
try: except ImportError: def colored(x, *args, **kwargs): return x class UniversalAgent: def __init__( self, name: str, agent_config: Optional[Dict] = None, duty: Optional[str] = None, work_flow: Optional[str] = None, use_tool: Optional[str] = None, # only | join super_rich: Optional[str] = None, # auto | on | off stream_mode: Optional[bool] = None, ): """Agent base class Each agent can communicate with other agents in the current department and the leader of the subordinate department to complete tasks together. 每个 agent 可与当前部门的其他 agent 以及下级部门的 leader 沟通,协作完成任务。 To provide functions beyond the modeling capabilities for the agent, you can override the tool_function method. 想要为 agent 提供模型能力之外的功能,可以通过重写 tool_function 方法来实现。 :param name: The agent name should be unique in the organizational structure. agent name 在组织架构中应当是唯一的。 :param agent_config: The agent configuration includes: agent 配置包括: - main_model: The LLM configuration of the agent's main body. agent 主体的 LLM 配置。 - summary_model: The LLM configuration used for compressing context and generating text summaries. 用于压缩上下文以及生成文本摘要的 LLM 配置。 - request_interval_time: The interval time of LLM requests. LLM 请求间隔时间。 - request_timeout:The timeout of LLM requests. LLM 请求超时时间。 - max_retries: The maximum number of retries for LLM requests. LLM 请求最大重试次数。 :param duty: Used to explain one's job responsibilities to other agents. 用于向其他 agent 说明自己的工作职责。 :param work_flow: Defines the workflow of the agent. 定义 agent 的工作流程。 :param use_tool: Defines the mode of the agent using the tool_function: 定义 agent 使用 tool_function 的模式: - None: means not using the tool function. 不使用工具函数。 - only: Do not use the LLM, only use the tool function to generate results. 不使用 LLM,仅使用工具函数生成结果。 - join: The content generated by the LLM will be used as the input parameter for the tool_function. LLM 生成的内容将作为 tool_function 的输入参数 :param super_rich: Whether to enable the deep thought function. When enabled, it uses a set of analysis processes to refine the output of the agent. However, this can increase the number of tokens used, so it is not recommended for use with the gpt-4 model. The name "super_rich" is a reminder that using this function with gpt-4 can be expensive, even more so than Elon Musk's earning speed. 是否开启深思功能,开启后会使用一套分析流程来收敛 agent 的输出结果,但这样做会增加 tokens 的消耗,因此不建议在gpt-4模型下使用。 之所以这个参数叫 super_rich ,是为了提醒用户,如果在 gpt-4 下使用,其花钱的速度可能会超过马斯克赚钱的速度。 - auto: Disable for GPT-4, enable for other models 在 gpt-4下禁用,其他模型开启 - on: Always enabled 始终开启 - off: Always disabled 始终关闭 :param stream_mode: Whether to enable the stream_mode 定义 agent 的工作流程。 """ self.name = name
try: except ImportError: def colored(x, *args, **kwargs): return x class UniversalAgent: def __init__( self, name: str, agent_config: Optional[Dict] = None, duty: Optional[str] = None, work_flow: Optional[str] = None, use_tool: Optional[str] = None, # only | join super_rich: Optional[str] = None, # auto | on | off stream_mode: Optional[bool] = None, ): """Agent base class Each agent can communicate with other agents in the current department and the leader of the subordinate department to complete tasks together. 每个 agent 可与当前部门的其他 agent 以及下级部门的 leader 沟通,协作完成任务。 To provide functions beyond the modeling capabilities for the agent, you can override the tool_function method. 想要为 agent 提供模型能力之外的功能,可以通过重写 tool_function 方法来实现。 :param name: The agent name should be unique in the organizational structure. agent name 在组织架构中应当是唯一的。 :param agent_config: The agent configuration includes: agent 配置包括: - main_model: The LLM configuration of the agent's main body. agent 主体的 LLM 配置。 - summary_model: The LLM configuration used for compressing context and generating text summaries. 用于压缩上下文以及生成文本摘要的 LLM 配置。 - request_interval_time: The interval time of LLM requests. LLM 请求间隔时间。 - request_timeout:The timeout of LLM requests. LLM 请求超时时间。 - max_retries: The maximum number of retries for LLM requests. LLM 请求最大重试次数。 :param duty: Used to explain one's job responsibilities to other agents. 用于向其他 agent 说明自己的工作职责。 :param work_flow: Defines the workflow of the agent. 定义 agent 的工作流程。 :param use_tool: Defines the mode of the agent using the tool_function: 定义 agent 使用 tool_function 的模式: - None: means not using the tool function. 不使用工具函数。 - only: Do not use the LLM, only use the tool function to generate results. 不使用 LLM,仅使用工具函数生成结果。 - join: The content generated by the LLM will be used as the input parameter for the tool_function. LLM 生成的内容将作为 tool_function 的输入参数 :param super_rich: Whether to enable the deep thought function. When enabled, it uses a set of analysis processes to refine the output of the agent. However, this can increase the number of tokens used, so it is not recommended for use with the gpt-4 model. The name "super_rich" is a reminder that using this function with gpt-4 can be expensive, even more so than Elon Musk's earning speed. 是否开启深思功能,开启后会使用一套分析流程来收敛 agent 的输出结果,但这样做会增加 tokens 的消耗,因此不建议在gpt-4模型下使用。 之所以这个参数叫 super_rich ,是为了提醒用户,如果在 gpt-4 下使用,其花钱的速度可能会超过马斯克赚钱的速度。 - auto: Disable for GPT-4, enable for other models 在 gpt-4下禁用,其他模型开启 - on: Always enabled 始终开启 - off: Always disabled 始终关闭 :param stream_mode: Whether to enable the stream_mode 定义 agent 的工作流程。 """ self.name = name
self.agent_config = AgentConfig(agent_config) if agent_config else None
3
2023-12-06 03:24:34+00:00
12k
JingHao99/IDR-Ingredients-oriented-Degradation-Reformulation
inference.py
[ { "identifier": "AverageMeter", "path": "utils/metric_util.py", "snippet": "class AverageMeter():\r\n \"\"\" Computes and stores the average and current value \"\"\"\r\n\r\n def __init__(self):\r\n self.reset()\r\n\r\n def reset(self):\r\n \"\"\" Reset all statistics \"\"\"\r\n ...
import argparse import subprocess import numpy as np import os import torch import torch.nn as nn import logging from tqdm import tqdm from PIL import Image from torch.utils.data import DataLoader from torch.utils.data import Dataset from torchvision.transforms import ToPILImage, Compose, RandomCrop, ToTensor from utils.metric_util import AverageMeter from utils.tensor_op import save_img_tensor, save_image_tensor from utils.util import mkdir, setup_logger from utils.data_util import crop_HWC_img, random_augmentation, tensor2img from metrics.psnr_ssim import compute_psnr_ssim, calculate_psnr, calculate_ssim from models.archs.IDR_restormer_arch import IDR_restormer
7,498
self._init_input_ids() def _edgeComputation(self,x): x_diffx = np.abs(x[:,1:,:] - x[:,:-1,:]) x_diffy = np.abs(x[1:,:,:] - x[:-1,:,:]) y = np.zeros_like(x) y[:,1:,:] += x_diffx y[:,:-1,:] += x_diffx y[1:,:,:] += x_diffy y[:-1,:,:] += x_diffy y = np.sum(y,2)/3 y /= 4 return y[:,:,None].astype(np.float32) def __getitem__(self, idx): degraded_path = self.ids[idx] clean_path = self._get_gt_path(degraded_path) degraded_img = crop_HWC_img(np.array(Image.open(degraded_path).convert('RGB')), base=32) clean_img = crop_HWC_img(np.array(Image.open(clean_path).convert('RGB')), base=32) clean_img, degraded_img = self.toTensor(clean_img), self.toTensor(degraded_img) degraded_name = degraded_path.split('/')[-1][:-4] return [degraded_name], degraded_img, clean_img def __len__(self): return self.length def test_Denoise(net, dataset, task="CBSD68", sigma=15,save_img=True): logger = logging.getLogger('base') output_path = opt.output_path + 'denoise/' + str(sigma) + '/' # subprocess.check_output(['mkdir', '-p', output_path]) mkdir(output_path) dataset.set_dataset(task) dataset.set_sigma(sigma) testloader = DataLoader(dataset, batch_size=1, pin_memory=True, shuffle=False, num_workers=0) psnr = AverageMeter() ssim = AverageMeter() with torch.no_grad(): for ([clean_name], degrad_patch, clean_patch) in tqdm(testloader): degrad_patch, clean_patch = degrad_patch.cuda(), clean_patch.cuda() restored = net(degrad_patch) if type(restored) == list: restored = restored[0] temp_psnr, temp_ssim, N = compute_psnr_ssim(restored, clean_patch) psnr.update(temp_psnr, N) ssim.update(temp_ssim, N) if save_img: save_image_tensor(restored, output_path + clean_name[0] + '.png') logger.info("Deonise sigma=%d: psnr: %.2f, ssim: %.4f" % (sigma, psnr.avg, ssim.avg)) def test_Derain_Dehaze(net, dataset, task="derain",save_img=True): logger = logging.getLogger('base') output_path = opt.output_path + task + '/' # subprocess.check_output(['mkdir', '-p', output_path]) mkdir(output_path) dataset.set_dataset(task) testloader = DataLoader(dataset, batch_size=1, pin_memory=True, shuffle=False, num_workers=0) psnr = AverageMeter() ssim = AverageMeter() with torch.no_grad(): for ([degraded_name], degrad_patch, clean_patch) in tqdm(testloader): degrad_patch, clean_patch = degrad_patch.cuda(), clean_patch.cuda() restored = net(degrad_patch) if type(restored) == list: restored = restored[0] temp_psnr, temp_ssim, N = compute_psnr_ssim(restored, clean_patch) N = degrad_patch.shape[0] psnr.update(temp_psnr, N) ssim.update(temp_ssim, N) if save_img: save_image_tensor(restored, output_path + degraded_name[0] + '.png') logger.info("PSNR: %.2f, SSIM: %.4f" % (psnr.avg, ssim.avg)) if __name__ == '__main__': parser = argparse.ArgumentParser() # Input Parameters parser.add_argument('--cuda', type=int, default=0) parser.add_argument('--mode', type=int, default=0, help='0 for 5 tasks, 1 for denoising details, 2 for unknowing UDC') parser.add_argument('--denoise_CBSD68_path', type=str, default="", help='save path of test noisy images') parser.add_argument('--denoise_urban100_path', type=str, default="", help='save path of test noisy images') parser.add_argument('--denoise_Kodak24_path', type=str, default="", help='save path of test noisy images') parser.add_argument('--derain_path', type=str, default="", help='save path of test raining images') parser.add_argument('--dehaze_path', type=str, default="", help='save path of test hazy images') parser.add_argument('--deblur_path', type=str, default="", help='save path of test blur images') parser.add_argument('--low_light_path', type=str, default="", help='save path of test low-light images') parser.add_argument('--udc_T_path', type=str, default="", help='save path of test udc Toled images') parser.add_argument('--udc_P_path', type=str, default="", help='save path of test udc Poled images') parser.add_argument('--output_path', type=str, default="./results/visualization", help='output save path') parser.add_argument('--ckpt_path', type=str, default="", help='checkpoint save path') parser.add_argument('--log_path', type=str, default="./results/log", help='checkpoint save path') opt = parser.parse_args() np.random.seed(0) torch.manual_seed(0) torch.cuda.set_device(opt.cuda) denoise_set = DenoiseTestDataset(opt) derain_set = DerainDehazeDataset(opt) # Make network
class DenoiseTestDataset(Dataset): def __init__(self, args, dataset="CBSD68"): super(DenoiseTestDataset, self).__init__() self.args = args self.clean_ids = [] self.sigma = 15 self.dataset_dict = {'CBSD68': 0, 'urban100': 1, 'Kodak24':2} self.set_dataset(dataset) self.toTensor = ToTensor() def _init_clean_ids(self): if self.task_idx == 0: self.clean_ids = [] name_list = os.listdir(self.args.denoise_CBSD68_path) self.clean_ids += [self.args.denoise_CBSD68_path + id_ for id_ in name_list] elif self.task_idx == 1: self.clean_ids = [] name_list = os.listdir(self.args.denoise_urban100_path) self.clean_ids += [self.args.denoise_urban100_path + id_ for id_ in name_list] elif self.task_idx == 2: self.clean_ids = [] name_list = os.listdir(self.args.denoise_Kodak24_path) self.clean_ids += [self.args.denoise_Kodak24_path + id_ for id_ in name_list] self.num_clean = len(self.clean_ids) def set_dataset(self, dataset): self.task_idx = self.dataset_dict[dataset] self._init_clean_ids() def _add_gaussian_noise(self, clean_patch): noise = np.random.randn(*clean_patch.shape) noisy_patch = np.clip(clean_patch + noise * self.sigma, 0, 255).astype(np.uint8) return noisy_patch, clean_patch def _edgeComputation(self,x): x_diffx = np.abs(x[:,1:,:] - x[:,:-1,:]) x_diffy = np.abs(x[1:,:,:] - x[:-1,:,:]) y = np.zeros_like(x) y[:,1:,:] += x_diffx y[:,:-1,:] += x_diffx y[1:,:,:] += x_diffy y[:-1,:,:] += x_diffy y = np.sum(y,2)/3 y /= 4 return y[:,:,None].astype(np.float32) def set_sigma(self, sigma): self.sigma = sigma def __getitem__(self, clean_id): clean_img = crop_HWC_img(np.array(Image.open(self.clean_ids[clean_id]).convert('RGB')), base=32) clean_name = self.clean_ids[clean_id].split("/")[-1].split('.')[0] noisy_img, _ = self._add_gaussian_noise(clean_img) clean_img, noisy_img = self.toTensor(clean_img), self.toTensor(noisy_img) return [clean_name], noisy_img, clean_img def __len__(self): return self.num_clean class DerainDehazeDataset(Dataset): def __init__(self, args, task="derain"): super(DerainDehazeDataset, self).__init__() self.ids = [] self.task_idx = 0 self.args = args self.task_dict = {'derain': 0, 'dehaze': 1, 'deblur':2, 'low-light':3, 'UDC_T':4, 'UDC_P':5} self.toTensor = ToTensor() self.set_dataset(task) def _init_input_ids(self): if self.task_idx == 0: self.ids = [] name_list = os.listdir(self.args.derain_path + 'input/') self.ids += [self.args.derain_path + 'input/' + id_ for id_ in name_list] elif self.task_idx == 1: self.ids = [] name_list = os.listdir(self.args.dehaze_path + 'input/') self.ids += [self.args.dehaze_path + 'input/' + id_ for id_ in name_list] elif self.task_idx == 2: self.ids = [] name_list = os.listdir(self.args.deblur_path + 'input/') self.ids += [self.args.deblur_path + 'input/' + id_ for id_ in name_list] elif self.task_idx == 3: self.ids = [] name_list = os.listdir(self.args.low_light_path + 'input/') self.ids += [self.args.low_light_path + 'input/' + id_ for id_ in name_list] elif self.task_idx == 4: self.ids = [] name_list = os.listdir(self.args.udc_T_path + 'input/') self.ids += [self.args.udc_T_path + 'input/' + id_ for id_ in name_list] elif self.task_idx == 5: self.ids = [] name_list = os.listdir(self.args.udc_P_path + 'input/') self.ids += [self.args.udc_P_path + 'input/' + id_ for id_ in name_list] self.length = len(self.ids) def _get_gt_path(self, degraded_name): if self.task_idx == 0: gt_name = degraded_name.replace("input", "target") elif self.task_idx == 1: dir_name = degraded_name.split("input")[0] + 'target/' name = degraded_name.split('/')[-1].split('_')[0] + '.png' gt_name = dir_name + name elif self.task_idx == 2: gt_name = degraded_name.replace("input", "target") elif self.task_idx == 3: gt_name = degraded_name.replace("input", "target") elif self.task_idx == 4: gt_name = degraded_name.replace("input", "target") elif self.task_idx == 5: gt_name = degraded_name.replace("input", "target") return gt_name def set_dataset(self, task): self.task_idx = self.task_dict[task] self._init_input_ids() def _edgeComputation(self,x): x_diffx = np.abs(x[:,1:,:] - x[:,:-1,:]) x_diffy = np.abs(x[1:,:,:] - x[:-1,:,:]) y = np.zeros_like(x) y[:,1:,:] += x_diffx y[:,:-1,:] += x_diffx y[1:,:,:] += x_diffy y[:-1,:,:] += x_diffy y = np.sum(y,2)/3 y /= 4 return y[:,:,None].astype(np.float32) def __getitem__(self, idx): degraded_path = self.ids[idx] clean_path = self._get_gt_path(degraded_path) degraded_img = crop_HWC_img(np.array(Image.open(degraded_path).convert('RGB')), base=32) clean_img = crop_HWC_img(np.array(Image.open(clean_path).convert('RGB')), base=32) clean_img, degraded_img = self.toTensor(clean_img), self.toTensor(degraded_img) degraded_name = degraded_path.split('/')[-1][:-4] return [degraded_name], degraded_img, clean_img def __len__(self): return self.length def test_Denoise(net, dataset, task="CBSD68", sigma=15,save_img=True): logger = logging.getLogger('base') output_path = opt.output_path + 'denoise/' + str(sigma) + '/' # subprocess.check_output(['mkdir', '-p', output_path]) mkdir(output_path) dataset.set_dataset(task) dataset.set_sigma(sigma) testloader = DataLoader(dataset, batch_size=1, pin_memory=True, shuffle=False, num_workers=0) psnr = AverageMeter() ssim = AverageMeter() with torch.no_grad(): for ([clean_name], degrad_patch, clean_patch) in tqdm(testloader): degrad_patch, clean_patch = degrad_patch.cuda(), clean_patch.cuda() restored = net(degrad_patch) if type(restored) == list: restored = restored[0] temp_psnr, temp_ssim, N = compute_psnr_ssim(restored, clean_patch) psnr.update(temp_psnr, N) ssim.update(temp_ssim, N) if save_img: save_image_tensor(restored, output_path + clean_name[0] + '.png') logger.info("Deonise sigma=%d: psnr: %.2f, ssim: %.4f" % (sigma, psnr.avg, ssim.avg)) def test_Derain_Dehaze(net, dataset, task="derain",save_img=True): logger = logging.getLogger('base') output_path = opt.output_path + task + '/' # subprocess.check_output(['mkdir', '-p', output_path]) mkdir(output_path) dataset.set_dataset(task) testloader = DataLoader(dataset, batch_size=1, pin_memory=True, shuffle=False, num_workers=0) psnr = AverageMeter() ssim = AverageMeter() with torch.no_grad(): for ([degraded_name], degrad_patch, clean_patch) in tqdm(testloader): degrad_patch, clean_patch = degrad_patch.cuda(), clean_patch.cuda() restored = net(degrad_patch) if type(restored) == list: restored = restored[0] temp_psnr, temp_ssim, N = compute_psnr_ssim(restored, clean_patch) N = degrad_patch.shape[0] psnr.update(temp_psnr, N) ssim.update(temp_ssim, N) if save_img: save_image_tensor(restored, output_path + degraded_name[0] + '.png') logger.info("PSNR: %.2f, SSIM: %.4f" % (psnr.avg, ssim.avg)) if __name__ == '__main__': parser = argparse.ArgumentParser() # Input Parameters parser.add_argument('--cuda', type=int, default=0) parser.add_argument('--mode', type=int, default=0, help='0 for 5 tasks, 1 for denoising details, 2 for unknowing UDC') parser.add_argument('--denoise_CBSD68_path', type=str, default="", help='save path of test noisy images') parser.add_argument('--denoise_urban100_path', type=str, default="", help='save path of test noisy images') parser.add_argument('--denoise_Kodak24_path', type=str, default="", help='save path of test noisy images') parser.add_argument('--derain_path', type=str, default="", help='save path of test raining images') parser.add_argument('--dehaze_path', type=str, default="", help='save path of test hazy images') parser.add_argument('--deblur_path', type=str, default="", help='save path of test blur images') parser.add_argument('--low_light_path', type=str, default="", help='save path of test low-light images') parser.add_argument('--udc_T_path', type=str, default="", help='save path of test udc Toled images') parser.add_argument('--udc_P_path', type=str, default="", help='save path of test udc Poled images') parser.add_argument('--output_path', type=str, default="./results/visualization", help='output save path') parser.add_argument('--ckpt_path', type=str, default="", help='checkpoint save path') parser.add_argument('--log_path', type=str, default="./results/log", help='checkpoint save path') opt = parser.parse_args() np.random.seed(0) torch.manual_seed(0) torch.cuda.set_device(opt.cuda) denoise_set = DenoiseTestDataset(opt) derain_set = DerainDehazeDataset(opt) # Make network
net = IDR_restormer(inp_channels=3, out_channels=3, dim=24, num_blocks=[2,3,3,4], num_refinement_blocks=2, heads=[1,2,4,8], ffn_expansion_factor=2.66, bias=False, LayerNorm_type='WithBias', num_degra_queries = 24, keep_degra=48)
11
2023-12-07 10:58:34+00:00
12k
neu-spiral/multi-label-emg
multi_label_emg/train.py
[ { "identifier": "load_data_dict", "path": "multi_label_emg/data.py", "snippet": "def load_data_dict():\n \"\"\"\n Loads features and labels from subject folders into a single dictionary as described below.\n NOTE - preprocessing should be been done first to extract features from raw data (see R...
import sys import numpy as np import plotly.graph_objects as go import argparse from loguru import logger from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.mixture import GaussianMixture from sklearn.neighbors import KernelDensity, KNeighborsClassifier from sklearn.neural_network import MLPClassifier from sklearn.pipeline import make_pipeline from sklearn.preprocessing import RobustScaler from sklearn.svm import SVC from multi_label_emg.data import load_data_dict from multi_label_emg.models import AvgPairs, ElementwiseMaxPairs, ParallelA, ParallelB from multi_label_emg.utils import ( NO_DIR_IDX, NO_MOD_IDX, RESULTS_DIR, canonical_coords, confusion_matrix, str2bool, )
7,823
# Don't use "Feedback" blocks for this analysis test_blocks = ["HoldPulse3_NoFeedBack", "SimultaneousPulse3_NoFeedBack"] test_features = np.concatenate([data[f"{block}_features"] for block in test_blocks]) test_dir_labels = np.concatenate([data[f"{block}_dir_labels"] for block in test_blocks]) test_mod_labels = np.concatenate([data[f"{block}_mod_labels"] for block in test_blocks]) logger.info(f"test set: {test_features.shape=}, {test_dir_labels.shape=}, {test_mod_labels.shape=}") # Vary strategy for augmented doubles double_features_aug, double_dir_labels_aug, double_mod_labels_aug = get_augmented_doubles( doubles_method, feature_combine_type, fraction_doubles_per_class, train_features, train_dir_labels, train_mod_labels, ) # Make augmented singles # Figure out how many doubles per class. Take avg and then apply rel_fraction_singles_per_class to # get the number of singles per class n_singles_per_class = 0 if singles_method != "none": doubles_labels_2d = np.stack((double_dir_labels_aug.argmax(-1), double_mod_labels_aug.argmax(-1)), axis=-1) class_sizes = np.unique(doubles_labels_2d, axis=0, return_counts=True)[-1] n_singles_per_class = int(np.round(np.mean(class_sizes) * rel_fraction_singles_per_class)) single_features_aug, single_dir_labels_aug, single_mod_labels_aug = get_augmented_singles( singles_method, n_singles_per_class, train_features, train_dir_labels, train_mod_labels ) # Merge all train data train_features = np.concatenate([train_features, double_features_aug, single_features_aug]) train_dir_labels = np.concatenate([train_dir_labels, double_dir_labels_aug, single_dir_labels_aug]) train_mod_labels = np.concatenate([train_mod_labels, double_mod_labels_aug, single_mod_labels_aug]) logger.info(f"Augmented train set: {train_features.shape=}, {train_dir_labels.shape=}, {train_mod_labels.shape=}") # Create model if parallel_model_type == "ParallelA": model = ParallelA( get_clf(clf_name, num_classes=5), get_clf(clf_name, num_classes=3), use_augmentation=False, include_rest_data_for_clf=True, ) elif parallel_model_type == "ParallelB": model = ParallelB( dir_clf=get_clf(clf_name, num_classes=4), mod_clf=get_clf(clf_name, num_classes=2), has_dir_clf=get_clf(clf_name, num_classes=2), has_mod_clf=get_clf(clf_name, num_classes=2), use_augmentation=False, # include_rest_data_for_clf=True, # NOTE - always using true, flag is not in model ) elif parallel_model_type == "SerialControl": model = get_clf(clf_name, num_classes=15) else: raise ValueError(f"Unknown parallel model type: {parallel_model_type}") # Train logger.info("Train...") if parallel_model_type == "SerialControl": # Convert labels to integer by making 2-digit numbers, # where the 10s place is the dir label and the 1s place is the mod label train_labels = train_dir_labels.argmax(-1) * 10 + train_mod_labels.argmax(-1) model.fit(train_features, train_labels) else: model.fit(train_features, train_dir_labels, train_mod_labels) # Evaluate logger.info("Evaluate") if parallel_model_type == "SerialControl": combined_preds = model.predict(test_features) dir_preds = combined_preds // 10 mod_preds = combined_preds % 10 else: dir_preds, mod_preds = model.predict(test_features) preds_2d = np.stack([dir_preds, mod_preds], axis=-1) true_labels_2d = np.stack([test_dir_labels.argmax(-1), test_mod_labels.argmax(-1)], axis=-1) return confusion_matrix(true_labels_2d, preds_2d) if __name__ == "__main__": logger.remove() logger.add(sys.stdout, level="INFO", colorize=True) parser = argparse.ArgumentParser() parser.add_argument("--subject", type=str, required=True) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--parallel_model_type", choices=["ParallelA", "ParallelB", "SerialControl"], required=True) clf_names = ["mlp", "rf", "logr"] parser.add_argument("--clf_name", type=str, choices=clf_names, required=True) doubles_methods = [ "none", "subset_uniform", "subset_near_mean", "subset_spaced_quantiles", "subsetInput_uniform", "subsetInput_near_mean", "subsetInput_spaced_quantiles", "all", ] parser.add_argument("--doubles_method", type=str, choices=doubles_methods, required=True) parser.add_argument("--fraction_doubles_per_class", type=float, required=True) singles_methods = [ "none", "add-gaussian-0.3", "add-gaussian-0.4", "add-gaussian-0.5", "fit-gmm-1", "fit-gmm-5", "fit-gmm-10", "fit-kde-gaussian-silverman", "fit-kde-gaussian-0.01", "fit-kde-gaussian-0.1", "fit-kde-gaussian-1.0", ] parser.add_argument("--singles_method", type=str, choices=singles_methods, required=True) parser.add_argument("--rel_fraction_singles_per_class", type=float, required=True)
def get_name( subject: str, seed: int, parallel_model_type: str, clf_name: str, doubles_method: str, fraction_doubles_per_class: float, singles_method: str, rel_fraction_singles_per_class: float, include_doubles_in_train: bool, feature_combine_type: str, ): return "__".join( [ f"subj={subject}", f"seed={seed}", f"par={parallel_model_type}", f"clf={clf_name}", f"doubles={doubles_method}", f"frac_doubles={fraction_doubles_per_class}", f"singles={singles_method}", f"frac_singles={rel_fraction_singles_per_class}", f"incl_doubles={include_doubles_in_train}", f"feat_type={feature_combine_type}", ] ) def plot_confusion_matrix(data: np.ndarray): def make_text(cm): text = [] for v in cm.flatten(): text.append(f"{round(v, 2)}") return np.array(text).reshape(cm.shape) coords, coords_str = canonical_coords() text = make_text(data) fig = go.Figure() fig.update_layout( # margin=margin, xaxis=dict( title="Predicted", tickangle=-45, tickmode="array", ticktext=coords_str, tickvals=list(range(len(coords_str))), constrain="domain", ), yaxis=dict( title="Actual", tickmode="array", ticktext=coords_str, tickvals=list(range(len(coords_str))), autorange="reversed", scaleanchor="x", scaleratio=1, constrain="domain", ), ) fig.add_trace( go.Heatmap(z=data, text=text, texttemplate="%{text}", zmin=0, zmax=1, colorscale="Blues", showscale=False) ) return fig def subset_doubles_uniform( n_per_class: int, features_aug: np.ndarray, dir_labels_aug: np.ndarray, mod_labels_aug: np.ndarray ): """For each class, take n_per_class items uniformly at random""" res_x, res_y_dir, res_y_mod = [], [], [] labels_2d = np.stack([dir_labels_aug.argmax(-1), mod_labels_aug.argmax(-1)], axis=-1) for d, m in np.unique(labels_2d, axis=0): idx = np.where((labels_2d == (d, m)).all(-1))[0] subset_idx = np.random.choice(idx, size=n_per_class, replace=False) res_x.append(features_aug[subset_idx]) res_y_dir.append(dir_labels_aug[subset_idx]) res_y_mod.append(mod_labels_aug[subset_idx]) features_aug = np.concatenate(res_x) dir_labels_aug = np.concatenate(res_y_dir) mod_labels_aug = np.concatenate(res_y_mod) return features_aug, dir_labels_aug, mod_labels_aug def subset_doubles_near_mean( n_per_class: int, features_aug: np.ndarray, dir_labels_aug: np.ndarray, mod_labels_aug: np.ndarray ): """For each class, take n_per_class items closest to the mean of these synthetic items""" # Find class means class_means = {} labels_2d = np.stack([dir_labels_aug.argmax(-1), mod_labels_aug.argmax(-1)], axis=-1) for d, m in np.unique(labels_2d, axis=0): idx = np.where((labels_2d == (d, m)).all(-1))[0] class_means[(d, m)] = np.mean(features_aug[idx], axis=0) # Subset each class by taking items closest to mean res_x, res_y_dir, res_y_mod = [], [], [] for d, m in np.unique(labels_2d, axis=0): class_mean = class_means[(d, m)] idx = np.where((labels_2d == (d, m)).all(-1))[0] dists = np.linalg.norm(features_aug[idx] - class_mean, axis=-1) k_smallest_idx = np.argpartition(dists, n_per_class)[:n_per_class] subset_idx = idx[k_smallest_idx] res_x.append(features_aug[subset_idx]) res_y_dir.append(dir_labels_aug[subset_idx]) res_y_mod.append(mod_labels_aug[subset_idx]) features_aug = np.concatenate(res_x) dir_labels_aug = np.concatenate(res_y_dir) mod_labels_aug = np.concatenate(res_y_mod) return features_aug, dir_labels_aug, mod_labels_aug def subset_doubles_spaced_quantiles( n_per_class: int, features_aug: np.ndarray, dir_labels_aug: np.ndarray, mod_labels_aug: np.ndarray ): """For each class, rank items by their distance to the class mean, and take items with ranks 1, K+1, 2K+1. The spacing K will be approx (class_size / n_per_class) """ # Find class means class_means = {} labels_2d = np.stack([dir_labels_aug.argmax(-1), mod_labels_aug.argmax(-1)], axis=-1) for d, m in np.unique(labels_2d, axis=0): idx = np.where((labels_2d == (d, m)).all(-1))[0] class_means[(d, m)] = np.mean(features_aug[idx], axis=0) # Subset each class by taking items closest to mean res_x, res_y_dir, res_y_mod = [], [], [] for d, m in np.unique(labels_2d, axis=0): class_mean = class_means[(d, m)] idx = np.where((labels_2d == (d, m)).all(-1))[0] dists = np.linalg.norm(features_aug[idx] - class_mean, axis=-1) ranked_distances = np.argsort(dists) spacing = int(np.floor(len(idx) / n_per_class)) # Since we use floor, we step slightly too little. # In case this gives us extra items, we also truncate. subset_idx = idx[ranked_distances[::spacing][:n_per_class]] n_subset = len(subset_idx) assert abs(n_subset - n_per_class) <= 1 res_x.append(features_aug[subset_idx]) res_y_dir.append(dir_labels_aug[subset_idx]) res_y_mod.append(mod_labels_aug[subset_idx]) features_aug = np.concatenate(res_x) dir_labels_aug = np.concatenate(res_y_dir) mod_labels_aug = np.concatenate(res_y_mod) return features_aug, dir_labels_aug, mod_labels_aug def subset_dir_mod( method: str, fraction_doubles_per_class: float, features: np.ndarray, dir_labels: np.ndarray, mod_labels: np.ndarray ): # Should have 1-hot vector labels assert dir_labels.ndim == 2 assert mod_labels.ndim == 2 # check these are all singles items_with_dir = dir_labels.argmax(-1) != NO_DIR_IDX items_with_mod = mod_labels.argmax(-1) != NO_MOD_IDX items_with_both = np.logical_and(items_with_dir, items_with_mod) assert np.sum(items_with_both) == 0 labels_2d = np.stack([dir_labels.argmax(-1), mod_labels.argmax(-1)], axis=-1) # Figure out how many items we have per class # Then use fraction_doubles_per_class to figure out how many doubles we want class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] n_per_class = int(np.round(fraction_doubles_per_class * np.mean(class_sizes))) n_per_class = min(n_per_class, np.min(class_sizes)) logger.info(f"Initial class sizes: {class_sizes}, n_per_class: {n_per_class}") # For each class, fit a multivariate gaussian and sample the requested number of points res_x, res_y_dir, res_y_mod = [], [], [] for d, m in np.unique(labels_2d, axis=0): idx = np.where((labels_2d == (d, m)).all(-1))[0] class_mean = np.mean(features[idx], axis=0) if method == "subsetInput_uniform": subset_idx = np.random.choice(idx, n_per_class, replace=False) elif method == "subsetInput_near_mean": dists = np.linalg.norm(features[idx] - class_mean, axis=-1) ranked_distances = np.argsort(dists) subset_idx = idx[ranked_distances[:n_per_class]] elif method == "subsetInput_spaced_quantiles": dists = np.linalg.norm(features[idx] - class_mean, axis=-1) ranked_distances = np.argsort(dists) spacing = int(np.floor(len(idx) / n_per_class)) # Since we use floor, we step slightly too little. # In case this gives us extra items, we also truncate. subset_idx = idx[ranked_distances[::spacing][:n_per_class]] n_subset = len(subset_idx) assert abs(n_subset - n_per_class) <= 1 res_x.append(features[subset_idx]) res_y_dir.append(dir_labels[subset_idx]) res_y_mod.append(mod_labels[subset_idx]) res_x = np.concatenate(res_x) res_y_dir = np.concatenate(res_y_dir) res_y_mod = np.concatenate(res_y_mod) labels_2d = np.stack([res_y_dir.argmax(-1), res_y_mod.argmax(-1)], axis=-1) class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] logger.info(f"Class sizes after subset: {class_sizes}") return res_x, res_y_dir, res_y_mod def get_augmented_doubles( method: str, feature_combine_type: str, fraction_doubles_per_class: float, features: np.ndarray, dir_labels: np.ndarray, mod_labels: np.ndarray, ): if feature_combine_type == "avg": aug = AvgPairs(-1) elif feature_combine_type == "max": aug = ElementwiseMaxPairs(-1) else: raise ValueError(f"Unknown feature_combine_type: {feature_combine_type}") if method == "none": logger.info("No synthetic doubles") # We create nothing and return early features_aug = np.empty((0, *features.shape[1:])) dir_labels_aug = np.empty((0, *dir_labels.shape[1:])) mod_labels_aug = np.empty((0, *mod_labels.shape[1:])) return features_aug, dir_labels_aug, mod_labels_aug if method.startswith("subsetInput"): # NOTE - here, n_per_class means how many items in each INPUT class # Do the subsetting before making combinations logger.info("Subset before creating doubles") features_subset, dir_labels_subset, mod_labels_subset = subset_dir_mod( method, fraction_doubles_per_class, features, dir_labels, mod_labels ) features_aug, dir_labels_aug, mod_labels_aug = aug(features_subset, dir_labels_subset, mod_labels_subset) labels_2d = np.stack([dir_labels_aug.argmax(-1), mod_labels_aug.argmax(-1)], axis=-1) class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] logger.info(f"Final synthetic double class sizes: {class_sizes}") return features_aug, dir_labels_aug, mod_labels_aug # Other methods create all combinations and THEN subset # First, create all augmented items logger.info("Subset after creating doubles") features_aug, dir_labels_aug, mod_labels_aug = aug(features, dir_labels, mod_labels) labels_2d = np.stack([dir_labels_aug.argmax(-1), mod_labels_aug.argmax(-1)], axis=-1) class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] logger.info(f"Initial synthetic double class sizes: {class_sizes}") # check these are all doubles items_with_dir = dir_labels_aug.argmax(-1) != NO_DIR_IDX items_with_mod = mod_labels_aug.argmax(-1) != NO_MOD_IDX items_with_both = np.logical_and(items_with_dir, items_with_mod) assert np.sum(items_with_both) == len(features_aug) # Figure out how many items we want per class n_per_class = int(np.round(fraction_doubles_per_class * np.mean(class_sizes))) n_per_class = min(n_per_class, np.min(class_sizes)) # Then, subset as requested if method == "all": pass elif method == "subset_uniform": features_aug, dir_labels_aug, mod_labels_aug = subset_doubles_uniform( n_per_class, features_aug, dir_labels_aug, mod_labels_aug ) elif method == "subset_near_mean": features_aug, dir_labels_aug, mod_labels_aug = subset_doubles_near_mean( n_per_class, features_aug, dir_labels_aug, mod_labels_aug ) elif method == "subset_spaced_quantiles": features_aug, dir_labels_aug, mod_labels_aug = subset_doubles_spaced_quantiles( n_per_class, features_aug, dir_labels_aug, mod_labels_aug ) else: raise ValueError(f"Unknown augmentation method: {method}") labels_2d = np.stack([dir_labels_aug.argmax(-1), mod_labels_aug.argmax(-1)], axis=-1) class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] logger.info(f"Final synthetic double class sizes: {class_sizes}") return features_aug, dir_labels_aug, mod_labels_aug def get_noise_simple(x, relative_std): """Add noise to x, where the noise standard deviation is relative_std * x.std()""" return np.random.randn(*x.shape) * relative_std * x.std(0) def balanced_sample_singles(features, dir_labels, mod_labels, n_per_class): # Should have 1-hot vector labels assert dir_labels.ndim == 2 assert mod_labels.ndim == 2 # check these are all singles items_with_dir = dir_labels.argmax(-1) != NO_DIR_IDX items_with_mod = mod_labels.argmax(-1) != NO_MOD_IDX items_with_both = np.logical_and(items_with_dir, items_with_mod) assert np.sum(items_with_both) == 0 labels_2d = np.stack([dir_labels.argmax(-1), mod_labels.argmax(-1)], axis=-1) res_x, res_y_dir, res_y_mod = [], [], [] for d, m in np.unique(labels_2d, axis=0): idx = np.where((labels_2d == (d, m)).all(-1))[0] n_needed = n_per_class selected_idx = [] while True: if n_needed >= len(idx): # Take all items in this class 1 more time selected_idx.append(idx) n_needed -= len(idx) else: # Take the remaining items randomly selected_idx.append(np.random.choice(idx, n_needed, replace=False)) break selected_idx = np.concatenate(selected_idx) res_x.append(features[selected_idx]) res_y_dir.append(dir_labels[selected_idx]) res_y_mod.append(mod_labels[selected_idx]) return np.concatenate(res_x), np.concatenate(res_y_dir), np.concatenate(res_y_mod) def sample_singles_gmm(features, dir_labels, mod_labels, n_per_class, n_components): """Fit a GMM to each class, then sample as requested""" assert dir_labels.ndim == 2 assert mod_labels.ndim == 2 # check these are all singles items_with_dir = dir_labels.argmax(-1) != NO_DIR_IDX items_with_mod = mod_labels.argmax(-1) != NO_MOD_IDX items_with_both = np.logical_and(items_with_dir, items_with_mod) assert np.sum(items_with_both) == 0 labels_2d = np.stack([dir_labels.argmax(-1), mod_labels.argmax(-1)], axis=-1) # For each class, fit a multivariate gaussian and sample the requested number of points res_x, res_y_dir, res_y_mod = [], [], [] for d, m in np.unique(labels_2d, axis=0): # NOTE - d and m are now integer values. We need to convert them to 1-hot vectors for the output d_onehot = np.zeros(dir_labels.shape[1]) d_onehot[d] = 1 m_onehot = np.zeros(mod_labels.shape[1]) m_onehot[m] = 1 idx = np.where((labels_2d == (d, m)).all(-1))[0] gmm = GaussianMixture(n_components=n_components) gmm.fit(features[idx]) res_x.append(gmm.sample(n_per_class)[0]) res_y_dir.append(np.tile(d_onehot, (n_per_class, 1))) res_y_mod.append(np.tile(m_onehot, (n_per_class, 1))) return np.concatenate(res_x), np.concatenate(res_y_dir), np.concatenate(res_y_mod) def sample_singles_kde(features, dir_labels, mod_labels, n_per_class, bandwidth): """Fit a GMM to each class, then sample as requested""" assert dir_labels.ndim == 2 assert mod_labels.ndim == 2 # check these are all singles items_with_dir = dir_labels.argmax(-1) != NO_DIR_IDX items_with_mod = mod_labels.argmax(-1) != NO_MOD_IDX items_with_both = np.logical_and(items_with_dir, items_with_mod) assert np.sum(items_with_both) == 0 labels_2d = np.stack([dir_labels.argmax(-1), mod_labels.argmax(-1)], axis=-1) # For each class, fit a multivariate gaussian and sample the requested number of points res_x, res_y_dir, res_y_mod = [], [], [] for d, m in np.unique(labels_2d, axis=0): # NOTE - d and m are now integer values. We need to convert them to 1-hot vectors for the output d_onehot = np.zeros(dir_labels.shape[1]) d_onehot[d] = 1 m_onehot = np.zeros(mod_labels.shape[1]) m_onehot[m] = 1 idx = np.where((labels_2d == (d, m)).all(-1))[0] kde = KernelDensity(bandwidth=bandwidth) kde.fit(features[idx]) res_x.append(kde.sample(n_per_class)) res_y_dir.append(np.tile(d_onehot, (n_per_class, 1))) res_y_mod.append(np.tile(m_onehot, (n_per_class, 1))) return np.concatenate(res_x), np.concatenate(res_y_dir), np.concatenate(res_y_mod) def get_augmented_singles( method: str, n_per_class: int, features: np.ndarray, dir_labels: np.ndarray, mod_labels: np.ndarray ): if method == "none": logger.info("No augmented singles") # Return empties so we can just concatenate and not worry about it features_aug = np.empty((0, *features.shape[1:])) dir_labels_aug = np.empty((0, *dir_labels.shape[1:])) mod_labels_aug = np.empty((0, *mod_labels.shape[1:])) return features_aug, dir_labels_aug, mod_labels_aug logger.info(f"Augmenting singles with method {method}") if method.startswith("add-gaussian"): # First, choose a subset of items according to n_per_class features, dir_labels_aug, mod_labels_aug = balanced_sample_singles( features, dir_labels, mod_labels, n_per_class ) if method == "add-gaussian-0.05": factor = 0.05 elif method == "add-gaussian-0.1": factor = 0.1 elif method == "add-gaussian-0.2": factor = 0.2 elif method == "add-gaussian-0.3": factor = 0.3 elif method == "add-gaussian-0.4": factor = 0.4 elif method == "add-gaussian-0.5": factor = 0.5 elif method == "add-gaussian-0.6": factor = 0.6 else: raise ValueError(f"Unknown gaussian factor: {method}") features_aug = features + get_noise_simple(features, factor) elif method.startswith("fit-gmm"): if method == "fit-gmm-1": nc = 1 elif method == "fit-gmm-3": nc = 3 elif method == "fit-gmm-5": nc = 5 elif method == "fit-gmm-10": nc = 10 features_aug, dir_labels_aug, mod_labels_aug = sample_singles_gmm( features, dir_labels, mod_labels, n_per_class, n_components=nc ) elif method.startswith("fit-kde"): if method == "fit-kde-gaussian-scott": bandwidth = "scott" if method == "fit-kde-gaussian-silverman": bandwidth = "silverman" if method == "fit-kde-gaussian-0.01": bandwidth = 0.01 if method == "fit-kde-gaussian-0.1": bandwidth = 0.1 if method == "fit-kde-gaussian-1.0": bandwidth = 1.0 if method == "fit-kde-gaussian-10.0": bandwidth = 10.0 features_aug, dir_labels_aug, mod_labels_aug = sample_singles_kde( features, dir_labels, mod_labels, n_per_class, bandwidth=bandwidth ) else: raise NotImplementedError() labels_2d = np.stack([dir_labels_aug.argmax(-1), mod_labels_aug.argmax(-1)], axis=-1) class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] logger.info(f"Augmented singles class sizes: {class_sizes}") return features_aug, dir_labels_aug, mod_labels_aug def get_clf(name: str, num_classes: int): if name == "mlp": return make_pipeline( RobustScaler(), MLPClassifier(hidden_layer_sizes=[100, 100, 100], early_stopping=True, max_iter=200) ) elif name == "logr": return make_pipeline(RobustScaler(), LogisticRegression(class_weight="balanced", max_iter=2000, n_jobs=-1)) elif name == "svc": return make_pipeline(RobustScaler(), SVC(class_weight="balanced", probability=True)) elif name == "rf": return make_pipeline(RobustScaler(), RandomForestClassifier(class_weight="balanced", n_jobs=-1)) elif name == "knn": return make_pipeline(RobustScaler(), KNeighborsClassifier()) elif name == "lda": return make_pipeline(RobustScaler(), LinearDiscriminantAnalysis()) elif name == "gbc": return make_pipeline(RobustScaler(), GradientBoostingClassifier()) else: raise ValueError(f"Unknown model name: {name}") def balance_classes(train_features, train_dir_labels, train_mod_labels): # Subsample the "Rest" class since it will be overrepresented assert train_dir_labels.ndim == 2 assert train_mod_labels.ndim == 2 labels_2d = np.stack([train_dir_labels.argmax(-1), train_mod_labels.argmax(-1)], axis=-1) class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] logger.info(f"Before pruning 'Rest' items, class sizes: {class_sizes}") rest_idx = np.where((labels_2d == [NO_DIR_IDX, NO_MOD_IDX]).all(-1))[0] active_idx = np.where((labels_2d != [NO_DIR_IDX, NO_MOD_IDX]).any(-1))[0] active_counts = np.unique(labels_2d[active_idx], axis=0, return_counts=True)[-1] avg_n_active = int(np.mean(active_counts)) subset_rest_idx = np.random.choice(rest_idx, avg_n_active, replace=False) res_x = np.concatenate((train_features[active_idx], train_features[subset_rest_idx])) res_y_dir = np.concatenate((train_dir_labels[active_idx], train_dir_labels[subset_rest_idx])) res_y_mod = np.concatenate((train_mod_labels[active_idx], train_mod_labels[subset_rest_idx])) res_labels_2d = np.stack([res_y_dir.argmax(-1), res_y_mod.argmax(-1)], axis=-1) res_class_sizes = np.unique(res_labels_2d, axis=0, return_counts=True)[-1] logger.info(f"After pruning 'Rest' items, class sizes: {res_class_sizes}") return res_x, res_y_dir, res_y_mod def remove_double_gestures(train_features, train_dir_labels, train_mod_labels): labels_2d = np.stack([train_dir_labels.argmax(-1), train_mod_labels.argmax(-1)], axis=-1) class_sizes = np.unique(labels_2d, axis=0, return_counts=True)[-1] logger.info(f"Before removing double gestures, class sizes: {class_sizes}") items_with_dir = train_dir_labels.argmax(-1) != NO_DIR_IDX items_with_mod = train_mod_labels.argmax(-1) != NO_MOD_IDX # Remove items with both direction and modifier singles_idx = ~np.logical_and(items_with_dir, items_with_mod) res_features = train_features[singles_idx] res_dir_labels = train_dir_labels[singles_idx] res_mod_labels = train_mod_labels[singles_idx] res_labels_2d = np.stack([res_dir_labels.argmax(-1), res_mod_labels.argmax(-1)], axis=-1) res_class_sizes = np.unique(res_labels_2d, axis=0, return_counts=True)[-1] logger.info(f"After removing double gestures, class sizes: {res_class_sizes}") return res_features, res_dir_labels, res_mod_labels @logger.catch(onerror=lambda _: sys.exit(1)) def run_training( subject: str, parallel_model_type: str, clf_name: str, doubles_method: str, fraction_doubles_per_class: float, singles_method: str, rel_fraction_singles_per_class: float, include_doubles_in_train: bool, feature_combine_type: str, ): # We don't want to modify code in the gest module itself. # Thus, we'll do augmentation manually here, and tell the model not to do # any further augmentation. # Load train data data_dict = load_data_dict() try: data = data_dict[subject] except KeyError: raise ValueError(f"Unknown subject: {subject}") train_features = data["Calibration_features"] train_dir_labels = data["Calibration_dir_labels"] train_mod_labels = data["Calibration_mod_labels"] # First, reduce amount of "Rest" items in train set train_features, train_dir_labels, train_mod_labels = balance_classes( train_features, train_dir_labels, train_mod_labels ) # Remove any double gestures that occured due to bad participant behavior train_features, train_dir_labels, train_mod_labels = remove_double_gestures( train_features, train_dir_labels, train_mod_labels ) # NOTE - we use HoldPulse1_NoFeedback and SimultaneousPulse1_NoFeedback for train set in the "upper bound" # otherwise, these blocks are not used # Load test data if include_doubles_in_train: # We use blocks 1 and 2 of the "NoFeedBack" portion of experiment # Double check that we're not using augmentation assert doubles_method == "none" assert singles_method == "none" # Add real combos to train set train_features = np.concatenate( [ train_features, data["HoldPulse1_NoFeedBack_features"], data["SimultaneousPulse1_NoFeedBack_features"], data["HoldPulse2_NoFeedBack_features"], data["SimultaneousPulse2_NoFeedBack_features"], ] ) train_dir_labels = np.concatenate( [ train_dir_labels, data["HoldPulse1_NoFeedBack_dir_labels"], data["SimultaneousPulse1_NoFeedBack_dir_labels"], data["HoldPulse2_NoFeedBack_dir_labels"], data["SimultaneousPulse2_NoFeedBack_dir_labels"], ] ) train_mod_labels = np.concatenate( [ train_mod_labels, data["HoldPulse1_NoFeedBack_mod_labels"], data["SimultaneousPulse1_NoFeedBack_mod_labels"], data["HoldPulse2_NoFeedBack_mod_labels"], data["SimultaneousPulse2_NoFeedBack_mod_labels"], ] ) logger.info(f"Initial train set: {train_features.shape=}, {train_dir_labels.shape=}, {train_mod_labels.shape=}") # Don't use "Feedback" blocks for this analysis test_blocks = ["HoldPulse3_NoFeedBack", "SimultaneousPulse3_NoFeedBack"] test_features = np.concatenate([data[f"{block}_features"] for block in test_blocks]) test_dir_labels = np.concatenate([data[f"{block}_dir_labels"] for block in test_blocks]) test_mod_labels = np.concatenate([data[f"{block}_mod_labels"] for block in test_blocks]) logger.info(f"test set: {test_features.shape=}, {test_dir_labels.shape=}, {test_mod_labels.shape=}") # Vary strategy for augmented doubles double_features_aug, double_dir_labels_aug, double_mod_labels_aug = get_augmented_doubles( doubles_method, feature_combine_type, fraction_doubles_per_class, train_features, train_dir_labels, train_mod_labels, ) # Make augmented singles # Figure out how many doubles per class. Take avg and then apply rel_fraction_singles_per_class to # get the number of singles per class n_singles_per_class = 0 if singles_method != "none": doubles_labels_2d = np.stack((double_dir_labels_aug.argmax(-1), double_mod_labels_aug.argmax(-1)), axis=-1) class_sizes = np.unique(doubles_labels_2d, axis=0, return_counts=True)[-1] n_singles_per_class = int(np.round(np.mean(class_sizes) * rel_fraction_singles_per_class)) single_features_aug, single_dir_labels_aug, single_mod_labels_aug = get_augmented_singles( singles_method, n_singles_per_class, train_features, train_dir_labels, train_mod_labels ) # Merge all train data train_features = np.concatenate([train_features, double_features_aug, single_features_aug]) train_dir_labels = np.concatenate([train_dir_labels, double_dir_labels_aug, single_dir_labels_aug]) train_mod_labels = np.concatenate([train_mod_labels, double_mod_labels_aug, single_mod_labels_aug]) logger.info(f"Augmented train set: {train_features.shape=}, {train_dir_labels.shape=}, {train_mod_labels.shape=}") # Create model if parallel_model_type == "ParallelA": model = ParallelA( get_clf(clf_name, num_classes=5), get_clf(clf_name, num_classes=3), use_augmentation=False, include_rest_data_for_clf=True, ) elif parallel_model_type == "ParallelB": model = ParallelB( dir_clf=get_clf(clf_name, num_classes=4), mod_clf=get_clf(clf_name, num_classes=2), has_dir_clf=get_clf(clf_name, num_classes=2), has_mod_clf=get_clf(clf_name, num_classes=2), use_augmentation=False, # include_rest_data_for_clf=True, # NOTE - always using true, flag is not in model ) elif parallel_model_type == "SerialControl": model = get_clf(clf_name, num_classes=15) else: raise ValueError(f"Unknown parallel model type: {parallel_model_type}") # Train logger.info("Train...") if parallel_model_type == "SerialControl": # Convert labels to integer by making 2-digit numbers, # where the 10s place is the dir label and the 1s place is the mod label train_labels = train_dir_labels.argmax(-1) * 10 + train_mod_labels.argmax(-1) model.fit(train_features, train_labels) else: model.fit(train_features, train_dir_labels, train_mod_labels) # Evaluate logger.info("Evaluate") if parallel_model_type == "SerialControl": combined_preds = model.predict(test_features) dir_preds = combined_preds // 10 mod_preds = combined_preds % 10 else: dir_preds, mod_preds = model.predict(test_features) preds_2d = np.stack([dir_preds, mod_preds], axis=-1) true_labels_2d = np.stack([test_dir_labels.argmax(-1), test_mod_labels.argmax(-1)], axis=-1) return confusion_matrix(true_labels_2d, preds_2d) if __name__ == "__main__": logger.remove() logger.add(sys.stdout, level="INFO", colorize=True) parser = argparse.ArgumentParser() parser.add_argument("--subject", type=str, required=True) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--parallel_model_type", choices=["ParallelA", "ParallelB", "SerialControl"], required=True) clf_names = ["mlp", "rf", "logr"] parser.add_argument("--clf_name", type=str, choices=clf_names, required=True) doubles_methods = [ "none", "subset_uniform", "subset_near_mean", "subset_spaced_quantiles", "subsetInput_uniform", "subsetInput_near_mean", "subsetInput_spaced_quantiles", "all", ] parser.add_argument("--doubles_method", type=str, choices=doubles_methods, required=True) parser.add_argument("--fraction_doubles_per_class", type=float, required=True) singles_methods = [ "none", "add-gaussian-0.3", "add-gaussian-0.4", "add-gaussian-0.5", "fit-gmm-1", "fit-gmm-5", "fit-gmm-10", "fit-kde-gaussian-silverman", "fit-kde-gaussian-0.01", "fit-kde-gaussian-0.1", "fit-kde-gaussian-1.0", ] parser.add_argument("--singles_method", type=str, choices=singles_methods, required=True) parser.add_argument("--rel_fraction_singles_per_class", type=float, required=True)
parser.add_argument("--include_doubles_in_train", type=str2bool, required=True)
10
2023-12-12 16:50:34+00:00
12k
ebb-earl-co/tidal-wave
tidal_wave/album.py
[ { "identifier": "AudioFormat", "path": "tidal_wave/media.py", "snippet": "class AudioFormat(str, Enum):\n sony_360_reality_audio = \"360\"\n dolby_atmos = \"Atmos\"\n hi_res = \"HiRes\"\n mqa = \"MQA\"\n lossless = \"Lossless\"\n high = \"High\"\n low = \"Low\"" }, { "identi...
from dataclasses import dataclass from pathlib import Path from typing import List, Optional from requests import Session from .media import AudioFormat from .models import ( AlbumsEndpointResponseJSON, AlbumsItemsResponseJSON, AlbumsReviewResponseJSON, ) from .requesting import request_albums, request_album_items, request_album_review from .track import Track from .utils import download_cover_image import json import sys
7,628
@dataclass class Album: album_id: int def __post_init__(self): self.album_dir: Optional[Path] = None self.album_cover_saved: bool = False def get_items(self, session: Session): """This method populates self.tracks by requesting from TIDAL albums/items endpoint.""" album_items: AlbumsItemsResponseJSON = request_album_items( session=session, identifier=self.album_id ) _items = album_items.items if album_items is not None else () self.tracks = tuple(_item.item for _item in _items) def get_metadata(self, session: Session): """This method populates self.metadata by requesting from TIDAL /albums endpoint""" self.metadata: AlbumsEndpointResponseJSON = request_albums( session=session, identifier=self.album_id ) def get_review(self, session: Session): """This method requests the review corresponding to self.album_id in TIDAL. If it exists, it is written to disk as AlbumReview.json in self.album_dir""" self.album_review: Optional[AlbumsReviewResponseJSON] = request_album_review( session=session, identifier=self.album_id ) if self.album_review is not None: (self.album_dir / "AlbumReview.json").write_text( self.album_review.to_json() ) def set_dir(self, out_dir: Path): """This method populates self.album_dir as a sub-subdirectory of out_dir: its parent directory is the name of the (main) artist of the album""" artist_substring: str = self.metadata.artist.name.replace("..", "") album_substring: str = ( f"{self.metadata.name.replace('..', '')} " f"[{self.metadata.id}] [{self.metadata.release_date.year}]" ) self.album_dir = out_dir / artist_substring / album_substring self.album_dir.mkdir(parents=True, exist_ok=True) if self.metadata.number_of_volumes > 1: for v in range(1, self.metadata.number_of_volumes + 1): volume_substring: str = f"Volume {v}" (out_dir / artist_substring / album_substring / volume_substring).mkdir( parents=True, exist_ok=True ) def save_cover_image(self, session: Session, out_dir: Path): """This method writes cover.jpg in self.album_dir via the utils.download_cover_image() function. If successful, then self.album_cover_saved takes the value True""" if self.album_dir is None: self.set_dir(out_dir=out_dir) self.cover_path: Path = self.album_dir / "cover.jpg" if not self.cover_path.exists(): download_cover_image( session=session, cover_uuid=self.metadata.cover, output_dir=self.album_dir, ) else: self.album_cover_saved = True def get_tracks( self, session: Session, audio_format: AudioFormat, out_dir: Path ) -> List[Optional[str]]: """This method uses self.tracks to call track.Track.get() for each track in self.tracks. It uses the result of each of these calls to populate self.track_files""" track_files: List[str] = [None] * self.metadata.number_of_tracks for i, t in enumerate(self.tracks): # type(t) is TracksEndpointResponseJSON
@dataclass class Album: album_id: int def __post_init__(self): self.album_dir: Optional[Path] = None self.album_cover_saved: bool = False def get_items(self, session: Session): """This method populates self.tracks by requesting from TIDAL albums/items endpoint.""" album_items: AlbumsItemsResponseJSON = request_album_items( session=session, identifier=self.album_id ) _items = album_items.items if album_items is not None else () self.tracks = tuple(_item.item for _item in _items) def get_metadata(self, session: Session): """This method populates self.metadata by requesting from TIDAL /albums endpoint""" self.metadata: AlbumsEndpointResponseJSON = request_albums( session=session, identifier=self.album_id ) def get_review(self, session: Session): """This method requests the review corresponding to self.album_id in TIDAL. If it exists, it is written to disk as AlbumReview.json in self.album_dir""" self.album_review: Optional[AlbumsReviewResponseJSON] = request_album_review( session=session, identifier=self.album_id ) if self.album_review is not None: (self.album_dir / "AlbumReview.json").write_text( self.album_review.to_json() ) def set_dir(self, out_dir: Path): """This method populates self.album_dir as a sub-subdirectory of out_dir: its parent directory is the name of the (main) artist of the album""" artist_substring: str = self.metadata.artist.name.replace("..", "") album_substring: str = ( f"{self.metadata.name.replace('..', '')} " f"[{self.metadata.id}] [{self.metadata.release_date.year}]" ) self.album_dir = out_dir / artist_substring / album_substring self.album_dir.mkdir(parents=True, exist_ok=True) if self.metadata.number_of_volumes > 1: for v in range(1, self.metadata.number_of_volumes + 1): volume_substring: str = f"Volume {v}" (out_dir / artist_substring / album_substring / volume_substring).mkdir( parents=True, exist_ok=True ) def save_cover_image(self, session: Session, out_dir: Path): """This method writes cover.jpg in self.album_dir via the utils.download_cover_image() function. If successful, then self.album_cover_saved takes the value True""" if self.album_dir is None: self.set_dir(out_dir=out_dir) self.cover_path: Path = self.album_dir / "cover.jpg" if not self.cover_path.exists(): download_cover_image( session=session, cover_uuid=self.metadata.cover, output_dir=self.album_dir, ) else: self.album_cover_saved = True def get_tracks( self, session: Session, audio_format: AudioFormat, out_dir: Path ) -> List[Optional[str]]: """This method uses self.tracks to call track.Track.get() for each track in self.tracks. It uses the result of each of these calls to populate self.track_files""" track_files: List[str] = [None] * self.metadata.number_of_tracks for i, t in enumerate(self.tracks): # type(t) is TracksEndpointResponseJSON
track: Track = Track(track_id=t.id)
7
2023-12-12 21:50:25+00:00
12k
Deltares/imod-python
imod/mf6/dis.py
[ { "identifier": "Package", "path": "imod/mf6/package.py", "snippet": "class Package(PackageBase, abc.ABC):\n \"\"\"\n Package is used to share methods for specific packages with no time\n component.\n\n It is not meant to be used directly, only to inherit from, to implement new\n packages...
import pathlib import numpy as np import imod from imod.mf6.package import Package from imod.mf6.regridding_utils import RegridderType from imod.mf6.validation import DisBottomSchema from imod.schemata import ( ActiveCellsConnectedSchema, AllValueSchema, AnyValueSchema, DimsSchema, DTypeSchema, IdentityNoDataSchema, IndexesSchema, )
9,382
class StructuredDiscretization(Package): """ Discretization information for structered grids is specified using the file. (DIS6) Only one discretization input file (DISU6, DISV6 or DIS6) can be specified for a model. https://water.usgs.gov/water-resources/software/MODFLOW-6/mf6io_6.0.4.pdf#page=35 Parameters ---------- top: array of floats (xr.DataArray) is the top elevation for each cell in the top model layer. bottom: array of floats (xr.DataArray) is the bottom elevation for each cell. idomain: array of integers (xr.DataArray) Indicates the existence status of a cell. Horizontal discretization information will be derived from the x and y coordinates of the DataArray. If the idomain value for a cell is 0, the cell does not exist in the simulation. Input and output values will be read and written for the cell, but internal to the program, the cell is excluded from the solution. If the idomain value for a cell is 1, the cell exists in the simulation. if the idomain value for a cell is -1, the cell does not exist in the simulation. Furthermore, the first existing cell above will be connected to the first existing cell below. This type of cell is referred to as a "vertical pass through" cell. validate: {True, False} Flag to indicate whether the package should be validated upon initialization. This raises a ValidationError if package input is provided in the wrong manner. Defaults to True. """ _pkg_id = "dis" _init_schemata = { "top": [ DTypeSchema(np.floating), DimsSchema("y", "x") | DimsSchema(), IndexesSchema(), ], "bottom": [ DTypeSchema(np.floating), DimsSchema("layer", "y", "x") | DimsSchema("layer"), IndexesSchema(), ], "idomain": [ DTypeSchema(np.integer), DimsSchema("layer", "y", "x"), IndexesSchema(), ], } _write_schemata = { "idomain": (
class StructuredDiscretization(Package): """ Discretization information for structered grids is specified using the file. (DIS6) Only one discretization input file (DISU6, DISV6 or DIS6) can be specified for a model. https://water.usgs.gov/water-resources/software/MODFLOW-6/mf6io_6.0.4.pdf#page=35 Parameters ---------- top: array of floats (xr.DataArray) is the top elevation for each cell in the top model layer. bottom: array of floats (xr.DataArray) is the bottom elevation for each cell. idomain: array of integers (xr.DataArray) Indicates the existence status of a cell. Horizontal discretization information will be derived from the x and y coordinates of the DataArray. If the idomain value for a cell is 0, the cell does not exist in the simulation. Input and output values will be read and written for the cell, but internal to the program, the cell is excluded from the solution. If the idomain value for a cell is 1, the cell exists in the simulation. if the idomain value for a cell is -1, the cell does not exist in the simulation. Furthermore, the first existing cell above will be connected to the first existing cell below. This type of cell is referred to as a "vertical pass through" cell. validate: {True, False} Flag to indicate whether the package should be validated upon initialization. This raises a ValidationError if package input is provided in the wrong manner. Defaults to True. """ _pkg_id = "dis" _init_schemata = { "top": [ DTypeSchema(np.floating), DimsSchema("y", "x") | DimsSchema(), IndexesSchema(), ], "bottom": [ DTypeSchema(np.floating), DimsSchema("layer", "y", "x") | DimsSchema("layer"), IndexesSchema(), ], "idomain": [ DTypeSchema(np.integer), DimsSchema("layer", "y", "x"), IndexesSchema(), ], } _write_schemata = { "idomain": (
ActiveCellsConnectedSchema(is_notnull=("!=", 0)),
3
2023-12-08 13:57:59+00:00
12k
Dong142857/Live3DPortrait
models/model.py
[ { "identifier": "upfirdn2d", "path": "torch_utils/ops/upfirdn2d.py", "snippet": "def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl='cuda'):\n r\"\"\"Pad, upsample, filter, and downsample a batch of 2D images.\n\n Performs the following sequence of operations for each cha...
import torch import torch.nn as nn import torch.nn.functional as F import math import sys from segmentation_models_pytorch.decoders.deeplabv3 import DeepLabV3 from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from einops import rearrange, repeat from torch_utils.ops import upfirdn2d from torch_utils.misc import assert_shape from functools import reduce from typing import Union from segmentation_models_pytorch.encoders.mix_transformer import OverlapPatchEmbed, Block from models.eg3d.volumetric_rendering.renderer import ImportanceRenderer, sample_from_planes from models.eg3d.volumetric_rendering.ray_sampler import RaySampler from models.eg3d.superresolution import SuperresolutionHybrid8XDC from models.eg3d.networks_stylegan2 import FullyConnectedLayer from models.eg3d.triplane import OSGDecoder from models.eg3d.networks_stylegan2 import Generator as StyleGAN2Backbone
7,378
# import segmentation_models_pytorch ''' impletement of RealTimeRF including the full model and LT model ''' # sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..'))) sys.path.append(".") sys.path.append("..") class TriGenerator(nn.Module): ''' similar to TriplaneGenerator class but lack of renderer ''' def __init__(self, # 参数表暂时不删,做占位用 z_dim, # Input latent (Z) dimensionality. c_dim, # Conditioning label (C) dimensionality. w_dim, # Intermediate latent (W) dimensionality. img_resolution, # Output resolution. img_channels, # Number of output color channels. sr_num_fp16_res = 0, mapping_kwargs = {}, # Arguments for MappingNetwork. rendering_kwargs = {}, sr_kwargs = {}, **synthesis_kwargs, # Arguments for SynthesisNetwork. ): super().__init__() self.z_dim=z_dim self.c_dim=c_dim self.w_dim=w_dim self.backbone = StyleGAN2Backbone(z_dim, c_dim, w_dim, img_resolution=256, img_channels=32*3, mapping_kwargs=mapping_kwargs, **synthesis_kwargs) self._last_planes = None self.rendering_kwargs = rendering_kwargs def mapping(self, z, c, truncation_psi=1, truncation_cutoff=None, update_emas=False): if self.rendering_kwargs['c_gen_conditioning_zero']: c = torch.zeros_like(c) return self.backbone.mapping(z, c * self.rendering_kwargs.get('c_scale', 0), truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff, update_emas=update_emas) def synthesis(self, ws, update_emas=False, cache_backbone=False, use_cached_backbone=False, **synthesis_kwargs): if use_cached_backbone and self._last_planes is not None: planes = self._last_planes else: planes = self.backbone.synthesis(ws, update_emas=update_emas, **synthesis_kwargs) if cache_backbone: self._last_planes = planes return planes def forward(self, z, c, truncation_psi=1, truncation_cutoff=None, neural_rendering_resolution=None, update_emas=False, cache_backbone=False, use_cached_backbone=False, **synthesis_kwargs): # Render a batch of generated images. ws = self.mapping(z, c, truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff, update_emas=update_emas) return self.synthesis(ws, update_emas=update_emas, neural_rendering_resolution=neural_rendering_resolution, cache_backbone=cache_backbone, use_cached_backbone=use_cached_backbone, **synthesis_kwargs) class TriplaneRenderer(nn.Module): def __init__(self, img_resolution, img_channels, rendering_kwargs={}) -> None: ''' Triplane Renderer Generate 2D image from triplanes representation SuperResolution without stylecode FullyConnected layer ''' super(TriplaneRenderer, self).__init__() self.img_resolution=img_resolution self.img_channels=img_channels self.renderer = ImportanceRenderer() self.ray_sampler = RaySampler() self.w_dim = 512 self.const = torch.nn.Parameter(torch.randn([1, 1, self.w_dim])) # 常数输入 self.decoder = OSGDecoder(32, {'decoder_lr_mul': rendering_kwargs.get('decoder_lr_mul', 1), 'decoder_output_dim': 32}) self.superresolution = SuperresolutionHybrid8XDC(32, img_resolution, sr_num_fp16_res=0, sr_antialias=True) self.rendering_kwargs = rendering_kwargs self.neural_rendering_resolution = 128 # 64 def synthesis(self, planes, c, neural_rendering_resolution=None): cam2world_matrix = c[:, :16].view(-1, 4, 4) intrinsics = c[:, 16:25].view(-1, 3, 3) if neural_rendering_resolution is None: neural_rendering_resolution = self.neural_rendering_resolution else: self.neural_rendering_resolution = neural_rendering_resolution # Create a batch of rays for volume rendering ray_origins, ray_directions = self.ray_sampler(cam2world_matrix, intrinsics, neural_rendering_resolution) N, _, _ = ray_origins.shape # Reshape output into three 32-channel planes planes = planes.view(len(planes), 3, 32, planes.shape[-2], planes.shape[-1]) # Perform volume rendering feature_samples, depth_samples, _ = self.renderer(planes, self.decoder, ray_origins, ray_directions, self.rendering_kwargs) # channels last # Reshape into 'raw' neural-rendered image H = W = neural_rendering_resolution feature_image = feature_samples.permute(0, 2, 1).reshape(N, feature_samples.shape[-1], H, W).contiguous() depth_image = depth_samples.permute(0, 2, 1).reshape(N, 1, H, W) # Run superresolution to get final image rgb_image = feature_image[:, :3] # sr_image = self.superresolution(rgb_image, feature_image, ws, noise_mode='none') const_w_input = self.const.repeat([N, 1, 1]) sr_image = self.superresolution(rgb_image, feature_image, const_w_input, noise_mode='none') return {'image': sr_image, 'image_raw': rgb_image, 'image_depth': depth_image, 'feature_image': feature_image, 'planes': planes} def sample_density(self, planes, coordinates, directions): ''' 给定triplanes和camera参数,生成图像并且返回 '''
# import segmentation_models_pytorch ''' impletement of RealTimeRF including the full model and LT model ''' # sys.path.insert(0, os.path.abspath(os.path.join(__file__, '..'))) sys.path.append(".") sys.path.append("..") class TriGenerator(nn.Module): ''' similar to TriplaneGenerator class but lack of renderer ''' def __init__(self, # 参数表暂时不删,做占位用 z_dim, # Input latent (Z) dimensionality. c_dim, # Conditioning label (C) dimensionality. w_dim, # Intermediate latent (W) dimensionality. img_resolution, # Output resolution. img_channels, # Number of output color channels. sr_num_fp16_res = 0, mapping_kwargs = {}, # Arguments for MappingNetwork. rendering_kwargs = {}, sr_kwargs = {}, **synthesis_kwargs, # Arguments for SynthesisNetwork. ): super().__init__() self.z_dim=z_dim self.c_dim=c_dim self.w_dim=w_dim self.backbone = StyleGAN2Backbone(z_dim, c_dim, w_dim, img_resolution=256, img_channels=32*3, mapping_kwargs=mapping_kwargs, **synthesis_kwargs) self._last_planes = None self.rendering_kwargs = rendering_kwargs def mapping(self, z, c, truncation_psi=1, truncation_cutoff=None, update_emas=False): if self.rendering_kwargs['c_gen_conditioning_zero']: c = torch.zeros_like(c) return self.backbone.mapping(z, c * self.rendering_kwargs.get('c_scale', 0), truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff, update_emas=update_emas) def synthesis(self, ws, update_emas=False, cache_backbone=False, use_cached_backbone=False, **synthesis_kwargs): if use_cached_backbone and self._last_planes is not None: planes = self._last_planes else: planes = self.backbone.synthesis(ws, update_emas=update_emas, **synthesis_kwargs) if cache_backbone: self._last_planes = planes return planes def forward(self, z, c, truncation_psi=1, truncation_cutoff=None, neural_rendering_resolution=None, update_emas=False, cache_backbone=False, use_cached_backbone=False, **synthesis_kwargs): # Render a batch of generated images. ws = self.mapping(z, c, truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff, update_emas=update_emas) return self.synthesis(ws, update_emas=update_emas, neural_rendering_resolution=neural_rendering_resolution, cache_backbone=cache_backbone, use_cached_backbone=use_cached_backbone, **synthesis_kwargs) class TriplaneRenderer(nn.Module): def __init__(self, img_resolution, img_channels, rendering_kwargs={}) -> None: ''' Triplane Renderer Generate 2D image from triplanes representation SuperResolution without stylecode FullyConnected layer ''' super(TriplaneRenderer, self).__init__() self.img_resolution=img_resolution self.img_channels=img_channels self.renderer = ImportanceRenderer() self.ray_sampler = RaySampler() self.w_dim = 512 self.const = torch.nn.Parameter(torch.randn([1, 1, self.w_dim])) # 常数输入 self.decoder = OSGDecoder(32, {'decoder_lr_mul': rendering_kwargs.get('decoder_lr_mul', 1), 'decoder_output_dim': 32}) self.superresolution = SuperresolutionHybrid8XDC(32, img_resolution, sr_num_fp16_res=0, sr_antialias=True) self.rendering_kwargs = rendering_kwargs self.neural_rendering_resolution = 128 # 64 def synthesis(self, planes, c, neural_rendering_resolution=None): cam2world_matrix = c[:, :16].view(-1, 4, 4) intrinsics = c[:, 16:25].view(-1, 3, 3) if neural_rendering_resolution is None: neural_rendering_resolution = self.neural_rendering_resolution else: self.neural_rendering_resolution = neural_rendering_resolution # Create a batch of rays for volume rendering ray_origins, ray_directions = self.ray_sampler(cam2world_matrix, intrinsics, neural_rendering_resolution) N, _, _ = ray_origins.shape # Reshape output into three 32-channel planes planes = planes.view(len(planes), 3, 32, planes.shape[-2], planes.shape[-1]) # Perform volume rendering feature_samples, depth_samples, _ = self.renderer(planes, self.decoder, ray_origins, ray_directions, self.rendering_kwargs) # channels last # Reshape into 'raw' neural-rendered image H = W = neural_rendering_resolution feature_image = feature_samples.permute(0, 2, 1).reshape(N, feature_samples.shape[-1], H, W).contiguous() depth_image = depth_samples.permute(0, 2, 1).reshape(N, 1, H, W) # Run superresolution to get final image rgb_image = feature_image[:, :3] # sr_image = self.superresolution(rgb_image, feature_image, ws, noise_mode='none') const_w_input = self.const.repeat([N, 1, 1]) sr_image = self.superresolution(rgb_image, feature_image, const_w_input, noise_mode='none') return {'image': sr_image, 'image_raw': rgb_image, 'image_depth': depth_image, 'feature_image': feature_image, 'planes': planes} def sample_density(self, planes, coordinates, directions): ''' 给定triplanes和camera参数,生成图像并且返回 '''
sampled_features = sample_from_planes(self.renderer.plane_axes, planes, coordinates, padding_mode='zeros', box_warp=self.rendering_kwargs['box_warp'])
3
2023-12-09 15:18:53+00:00
12k
blaise-tk/RVC_CLI
rvc/infer/infer.py
[ { "identifier": "load_audio", "path": "rvc/lib/utils.py", "snippet": "def load_audio(file, sampling_rate):\n try:\n file = file.strip(\" \").strip('\"').strip(\"\\n\").strip('\"').strip(\" \")\n out, _ = (\n ffmpeg.input(file, threads=0)\n .output(\"-\", format=\"f...
import os import sys import torch import numpy as np import soundfile as sf from vc_infer_pipeline import VC from rvc.lib.utils import load_audio from fairseq import checkpoint_utils from rvc.lib.infer_pack.models import ( SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono, SynthesizerTrnMs768NSFsid, SynthesizerTrnMs768NSFsid_nono, ) from rvc.configs.config import Config
7,790
config = Config() torch.manual_seed(114514) hubert_model = None def load_hubert(): global hubert_model models, _, _ = checkpoint_utils.load_model_ensemble_and_task( ["hubert_base.pt"], suffix="", ) hubert_model = models[0] hubert_model = hubert_model.to(config.device) if config.is_half: hubert_model = hubert_model.half() else: hubert_model = hubert_model.float() hubert_model.eval() def vc_single( sid=0, input_audio_path=None, f0_up_key=None, f0_file=None, f0_method=None, file_index=None, index_rate=None, resample_sr=0, rms_mix_rate=1, protect=0.33, hop_length=None, output_path=None, ): global tgt_sr, net_g, vc, hubert_model, version if input_audio_path is None: return "Please, load an audio!", None f0_up_key = int(f0_up_key) try: audio = load_audio(input_audio_path, 16000) audio_max = np.abs(audio).max() / 0.95 if audio_max > 1: audio /= audio_max if not hubert_model: load_hubert() if_f0 = cpt.get("f0", 1) file_index = ( file_index.strip(" ") .strip('"') .strip("\n") .strip('"') .strip(" ") .replace("trained", "added") ) if tgt_sr != resample_sr >= 16000: tgt_sr = resample_sr audio_opt = vc.pipeline( hubert_model, net_g, sid, audio, input_audio_path, f0_up_key, f0_method, file_index, index_rate, if_f0, filter_radius, tgt_sr, resample_sr, rms_mix_rate, version, protect, hop_length, f0_file=f0_file, ) if output_path is not None: sf.write(output_path, audio_opt, tgt_sr, format="WAV") return (tgt_sr, audio_opt) except Exception as error: print(error) def get_vc(weight_root, sid): global n_spk, tgt_sr, net_g, vc, cpt, version if sid == "" or sid == []: global hubert_model if hubert_model is not None: print("clean_empty_cache") del net_g, n_spk, vc, hubert_model, tgt_sr # ,cpt hubert_model = net_g = n_spk = vc = hubert_model = tgt_sr = None if torch.cuda.is_available(): torch.cuda.empty_cache() 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=config.is_half ) else:
config = Config() torch.manual_seed(114514) hubert_model = None def load_hubert(): global hubert_model models, _, _ = checkpoint_utils.load_model_ensemble_and_task( ["hubert_base.pt"], suffix="", ) hubert_model = models[0] hubert_model = hubert_model.to(config.device) if config.is_half: hubert_model = hubert_model.half() else: hubert_model = hubert_model.float() hubert_model.eval() def vc_single( sid=0, input_audio_path=None, f0_up_key=None, f0_file=None, f0_method=None, file_index=None, index_rate=None, resample_sr=0, rms_mix_rate=1, protect=0.33, hop_length=None, output_path=None, ): global tgt_sr, net_g, vc, hubert_model, version if input_audio_path is None: return "Please, load an audio!", None f0_up_key = int(f0_up_key) try: audio = load_audio(input_audio_path, 16000) audio_max = np.abs(audio).max() / 0.95 if audio_max > 1: audio /= audio_max if not hubert_model: load_hubert() if_f0 = cpt.get("f0", 1) file_index = ( file_index.strip(" ") .strip('"') .strip("\n") .strip('"') .strip(" ") .replace("trained", "added") ) if tgt_sr != resample_sr >= 16000: tgt_sr = resample_sr audio_opt = vc.pipeline( hubert_model, net_g, sid, audio, input_audio_path, f0_up_key, f0_method, file_index, index_rate, if_f0, filter_radius, tgt_sr, resample_sr, rms_mix_rate, version, protect, hop_length, f0_file=f0_file, ) if output_path is not None: sf.write(output_path, audio_opt, tgt_sr, format="WAV") return (tgt_sr, audio_opt) except Exception as error: print(error) def get_vc(weight_root, sid): global n_spk, tgt_sr, net_g, vc, cpt, version if sid == "" or sid == []: global hubert_model if hubert_model is not None: print("clean_empty_cache") del net_g, n_spk, vc, hubert_model, tgt_sr # ,cpt hubert_model = net_g = n_spk = vc = hubert_model = tgt_sr = None if torch.cuda.is_available(): torch.cuda.empty_cache() 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=config.is_half ) else:
net_g = SynthesizerTrnMs256NSFsid_nono(*cpt["config"])
2
2023-12-10 21:09:41+00:00
12k
Opt-Mucca/PySCIPOpt-ML
src/pyscipopt_ml/modelling/gradient_boosting/aggregate_tree_model.py
[ { "identifier": "add_decision_tree_classifier_constr", "path": "src/pyscipopt_ml/sklearn/decision_tree.py", "snippet": "def add_decision_tree_classifier_constr(\n scip_model,\n decision_tree_classifier,\n input_vars,\n output_vars=None,\n unique_naming_prefix=\"\",\n epsilon=0.0,\n ...
import numpy as np from ...sklearn.decision_tree import ( add_decision_tree_classifier_constr, add_decision_tree_regressor_constr, ) from ..base_predictor_constraint import AbstractPredictorConstr from ..classification.argmax_model import argmax_bound_formulation from ..decision_tree import leaf_formulation from ..var_utils import create_vars
8,852
The input variables that are passed to each decision tree output : np.ndarray The output variables of the predictor tree_vars : np.ndarray The PySCIPOpt variables that have been created to represent the output of each decision tree (i.e. estimator) trees : list A list of lists containing dictionary information that completely describe each decision tree (i.e. estimator) constant : np.ndarray An array of constant shift values that are added to the output values of each decision tree (i.e. estimator) lr : float or int The learning rate used while training. For GBDT / RF this scales the output of each tree n_estimators : int The number of decision trees (i.e. estimators) unique_naming_prefix : str The unique naming prefix string that goes before all variables and constraints that are constructed by SCIP epsilon : float The epsilon that is used for each decision tree model. See :py:func:`pyscipopt_ml.modelling.decision_tree.leaf_formulation`. aggr : str, "sum" or "avg" The aggregation method used in the formulation. Either the estimators are averages or summed. classification : bool Whether the aggregated output of each decision tree (i.e. estimator) should be used for classification. Returns ------- estimators : list A list of :py:class`pyscipopt_ml.modelling.aggregate_tree_model.TreeEstimator` created_vars : list A list containing all created PySCIPOpt vars created_cons : list A list containing all created PySCIPOpt cons """ # Get the number of samples and output dimension n_samples = _input.shape[0] outdim = output.shape[-1] # Create the individual tree estimators estimators = create_tree_estimators( scip_model, _input, tree_vars, trees, n_estimators, outdim, unique_naming_prefix, epsilon, False, **kwargs, ) # Aggregate the trees over the output dimension aggregate_tree_output = aggregate_estimator_outputs(tree_vars, lr, constant, aggr=aggr) # Formulate the appropriate constraints created_vars, created_cons = create_aggregation_constraints( scip_model, aggregate_tree_output, output, n_samples, outdim, unique_naming_prefix, classification, ) return estimators, created_vars, created_cons def create_aggregation_constraints( scip_model, aggregate_tree_output, output, n_samples, outdim, unique_naming_prefix, classification, ): """ Creates the variables and constraints that link the output of the predictor itself and the aggregation of each estimator. Parameters ---------- scip_model : PySCIPOpt Model The SCIP Model where the predictor should be inserted. aggregate_tree_output : np.ndarray The aggregated output variables of each decision tree output : np.ndarray The output variables of the predictor n_samples : int The number of samples outdim : int The number of outputs of each decision tree (i.e. estimator) unique_naming_prefix : str The unique naming prefix string that goes before all variables and constraints that are constructed by SCIP classification : bool Whether the aggregated output of each decision tree (i.e. estimator) should be used for classification. Returns ------- created_vars : list A list containing all created PySCIPOpt vars created_cons : list A list containing all created PySCIPOpt cons """ # Formulate the appropriate constraints created_cons = [] created_vars = [] if not classification: sum_tree_cons = np.zeros((n_samples, outdim), dtype=object) for i in range(n_samples): for j in range(outdim): name = unique_naming_prefix + f"tree_sum_{i}_{j}" sum_tree_cons[i][j] = scip_model.addCons( output[i][j] == aggregate_tree_output[i][j], name=name ) created_cons.append(sum_tree_cons) else:
""" Utilities for modelling gradient boosting decision trees and random forest constraints """ def aggregated_estimator_formulation( scip_model, _input, output, tree_vars, trees, constant, lr, n_estimators, unique_naming_prefix, epsilon, aggr, classification, **kwargs, ): """ Creates the model that represents the aggregation of estimators into a single output. This function is used exclusively for the case where the estimators are decision trees, and the larger predictor is either a gradient boosting decision tree or random forest. Parameters ---------- scip_model : PySCIPOpt Model The SCIP Model where the predictor should be inserted. _input : np.ndarray The input variables that are passed to each decision tree output : np.ndarray The output variables of the predictor tree_vars : np.ndarray The PySCIPOpt variables that have been created to represent the output of each decision tree (i.e. estimator) trees : list A list of lists containing dictionary information that completely describe each decision tree (i.e. estimator) constant : np.ndarray An array of constant shift values that are added to the output values of each decision tree (i.e. estimator) lr : float or int The learning rate used while training. For GBDT / RF this scales the output of each tree n_estimators : int The number of decision trees (i.e. estimators) unique_naming_prefix : str The unique naming prefix string that goes before all variables and constraints that are constructed by SCIP epsilon : float The epsilon that is used for each decision tree model. See :py:func:`pyscipopt_ml.modelling.decision_tree.leaf_formulation`. aggr : str, "sum" or "avg" The aggregation method used in the formulation. Either the estimators are averages or summed. classification : bool Whether the aggregated output of each decision tree (i.e. estimator) should be used for classification. Returns ------- estimators : list A list of :py:class`pyscipopt_ml.modelling.aggregate_tree_model.TreeEstimator` created_vars : list A list containing all created PySCIPOpt vars created_cons : list A list containing all created PySCIPOpt cons """ # Get the number of samples and output dimension n_samples = _input.shape[0] outdim = output.shape[-1] # Create the individual tree estimators estimators = create_tree_estimators( scip_model, _input, tree_vars, trees, n_estimators, outdim, unique_naming_prefix, epsilon, False, **kwargs, ) # Aggregate the trees over the output dimension aggregate_tree_output = aggregate_estimator_outputs(tree_vars, lr, constant, aggr=aggr) # Formulate the appropriate constraints created_vars, created_cons = create_aggregation_constraints( scip_model, aggregate_tree_output, output, n_samples, outdim, unique_naming_prefix, classification, ) return estimators, created_vars, created_cons def create_aggregation_constraints( scip_model, aggregate_tree_output, output, n_samples, outdim, unique_naming_prefix, classification, ): """ Creates the variables and constraints that link the output of the predictor itself and the aggregation of each estimator. Parameters ---------- scip_model : PySCIPOpt Model The SCIP Model where the predictor should be inserted. aggregate_tree_output : np.ndarray The aggregated output variables of each decision tree output : np.ndarray The output variables of the predictor n_samples : int The number of samples outdim : int The number of outputs of each decision tree (i.e. estimator) unique_naming_prefix : str The unique naming prefix string that goes before all variables and constraints that are constructed by SCIP classification : bool Whether the aggregated output of each decision tree (i.e. estimator) should be used for classification. Returns ------- created_vars : list A list containing all created PySCIPOpt vars created_cons : list A list containing all created PySCIPOpt cons """ # Formulate the appropriate constraints created_cons = [] created_vars = [] if not classification: sum_tree_cons = np.zeros((n_samples, outdim), dtype=object) for i in range(n_samples): for j in range(outdim): name = unique_naming_prefix + f"tree_sum_{i}_{j}" sum_tree_cons[i][j] = scip_model.addCons( output[i][j] == aggregate_tree_output[i][j], name=name ) created_cons.append(sum_tree_cons) else:
new_vars, new_cons = argmax_bound_formulation(
3
2023-12-10 20:28:22+00:00
12k
camenduru/MotionDirector-hf
utils/lora_handler.py
[ { "identifier": "UNet3DConditionModel", "path": "models/unet_3d_condition.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n r\"\"\"\n UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep\n and returns sample sh...
import os import torch from logging import warnings from typing import Union from types import SimpleNamespace from models.unet_3d_condition import UNet3DConditionModel from transformers import CLIPTextModel from utils.convert_diffusers_to_original_ms_text_to_video import convert_unet_state_dict, convert_text_enc_state_dict_v20 from .lora import ( extract_lora_ups_down, inject_trainable_lora_extended, save_lora_weight, train_patch_pipe, monkeypatch_or_replace_lora, monkeypatch_or_replace_lora_extended )
10,785
self, version: LORA_VERSIONS = LoraVersions.cloneofsimo, use_unet_lora: bool = False, use_text_lora: bool = False, save_for_webui: bool = False, only_for_webui: bool = False, lora_bias: str = 'none', unet_replace_modules: list = None, text_encoder_replace_modules: list = None ): self.version = version self.lora_loader = self.get_lora_func(func_type=LoraFuncTypes.loader) self.lora_injector = self.get_lora_func(func_type=LoraFuncTypes.injector) self.lora_bias = lora_bias self.use_unet_lora = use_unet_lora self.use_text_lora = use_text_lora self.save_for_webui = save_for_webui self.only_for_webui = only_for_webui self.unet_replace_modules = unet_replace_modules self.text_encoder_replace_modules = text_encoder_replace_modules self.use_lora = any([use_text_lora, use_unet_lora]) def is_cloneofsimo_lora(self): return self.version == LoraVersions.cloneofsimo def get_lora_func(self, func_type: LORA_FUNC_TYPES = LoraFuncTypes.loader): if self.is_cloneofsimo_lora(): if func_type == LoraFuncTypes.loader: return monkeypatch_or_replace_lora_extended if func_type == LoraFuncTypes.injector: return inject_trainable_lora_extended assert "LoRA Version does not exist." def check_lora_ext(self, lora_file: str): return lora_file.endswith(tuple(LORA_FILE_TYPES)) def get_lora_file_path( self, lora_path: str, model: Union[UNet3DConditionModel, CLIPTextModel] ): if os.path.exists(lora_path): lora_filenames = [fns for fns in os.listdir(lora_path)] is_lora = self.check_lora_ext(lora_path) is_unet = isinstance(model, UNet3DConditionModel) is_text = isinstance(model, CLIPTextModel) idx = 0 if is_unet else 1 base_name = FILE_BASENAMES[idx] for lora_filename in lora_filenames: is_lora = self.check_lora_ext(lora_filename) if not is_lora: continue if base_name in lora_filename: return os.path.join(lora_path, lora_filename) return None def handle_lora_load(self, file_name:str, lora_loader_args: dict = None): self.lora_loader(**lora_loader_args) print(f"Successfully loaded LoRA from: {file_name}") def load_lora(self, model, lora_path: str = '', lora_loader_args: dict = None,): try: lora_file = self.get_lora_file_path(lora_path, model) if lora_file is not None: lora_loader_args.update({"lora_path": lora_file}) self.handle_lora_load(lora_file, lora_loader_args) else: print(f"Could not load LoRAs for {model.__class__.__name__}. Injecting new ones instead...") except Exception as e: print(f"An error occured while loading a LoRA file: {e}") def get_lora_func_args(self, lora_path, use_lora, model, replace_modules, r, dropout, lora_bias, scale): return_dict = lora_args.copy() if self.is_cloneofsimo_lora(): return_dict = filter_dict(return_dict, keys=CLONE_OF_SIMO_KEYS) return_dict.update({ "model": model, "loras": self.get_lora_file_path(lora_path, model), "target_replace_module": replace_modules, "r": r, "scale": scale, "dropout_p": dropout, }) return return_dict def do_lora_injection( self, model, replace_modules, bias='none', dropout=0, r=4, lora_loader_args=None, ): REPLACE_MODULES = replace_modules params = None negation = None is_injection_hybrid = False if self.is_cloneofsimo_lora(): is_injection_hybrid = True injector_args = lora_loader_args params, negation = self.lora_injector(**injector_args) # inject_trainable_lora_extended
FILE_BASENAMES = ['unet', 'text_encoder'] LORA_FILE_TYPES = ['.pt', '.safetensors'] CLONE_OF_SIMO_KEYS = ['model', 'loras', 'target_replace_module', 'r'] STABLE_LORA_KEYS = ['model', 'target_module', 'search_class', 'r', 'dropout', 'lora_bias'] lora_versions = dict( stable_lora = "stable_lora", cloneofsimo = "cloneofsimo" ) lora_func_types = dict( loader = "loader", injector = "injector" ) lora_args = dict( model = None, loras = None, target_replace_module = [], target_module = [], r = 4, search_class = [torch.nn.Linear], dropout = 0, lora_bias = 'none' ) LoraVersions = SimpleNamespace(**lora_versions) LoraFuncTypes = SimpleNamespace(**lora_func_types) LORA_VERSIONS = [LoraVersions.stable_lora, LoraVersions.cloneofsimo] LORA_FUNC_TYPES = [LoraFuncTypes.loader, LoraFuncTypes.injector] def filter_dict(_dict, keys=[]): if len(keys) == 0: assert "Keys cannot empty for filtering return dict." for k in keys: if k not in lora_args.keys(): assert f"{k} does not exist in available LoRA arguments" return {k: v for k, v in _dict.items() if k in keys} class LoraHandler(object): def __init__( self, version: LORA_VERSIONS = LoraVersions.cloneofsimo, use_unet_lora: bool = False, use_text_lora: bool = False, save_for_webui: bool = False, only_for_webui: bool = False, lora_bias: str = 'none', unet_replace_modules: list = None, text_encoder_replace_modules: list = None ): self.version = version self.lora_loader = self.get_lora_func(func_type=LoraFuncTypes.loader) self.lora_injector = self.get_lora_func(func_type=LoraFuncTypes.injector) self.lora_bias = lora_bias self.use_unet_lora = use_unet_lora self.use_text_lora = use_text_lora self.save_for_webui = save_for_webui self.only_for_webui = only_for_webui self.unet_replace_modules = unet_replace_modules self.text_encoder_replace_modules = text_encoder_replace_modules self.use_lora = any([use_text_lora, use_unet_lora]) def is_cloneofsimo_lora(self): return self.version == LoraVersions.cloneofsimo def get_lora_func(self, func_type: LORA_FUNC_TYPES = LoraFuncTypes.loader): if self.is_cloneofsimo_lora(): if func_type == LoraFuncTypes.loader: return monkeypatch_or_replace_lora_extended if func_type == LoraFuncTypes.injector: return inject_trainable_lora_extended assert "LoRA Version does not exist." def check_lora_ext(self, lora_file: str): return lora_file.endswith(tuple(LORA_FILE_TYPES)) def get_lora_file_path( self, lora_path: str, model: Union[UNet3DConditionModel, CLIPTextModel] ): if os.path.exists(lora_path): lora_filenames = [fns for fns in os.listdir(lora_path)] is_lora = self.check_lora_ext(lora_path) is_unet = isinstance(model, UNet3DConditionModel) is_text = isinstance(model, CLIPTextModel) idx = 0 if is_unet else 1 base_name = FILE_BASENAMES[idx] for lora_filename in lora_filenames: is_lora = self.check_lora_ext(lora_filename) if not is_lora: continue if base_name in lora_filename: return os.path.join(lora_path, lora_filename) return None def handle_lora_load(self, file_name:str, lora_loader_args: dict = None): self.lora_loader(**lora_loader_args) print(f"Successfully loaded LoRA from: {file_name}") def load_lora(self, model, lora_path: str = '', lora_loader_args: dict = None,): try: lora_file = self.get_lora_file_path(lora_path, model) if lora_file is not None: lora_loader_args.update({"lora_path": lora_file}) self.handle_lora_load(lora_file, lora_loader_args) else: print(f"Could not load LoRAs for {model.__class__.__name__}. Injecting new ones instead...") except Exception as e: print(f"An error occured while loading a LoRA file: {e}") def get_lora_func_args(self, lora_path, use_lora, model, replace_modules, r, dropout, lora_bias, scale): return_dict = lora_args.copy() if self.is_cloneofsimo_lora(): return_dict = filter_dict(return_dict, keys=CLONE_OF_SIMO_KEYS) return_dict.update({ "model": model, "loras": self.get_lora_file_path(lora_path, model), "target_replace_module": replace_modules, "r": r, "scale": scale, "dropout_p": dropout, }) return return_dict def do_lora_injection( self, model, replace_modules, bias='none', dropout=0, r=4, lora_loader_args=None, ): REPLACE_MODULES = replace_modules params = None negation = None is_injection_hybrid = False if self.is_cloneofsimo_lora(): is_injection_hybrid = True injector_args = lora_loader_args params, negation = self.lora_injector(**injector_args) # inject_trainable_lora_extended
for _up, _down in extract_lora_ups_down(
3
2023-12-11 04:51:39+00:00
12k
Theia-4869/MoSA
src/models/build_vit_backbone.py
[ { "identifier": "VisionTransformer", "path": "src/models/vit_backbones/vit.py", "snippet": "class VisionTransformer(nn.Module):\n def __init__(\n self, model_type,\n img_size=224, num_classes=21843, vis=False\n ):\n super(VisionTransformer, self).__init__()\n config = C...
import numpy as np import torch import os from .vit_backbones.vit import VisionTransformer from .vit_backbones.swin_transformer import SwinTransformer from .vit_backbones.vit_mae import build_model as mae_vit_model from .vit_backbones.vit_moco import vit_base from .vit_adapter.vit_adapter import AdaptedVisionTransformer from .vit_adapter.swin_adapter import AdaptedSwinTransformer from .vit_adapter.vit_mosa import MoSAVisionTransformer from .vit_adapter.swin_mosa import MoSASwinTransformer from .vit_adapter.vit_mae import build_model as adapter_mae_vit_model from .vit_adapter.vit_moco import vit_base as adapter_vit_base from .vit_adapter.vit_lora import LoRAVisionTransformer from .vit_adapter.vit_mosl import MoSLVisionTransformer
10,678
embed_dim = 96 num_layers = 4 elif model_type == "swinb_imagenet_224": model = SwinTransformer( img_size=crop_size, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinb_imagenet_384": model = SwinTransformer( img_size=384, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinb_imagenet22k_224": model = SwinTransformer( img_size=crop_size, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinb_imagenet22k_384": model = SwinTransformer( img_size=384, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinl_imagenet22k_224": model = SwinTransformer( img_size=crop_size, embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=7, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 192 num_layers = 4 feat_dim = int(embed_dim * 2 ** (num_layers - 1)) # load checkpoint model_w = os.path.join(model_root, MODEL_ZOO[model_type]) checkpoint = torch.load(model_w, map_location='cpu') state_dict = checkpoint['model'] if crop_size == 448: for k in list(state_dict.keys()): if "attn_mask" not in k: # remove prefix state_dict[k] = state_dict[k] # delete renamed or unused k else: del state_dict[k] # rename some keys for ssl models if model_type.endswith("ssl"): # rename moco pre-trained keys for k in list(state_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('encoder.'): # remove prefix state_dict[k[len("encoder."):]] = state_dict[k] # delete renamed or unused k del state_dict[k] model.load_state_dict(state_dict, strict=False) return model, feat_dim def build_vit_sup_models( model_type, crop_size, model_root=None, adapter_cfg=None, lora_cfg=None, load_pretrain=True, vis=False ): # image size is the size of actual image m2featdim = { "sup_vitb16_224": 768, "sup_vitb16": 768, "sup_vitl16_224": 1024, "sup_vitl16": 1024, "sup_vitb8_imagenet21k": 768, "sup_vitb16_imagenet21k": 768, "sup_vitb32_imagenet21k": 768, "sup_vitl16_imagenet21k": 1024, "sup_vitl32_imagenet21k": 1024, "sup_vith14_imagenet21k": 1280, } if adapter_cfg is not None: if adapter_cfg.MOE: model = MoSAVisionTransformer(model_type, crop_size, num_classes=-1, adapter_cfg=adapter_cfg, mid=adapter_cfg.DEEPREG) else: model = AdaptedVisionTransformer(model_type, crop_size, num_classes=-1, adapter_cfg=adapter_cfg) elif lora_cfg is not None: if lora_cfg.MOE: model = MoSLVisionTransformer(model_type, crop_size, num_classes=-1, lora_cfg=lora_cfg, mid=lora_cfg.DEEPREG) else:
#!/usr/bin/env python3 MODEL_ZOO = { "swint_imagenet": "swin_tiny_patch4_window7_224.pth", "swint_imagenet_ssl": "moby_swin_t_300ep_pretrained.pth", "swins_imagenet": "swin_small_patch4_window7_224.pth", "swinb_imagenet_224": "swin_base_patch4_window7_224.pth", "swinb_imagenet_384": "swin_base_patch4_window12_384.pth", "swinb_imagenet22k_224": "swin_base_patch4_window7_224_22k.pth", "swinb_imagenet22k_384": "swin_base_patch4_window12_384_22k.pth", "swinl_imagenet22k_224": "swin_large_patch4_window7_224_22k.pth", "sup_vitb8": "ViT-B_8.npz", "sup_vitb16_224": "ViT-B_16-224.npz", "sup_vitb16": "ViT-B_16.npz", "sup_vitl16_224": "ViT-L_16-224.npz", "sup_vitl16": "ViT-L_16.npz", "sup_vitb8_imagenet21k": "imagenet21k_ViT-B_8.npz", "sup_vitb32_imagenet21k": "imagenet21k_ViT-B_32.npz", "sup_vitb16_imagenet21k": "imagenet21k_ViT-B_16.npz", "sup_vitl16_imagenet21k": "imagenet21k_ViT-L_16.npz", "sup_vitl32_imagenet21k": "imagenet21k_ViT-L_32.npz", "sup_vith14_imagenet21k": "imagenet21k_ViT-H_14.npz", "mae_vith14": "mae_pretrain_vit_huge.pth", "mae_vitb16": "mae_pretrain_vit_base.pth", "mae_vitl16": "mae_pretrain_vit_large.pth", } def build_mae_model( model_type, crop_size, prompt_cfg, model_root, adapter_cfg=None ): if adapter_cfg is not None: model = adapter_mae_vit_model(model_type, adapter_cfg) else: model = mae_vit_model(model_type) out_dim = model.embed_dim ckpt = os.path.join(model_root, MODEL_ZOO[model_type]) checkpoint = torch.load(ckpt, map_location="cpu") state_dict = checkpoint['model'] model.load_state_dict(state_dict, strict=False) model.head = torch.nn.Identity() return model, out_dim def build_mocov3_model( model_type, crop_size, prompt_cfg, model_root, adapter_cfg=None ): if model_type != "mocov3_vitb": raise ValueError("Does not support other arch") if adapter_cfg is not None: model = adapter_vit_base(adapter_cfg) else: model = vit_base() out_dim = 768 ckpt = os.path.join(model_root,"mocov3_linear-vit-b-300ep.pth.tar") checkpoint = torch.load(ckpt, map_location="cpu") state_dict = checkpoint['state_dict'] for k in list(state_dict.keys()): # retain only base_encoder up to before the embedding layer if k.startswith('module.'): # remove prefix state_dict[k[len("module."):]] = state_dict[k] # delete renamed or unused k del state_dict[k] model.load_state_dict(state_dict, strict=False) model.head = torch.nn.Identity() return model, out_dim def build_swin_model(model_type, crop_size, model_root, adapter_cfg, lora_cfg, load_pretrain, vis): if adapter_cfg is not None: return _build_adapted_swin_model(model_type, crop_size, adapter_cfg, model_root) else: return _build_swin_model(model_type, crop_size, model_root) def _build_adapted_swin_model(model_type, crop_size, adapter_cfg, model_root): if model_type == "swinb_imagenet22k_224": if adapter_cfg.MOE: model = MoSASwinTransformer( adapter_config=adapter_cfg, mid=adapter_cfg.DEEPREG, img_size=crop_size, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, drop_path_rate=0.5, num_classes=-1, ) else: model = AdaptedSwinTransformer( adapter_config=adapter_cfg, img_size=crop_size, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 feat_dim = int(embed_dim * 2 ** (num_layers - 1)) # load checkpoint model_w = os.path.join(model_root, MODEL_ZOO[model_type]) checkpoint = torch.load(model_w, map_location='cpu') state_dict = checkpoint['model'] if crop_size == 448: for k in list(state_dict.keys()): if "attn_mask" not in k: # remove prefix state_dict[k] = state_dict[k] # delete renamed or unused k else: del state_dict[k] # rename some keys for ssl models if model_type.endswith("ssl"): # rename moco pre-trained keys for k in list(state_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('encoder.'): # remove prefix state_dict[k[len("encoder."):]] = state_dict[k] # delete renamed or unused k del state_dict[k] model.load_state_dict(state_dict, strict=False) return model, feat_dim def _build_swin_model(model_type, crop_size, model_root): if model_type == "swint_imagenet": model = SwinTransformer( img_size=crop_size, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, drop_path_rate=0.2, num_classes=-1, # setting to a negative value will make head as identity ) embed_dim = 96 num_layers = 4 elif model_type == "swint_imagenet_ssl": model = SwinTransformer( img_size=crop_size, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, drop_path_rate=0.2, num_classes=-1, ) embed_dim = 96 num_layers = 4 elif model_type == "swins_imagenet": model = SwinTransformer( img_size=crop_size, embed_dim=96, depths=[2, 2, 18, 2], num_heads=[3, 6, 12, 24], window_size=7, drop_path_rate=0.3, num_classes=-1, ) embed_dim = 96 num_layers = 4 elif model_type == "swinb_imagenet_224": model = SwinTransformer( img_size=crop_size, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinb_imagenet_384": model = SwinTransformer( img_size=384, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinb_imagenet22k_224": model = SwinTransformer( img_size=crop_size, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinb_imagenet22k_384": model = SwinTransformer( img_size=384, embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 128 num_layers = 4 elif model_type == "swinl_imagenet22k_224": model = SwinTransformer( img_size=crop_size, embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=7, drop_path_rate=0.5, num_classes=-1, ) embed_dim = 192 num_layers = 4 feat_dim = int(embed_dim * 2 ** (num_layers - 1)) # load checkpoint model_w = os.path.join(model_root, MODEL_ZOO[model_type]) checkpoint = torch.load(model_w, map_location='cpu') state_dict = checkpoint['model'] if crop_size == 448: for k in list(state_dict.keys()): if "attn_mask" not in k: # remove prefix state_dict[k] = state_dict[k] # delete renamed or unused k else: del state_dict[k] # rename some keys for ssl models if model_type.endswith("ssl"): # rename moco pre-trained keys for k in list(state_dict.keys()): # retain only encoder_q up to before the embedding layer if k.startswith('encoder.'): # remove prefix state_dict[k[len("encoder."):]] = state_dict[k] # delete renamed or unused k del state_dict[k] model.load_state_dict(state_dict, strict=False) return model, feat_dim def build_vit_sup_models( model_type, crop_size, model_root=None, adapter_cfg=None, lora_cfg=None, load_pretrain=True, vis=False ): # image size is the size of actual image m2featdim = { "sup_vitb16_224": 768, "sup_vitb16": 768, "sup_vitl16_224": 1024, "sup_vitl16": 1024, "sup_vitb8_imagenet21k": 768, "sup_vitb16_imagenet21k": 768, "sup_vitb32_imagenet21k": 768, "sup_vitl16_imagenet21k": 1024, "sup_vitl32_imagenet21k": 1024, "sup_vith14_imagenet21k": 1280, } if adapter_cfg is not None: if adapter_cfg.MOE: model = MoSAVisionTransformer(model_type, crop_size, num_classes=-1, adapter_cfg=adapter_cfg, mid=adapter_cfg.DEEPREG) else: model = AdaptedVisionTransformer(model_type, crop_size, num_classes=-1, adapter_cfg=adapter_cfg) elif lora_cfg is not None: if lora_cfg.MOE: model = MoSLVisionTransformer(model_type, crop_size, num_classes=-1, lora_cfg=lora_cfg, mid=lora_cfg.DEEPREG) else:
model = LoRAVisionTransformer(model_type, crop_size, num_classes=-1, lora_cfg=lora_cfg)
10
2023-12-06 07:50:16+00:00
12k
khwong-c/syn-magia
tests/bundle/test_bundle.py
[ { "identifier": "Input", "path": "magia/core.py", "snippet": "class Input(Signal):\n \"\"\"\n Representing an input signal.\n It has no driver, but it is driving other signals.\n It is used by both the module declaration and the module instance.\n \"\"\"\n\n def __init__(\n ...
import random import cocotb.clock import tests.helper as helper from pathlib import Path from cocotb_test.simulator import run as sim_run from magia import Input, Module, Output, Signal
7,323
@cocotb.test() async def inst_connect_test(dut): for i in range(10): dut.d.value = random.randint(0, 0xF0) await cocotb.clock.Timer(1, units="ns") actual_value = dut.q.value expected_value = dut.d.value + 2 assert expected_value == actual_value, f"Expected {expected_value}, got {actual_value} on Entry {i}." class TestBundle: TOP = "TopModule" def test_bundle_connect_inst(self, temp_build_dir):
@cocotb.test() async def inst_connect_test(dut): for i in range(10): dut.d.value = random.randint(0, 0xF0) await cocotb.clock.Timer(1, units="ns") actual_value = dut.q.value expected_value = dut.d.value + 2 assert expected_value == actual_value, f"Expected {expected_value}, got {actual_value} on Entry {i}." class TestBundle: TOP = "TopModule" def test_bundle_connect_inst(self, temp_build_dir):
class SubModule(Module):
3
2023-12-12 22:50:43+00:00
12k
nickruggeri/hypergraph-message-passing
main_message_passing.py
[ { "identifier": "load_data", "path": "src/data/data_io.py", "snippet": "def load_data(\n real_dataset: str = \"\",\n hye_file: str = \"\",\n pickle_file: str = \"\",\n N: int | None = None,\n) -> IncidenceHypergraph:\n \"\"\"Load a hypergraph dataset.\n Utility function for loading hyp...
import logging import random import sys import numpy as np from argparse import ArgumentParser from pathlib import Path from sem.str_to_type import none_or_type from src.data.data_io import load_data from src.model import dynamic_updates from src.model.hypergraph_block_model import HypergraphBlockModel
9,668
type=none_or_type(int), default=None, help=( "Number of nodes in the configurations hypergraph. Only needed (optionally)" " when specifying hye_file." ), ) parser.add_argument( "--K", type=int, help="Number of communities in the model.", ) parser.add_argument( "--n", type=none_or_type(str), default=None, help=( "Prior parameters for the communities of the stochastic block model. " "This is a path to a file to be opened via numpy.loadtxt. " "If not provided, the value of n is initialized at random. " ), ) parser.add_argument( "--p", type=none_or_type(str), default=None, help=( "Symmetric matrix of community interaction probabilities. " "This is a path to a file to be opened via numpy.loadtxt " "If not provided, the value of p is initialized at random. " ), ) # Model training. parser.add_argument( "--train_rounds", type=int, default=1, help=( "Train with different various random initializations and " "choose only the model attaining the best log-likelihood." ), ) parser.add_argument( "--em_iter", type=int, default=20, help="Max iterations of the EM procedure.", ) parser.add_argument( "--em_thresh", type=float, default=1.0e-5, help=( "Threshold for the parameter change during EM. The difference is computed " "with respect to the affinity matrix p and the community prior n." ), ) parser.add_argument( "--mp_iter", type=int, default=2000, help="Max iterations of the message passing procedure.", ) parser.add_argument( "--mp_thresh", type=float, default=1.0e-5, help=( "Threshold for the parameter change during message passing. " "The difference is computed with respect to the log-marginal values." ), ) parser.add_argument( "--mp_patience", type=int, default=50, help=( "Number of consecutive steps where the change in log-marginals is below " "the mp_thresh before message passing is stopped." ), ) parser.add_argument( "--dirichlet_init_alpha", type=none_or_type(float), default=None, help="Dirichlet alpha utilized for the model initialization.", ) parser.add_argument( "--dropout", type=float, default=0.99, help="Dropout in the message passing updates.", ) parser.add_argument( "--n_jobs", type=int, default=-1, help=( "Maximum number of parallel jobs. " "1 means no parallelization, -1 means all the available cores." ), ) parser.add_argument( "--seed", type=none_or_type(int), default=None, help="Random seed.", ) parser.add_argument( "--logging", type=str, default="INFO", help="Logging level.", ) args = parser.parse_args() random.seed(args.seed) logging.getLogger().setLevel(args.logging.upper())
if __name__ == "__main__": parser = ArgumentParser() # Data IO. parser.add_argument( "--real_dataset", type=none_or_type(str), default=None, help="Name of a real dataset to be loaded.", ) parser.add_argument( "--hye_file", type=none_or_type(str), default=None, help=( "Path to a file containing a list of hyperedges representing a " "hypergraph.", ), ) parser.add_argument( "--pickle_file", type=none_or_type(str), default=None, help="Path to a file containing a pickle serialized hypergraph.", ) # Data parameters. parser.add_argument( "--max_hye_size", type=none_or_type(int), default=None, help=( "The maximum hyperedge size considered. This value is used to exclude " "hyperedges in the configurations hypergraph, as well as a parameter of " "the probabilistic model to compute internal quantities." ), ) parser.add_argument( "--save_dir", type=none_or_type(Path), help="Directory where results are saved." ) # Model parameters. parser.add_argument( "--N", type=none_or_type(int), default=None, help=( "Number of nodes in the configurations hypergraph. Only needed (optionally)" " when specifying hye_file." ), ) parser.add_argument( "--K", type=int, help="Number of communities in the model.", ) parser.add_argument( "--n", type=none_or_type(str), default=None, help=( "Prior parameters for the communities of the stochastic block model. " "This is a path to a file to be opened via numpy.loadtxt. " "If not provided, the value of n is initialized at random. " ), ) parser.add_argument( "--p", type=none_or_type(str), default=None, help=( "Symmetric matrix of community interaction probabilities. " "This is a path to a file to be opened via numpy.loadtxt " "If not provided, the value of p is initialized at random. " ), ) # Model training. parser.add_argument( "--train_rounds", type=int, default=1, help=( "Train with different various random initializations and " "choose only the model attaining the best log-likelihood." ), ) parser.add_argument( "--em_iter", type=int, default=20, help="Max iterations of the EM procedure.", ) parser.add_argument( "--em_thresh", type=float, default=1.0e-5, help=( "Threshold for the parameter change during EM. The difference is computed " "with respect to the affinity matrix p and the community prior n." ), ) parser.add_argument( "--mp_iter", type=int, default=2000, help="Max iterations of the message passing procedure.", ) parser.add_argument( "--mp_thresh", type=float, default=1.0e-5, help=( "Threshold for the parameter change during message passing. " "The difference is computed with respect to the log-marginal values." ), ) parser.add_argument( "--mp_patience", type=int, default=50, help=( "Number of consecutive steps where the change in log-marginals is below " "the mp_thresh before message passing is stopped." ), ) parser.add_argument( "--dirichlet_init_alpha", type=none_or_type(float), default=None, help="Dirichlet alpha utilized for the model initialization.", ) parser.add_argument( "--dropout", type=float, default=0.99, help="Dropout in the message passing updates.", ) parser.add_argument( "--n_jobs", type=int, default=-1, help=( "Maximum number of parallel jobs. " "1 means no parallelization, -1 means all the available cores." ), ) parser.add_argument( "--seed", type=none_or_type(int), default=None, help="Random seed.", ) parser.add_argument( "--logging", type=str, default="INFO", help="Logging level.", ) args = parser.parse_args() random.seed(args.seed) logging.getLogger().setLevel(args.logging.upper())
hyg = load_data(
0
2023-12-06 22:01:38+00:00
12k
kramerlab/PeerLearning
run_peer.py
[ { "identifier": "DQNPeer", "path": "dqn_peer.py", "snippet": "class DQNPeer(make_peer_class(DQN)):\n \"\"\"\n A DQN version to be used with peer learning. Therefore, it features\n a critic function\n \"\"\"\n def critic(self, observations, actions):\n q_values = self.q_net(observat...
import argparse import datetime import gym import wandb import predefined_agents # noqa: F401 import env as local_envs # noqa: F401 from pathlib import Path from stable_baselines3 import SAC, TD3 from stable_baselines3.common.utils import set_random_seed, \ update_learning_rate from wandb.integration.sb3 import WandbCallback from dqn_peer import DQNPeer from peer import PeerGroup, make_peer_class from callbacks import PeerEvalCallback from utils import str2bool, add_default_values_to_parser, \ log_reward_avg_in_wandb, add_default_values_to_train_parser, \ new_random_seed, make_env, ControllerArguments
8,226
option_on = (args.use_trust or args.use_critic or args.use_agent_value) assert (option_on and args.peer_learning) or not option_on # create results/experiments folder time_string = datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S") unique_dir = f"{time_string}__{args.job_id}" experiment_folder = args.save_dir.joinpath(args.save_name, unique_dir) experiment_folder.mkdir(exist_ok=True, parents=True) str_folder = str(experiment_folder) print("Experiment folder is", str_folder) # suppress gym warnings gym.logger.set_level(level=gym.logger.DISABLED) # seed everything set_random_seed(args.seed) # init wandb wandb.tensorboard.patch(root_logdir=str_folder) run = wandb.init(entity="jgu-wandb", config=args.__dict__, project="peer-learning", monitor_gym=True, sync_tensorboard=False, name=f"{args.save_name}__{args.job_id}", notes=f"Peer Learning with {args.agent_count} agents on " f"the {args.env.split('-')[0]} environment.", dir=str_folder, mode=args.wandb) # initialize peer group algo_args = [] peer_args = [] for i in range(args.agent_count): algo_args.append( dict(policy="MlpPolicy", verbose=1, policy_kwargs=dict( net_arch=CA.argument_for_every_agent(args.net_arch, i) ), buffer_size=args.buffer_size, batch_size=args.batch_size, gamma=args.gamma, tau=args.tau, train_freq=args.train_freq, target_update_interval=args.target_update_interval, gradient_steps=args.gradient_steps, learning_starts=args.buffer_start_size, learning_rate=CA.argument_for_every_agent(args.learning_rate, i), tensorboard_log=None, device=args.device)) peer_args.append( dict(temperature=CA.argument_for_every_agent(args.T, i), temp_decay=CA.argument_for_every_agent(args.T_decay, i), algo_args=algo_args[i], env=args.env, env_args=args.env_args, use_trust=args.use_trust, use_critic=args.use_critic, buffer_size=args.trust_buffer_size, follow_steps=args.follow_steps, use_trust_buffer=args.use_trust_buffer, solo_training=not args.peer_learning, peers_sample_with_noise=args.peers_sample_with_noise, sample_random_actions=args.sample_random_actions, init_trust_values=args.init_trust_values, sample_from_suggestions=args.sample_from_suggestions, epsilon=args.epsilon, only_follow_peers=args.only_follow_peers)) # create Peer classes SACPeer = make_peer_class(SAC) TD3Peer = make_peer_class(TD3) # create peers and peer group peers = [] callbacks = [] eval_envs = [] for i in range(args.agent_count): args_for_agent = peer_args[i] agent_algo = CA.argument_for_every_agent(args.mix_agents, i) if agent_algo == 'SAC': args_for_agent["algo_args"]["ent_coef"] = "auto" args_for_agent["algo_args"]["use_sde"] = True args_for_agent["algo_args"]["policy_kwargs"]["log_std_init"] = -3 peer = SACPeer(**args_for_agent, seed=new_random_seed()) elif agent_algo == 'TD3': peer = TD3Peer(**args_for_agent, seed=new_random_seed()) elif agent_algo == 'DQN': args_for_agent["algo_args"]["exploration_fraction"] = \ args.exploration_fraction args_for_agent["algo_args"]["exploration_final_eps"] = \ args.exploration_final_eps peer = DQNPeer(**args_for_agent, seed=new_random_seed()) elif agent_algo in ['Adversarial', 'Expert']: class_str = f"predefined_agents." \ f"{args.env.split('-')[0]}{agent_algo}" peer = eval(class_str)(**args_for_agent, seed=new_random_seed()) else: raise NotImplementedError( f"The Agent {agent_algo}" f" is not implemented") peers.append(peer) eval_env = make_env(args.env, args.n_eval_episodes, **args.env_args) # every agent gets its own callbacks callbacks.append([WandbCallback(verbose=2)]) eval_envs.append(eval_env) peer_group = PeerGroup(peers, use_agent_values=args.use_agent_value, lr=args.trust_lr, switch_ratio=args.switch_ratio, init_agent_values=args.init_agent_values, use_advantage=args.use_advantage, max_peer_epochs=args.max_peer_epochs) # create callbacks for i in range(args.agent_count):
def add_args(): # create arg parser parser = argparse.ArgumentParser(description="Peer learning.") # General parser.add_argument("--save-name", type=str, default="delete_me") parser = add_default_values_to_parser(parser) # Training training = parser.add_argument_group("Training") add_default_values_to_train_parser(training) # Peer Learning peer_learning = parser.add_argument_group("Peer Learning") peer_learning.add_argument("--follow-steps", type=int, default=10) peer_learning.add_argument("--switch-ratio", type=float, default=1, help="How many times peer training compared to " "solo training Ratio of peer learning " "episodes to solo episodes; 0 -> only " "peer learning episodes." "ratio 0 {'solo': 0, 'peer': 100}" "ratio 0.2 {'solo': 83, 'peer': 17}" "ratio 0.25 {'solo': 80, 'peer': 20}" "ratio 0.333333 {'solo': 75, 'peer': 25}" "ratio 0.5 {'solo': 67, 'peer': 33}" "ratio 1 {'solo': 50, 'peer': 50}" "ratio 2 {'solo': 33, 'peer': 67}" "ratio 3 {'solo': 25, 'peer': 75}" "ratio 4 {'solo': 20, 'peer': 80}" "ratio 5 {'solo': 17, 'peer': 83}") peer_learning.add_argument("--peer-learning", type=str2bool, nargs="?", const=True, default=True) peer_learning.add_argument("--peers-sample-with-noise", type=str2bool, nargs="?", const=True, default=True) peer_learning.add_argument("--use-agent-value", type=str2bool, nargs="?", const=True, default=True) peer_learning.add_argument("--use-trust", type=str2bool, nargs="?", const=True, default=True) peer_learning.add_argument("--use-trust-buffer", type=str2bool, nargs="?", const=True, default=True) peer_learning.add_argument("--trust-buffer-size", type=int, default=1000) peer_learning.add_argument("--use-critic", type=str2bool, nargs="?", const=True, default=True) peer_learning.add_argument("--sample_random_actions", type=str2bool, nargs="?", const=True, default=False) peer_learning.add_argument("--trust-lr", type=float, default=0.001) peer_learning.add_argument("--T", type=float, nargs='*', default=[1]) peer_learning.add_argument("--T-decay", type=float, nargs='*', default=[0]) peer_learning.add_argument("--init-trust-values", type=float, default=200) peer_learning.add_argument("--init-agent-values", type=float, default=200) peer_learning.add_argument("--use-advantage", type=str2bool, nargs="?", const=False, default=False) peer_learning.add_argument("--sample-from-suggestions", type=str2bool, nargs="?", const=False, default=False) peer_learning.add_argument("--epsilon", type=float, default=0.0) peer_learning.add_argument("--max-peer-epochs", type=int, default=1_000_000_000) peer_learning.add_argument("--only-follow-peers", type=str2bool, nargs="?", const=False, default=False) return parser if __name__ == '__main__': # parse args arg_parser = add_args() args = arg_parser.parse_args() CA = ControllerArguments(args.agent_count) # assert if any peer learning strategy is chosen peer learning must be True option_on = (args.use_trust or args.use_critic or args.use_agent_value) assert (option_on and args.peer_learning) or not option_on # create results/experiments folder time_string = datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S") unique_dir = f"{time_string}__{args.job_id}" experiment_folder = args.save_dir.joinpath(args.save_name, unique_dir) experiment_folder.mkdir(exist_ok=True, parents=True) str_folder = str(experiment_folder) print("Experiment folder is", str_folder) # suppress gym warnings gym.logger.set_level(level=gym.logger.DISABLED) # seed everything set_random_seed(args.seed) # init wandb wandb.tensorboard.patch(root_logdir=str_folder) run = wandb.init(entity="jgu-wandb", config=args.__dict__, project="peer-learning", monitor_gym=True, sync_tensorboard=False, name=f"{args.save_name}__{args.job_id}", notes=f"Peer Learning with {args.agent_count} agents on " f"the {args.env.split('-')[0]} environment.", dir=str_folder, mode=args.wandb) # initialize peer group algo_args = [] peer_args = [] for i in range(args.agent_count): algo_args.append( dict(policy="MlpPolicy", verbose=1, policy_kwargs=dict( net_arch=CA.argument_for_every_agent(args.net_arch, i) ), buffer_size=args.buffer_size, batch_size=args.batch_size, gamma=args.gamma, tau=args.tau, train_freq=args.train_freq, target_update_interval=args.target_update_interval, gradient_steps=args.gradient_steps, learning_starts=args.buffer_start_size, learning_rate=CA.argument_for_every_agent(args.learning_rate, i), tensorboard_log=None, device=args.device)) peer_args.append( dict(temperature=CA.argument_for_every_agent(args.T, i), temp_decay=CA.argument_for_every_agent(args.T_decay, i), algo_args=algo_args[i], env=args.env, env_args=args.env_args, use_trust=args.use_trust, use_critic=args.use_critic, buffer_size=args.trust_buffer_size, follow_steps=args.follow_steps, use_trust_buffer=args.use_trust_buffer, solo_training=not args.peer_learning, peers_sample_with_noise=args.peers_sample_with_noise, sample_random_actions=args.sample_random_actions, init_trust_values=args.init_trust_values, sample_from_suggestions=args.sample_from_suggestions, epsilon=args.epsilon, only_follow_peers=args.only_follow_peers)) # create Peer classes SACPeer = make_peer_class(SAC) TD3Peer = make_peer_class(TD3) # create peers and peer group peers = [] callbacks = [] eval_envs = [] for i in range(args.agent_count): args_for_agent = peer_args[i] agent_algo = CA.argument_for_every_agent(args.mix_agents, i) if agent_algo == 'SAC': args_for_agent["algo_args"]["ent_coef"] = "auto" args_for_agent["algo_args"]["use_sde"] = True args_for_agent["algo_args"]["policy_kwargs"]["log_std_init"] = -3 peer = SACPeer(**args_for_agent, seed=new_random_seed()) elif agent_algo == 'TD3': peer = TD3Peer(**args_for_agent, seed=new_random_seed()) elif agent_algo == 'DQN': args_for_agent["algo_args"]["exploration_fraction"] = \ args.exploration_fraction args_for_agent["algo_args"]["exploration_final_eps"] = \ args.exploration_final_eps peer = DQNPeer(**args_for_agent, seed=new_random_seed()) elif agent_algo in ['Adversarial', 'Expert']: class_str = f"predefined_agents." \ f"{args.env.split('-')[0]}{agent_algo}" peer = eval(class_str)(**args_for_agent, seed=new_random_seed()) else: raise NotImplementedError( f"The Agent {agent_algo}" f" is not implemented") peers.append(peer) eval_env = make_env(args.env, args.n_eval_episodes, **args.env_args) # every agent gets its own callbacks callbacks.append([WandbCallback(verbose=2)]) eval_envs.append(eval_env) peer_group = PeerGroup(peers, use_agent_values=args.use_agent_value, lr=args.trust_lr, switch_ratio=args.switch_ratio, init_agent_values=args.init_agent_values, use_advantage=args.use_advantage, max_peer_epochs=args.max_peer_epochs) # create callbacks for i in range(args.agent_count):
peer_callback = PeerEvalCallback(eval_env=eval_envs[i],
3
2023-12-13 10:40:55+00:00
12k
ZS-YANG/FemtoDet-v3
projects/Detic_new/detic/detic.py
[ { "identifier": "LVISV1Dataset", "path": "mmdet/datasets/lvis.py", "snippet": "class LVISV1Dataset(LVISDataset):\n \"\"\"LVIS v1 dataset for detection.\"\"\"\n\n METAINFO = {\n 'classes':\n ('aerosol_can', 'air_conditioner', 'airplane', 'alarm_clock',\n 'alcohol', 'alligator'...
import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import clip from typing import List, Union from mmengine.logging import print_log from torch import Tensor from mmdet.datasets import LVISV1Dataset from mmdet.models.detectors.cascade_rcnn import CascadeRCNN from mmdet.registry import MODELS from mmdet.structures import SampleList from clip.simple_tokenizer import SimpleTokenizer from mmdet.datasets import CocoDataset from mmdet.datasets import CityscapesDataset from mmdet.datasets import VOCDataset from mmdet.datasets import OpenImagesDataset from mmdet.datasets import LVISV1Dataset
8,249
# Copyright (c) OpenMMLab. All rights reserved. class CLIPTextEncoder(nn.Module): def __init__(self, model_name='ViT-B/32'): super().__init__() self.tokenizer = SimpleTokenizer() pretrained_model, _ = clip.load(model_name, device='cpu') self.clip = pretrained_model @property def device(self): return self.clip.device @property def dtype(self): return self.clip.dtype def tokenize(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: if isinstance(texts, str): texts = [texts] sot_token = self.tokenizer.encoder['<|startoftext|>'] eot_token = self.tokenizer.encoder['<|endoftext|>'] all_tokens = [[sot_token] + self.tokenizer.encode(text) + [eot_token] for text in texts] result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: st = torch.randint(len(tokens) - context_length + 1, (1, ))[0].item() tokens = tokens[st:st + context_length] result[i, :len(tokens)] = torch.tensor(tokens) return result def forward(self, text): text = self.tokenize(text) text_features = self.clip.encode_text(text) return text_features def get_class_weight(original_caption, prompt_prefix='a '): if isinstance(original_caption, str): if original_caption == 'coco': class_names = CocoDataset.METAINFO['classes'] elif original_caption == 'cityscapes': class_names = CityscapesDataset.METAINFO['classes'] elif original_caption == 'voc': class_names = VOCDataset.METAINFO['classes'] elif original_caption == 'openimages': class_names = OpenImagesDataset.METAINFO['classes'] elif original_caption == 'lvis': class_names = LVISV1Dataset.METAINFO['classes'] else: if not original_caption.endswith('.'): original_caption = original_caption + ' . ' original_caption = original_caption.split(' . ') class_names = list(filter(lambda x: len(x) > 0, original_caption)) # for test.py else: class_names = list(original_caption) text_encoder = CLIPTextEncoder() text_encoder.eval() texts = [prompt_prefix + x for x in class_names] print_log(f'Computing text embeddings for {len(class_names)} classes.') embeddings = text_encoder(texts).detach().permute(1, 0).contiguous().cpu() return class_names, embeddings def reset_cls_layer_weight(roi_head, weight): if type(weight) == str: print_log(f'Resetting cls_layer_weight from file: {weight}') zs_weight = torch.tensor( np.load(weight), dtype=torch.float32).permute(1, 0).contiguous() # D x C else: zs_weight = weight zs_weight = torch.cat( [zs_weight, zs_weight.new_zeros( (zs_weight.shape[0], 1))], dim=1) # D x (C + 1) zs_weight = F.normalize(zs_weight, p=2, dim=0) zs_weight = zs_weight.to('cuda') num_classes = zs_weight.shape[-1] for bbox_head in roi_head.bbox_head: bbox_head.num_classes = num_classes del bbox_head.fc_cls.zs_weight bbox_head.fc_cls.zs_weight = zs_weight
# Copyright (c) OpenMMLab. All rights reserved. class CLIPTextEncoder(nn.Module): def __init__(self, model_name='ViT-B/32'): super().__init__() self.tokenizer = SimpleTokenizer() pretrained_model, _ = clip.load(model_name, device='cpu') self.clip = pretrained_model @property def device(self): return self.clip.device @property def dtype(self): return self.clip.dtype def tokenize(self, texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: if isinstance(texts, str): texts = [texts] sot_token = self.tokenizer.encoder['<|startoftext|>'] eot_token = self.tokenizer.encoder['<|endoftext|>'] all_tokens = [[sot_token] + self.tokenizer.encode(text) + [eot_token] for text in texts] result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) for i, tokens in enumerate(all_tokens): if len(tokens) > context_length: st = torch.randint(len(tokens) - context_length + 1, (1, ))[0].item() tokens = tokens[st:st + context_length] result[i, :len(tokens)] = torch.tensor(tokens) return result def forward(self, text): text = self.tokenize(text) text_features = self.clip.encode_text(text) return text_features def get_class_weight(original_caption, prompt_prefix='a '): if isinstance(original_caption, str): if original_caption == 'coco': class_names = CocoDataset.METAINFO['classes'] elif original_caption == 'cityscapes': class_names = CityscapesDataset.METAINFO['classes'] elif original_caption == 'voc': class_names = VOCDataset.METAINFO['classes'] elif original_caption == 'openimages': class_names = OpenImagesDataset.METAINFO['classes'] elif original_caption == 'lvis': class_names = LVISV1Dataset.METAINFO['classes'] else: if not original_caption.endswith('.'): original_caption = original_caption + ' . ' original_caption = original_caption.split(' . ') class_names = list(filter(lambda x: len(x) > 0, original_caption)) # for test.py else: class_names = list(original_caption) text_encoder = CLIPTextEncoder() text_encoder.eval() texts = [prompt_prefix + x for x in class_names] print_log(f'Computing text embeddings for {len(class_names)} classes.') embeddings = text_encoder(texts).detach().permute(1, 0).contiguous().cpu() return class_names, embeddings def reset_cls_layer_weight(roi_head, weight): if type(weight) == str: print_log(f'Resetting cls_layer_weight from file: {weight}') zs_weight = torch.tensor( np.load(weight), dtype=torch.float32).permute(1, 0).contiguous() # D x C else: zs_weight = weight zs_weight = torch.cat( [zs_weight, zs_weight.new_zeros( (zs_weight.shape[0], 1))], dim=1) # D x (C + 1) zs_weight = F.normalize(zs_weight, p=2, dim=0) zs_weight = zs_weight.to('cuda') num_classes = zs_weight.shape[-1] for bbox_head in roi_head.bbox_head: bbox_head.num_classes = num_classes del bbox_head.fc_cls.zs_weight bbox_head.fc_cls.zs_weight = zs_weight
@MODELS.register_module()
2
2023-12-11 15:23:03+00:00
12k
merlresearch/PixPNet
pixpnet/protonets/prp/prp.py
[ { "identifier": "AdaptiveAvgPool2DWrapperFct", "path": "pixpnet/protonets/prp/lrp_general6.py", "snippet": "class AdaptiveAvgPool2DWrapperFct(torch.autograd.Function):\n \"\"\"\n We can implement our own custom autograd Functions by subclassing\n torch.autograd.Function and implementing the for...
import copy import torch from collections import OrderedDict from torch import nn from torchvision import datasets from pixpnet.protonets.prp.lrp_general6 import ( AdaptiveAvgPool2DWrapperFct, Conv2DBeta0WrapperFct, CosineDistLRPClass, EltwiseSumStacked2EpsWrapperFct, L2LRPClass, LinearLayerEpsWrapperFct, MaxPool2DWrapperFct, ReluWrapperFct, SigmoidWrapperFct, SumStacked2, bnafterconv_overwrite_intoconv, get_lrpwrapperformodule, resetbn, ) from pixpnet.protonets.prp.resnet_features import BasicBlock, Bottleneck, ResNetFeatures
10,124
""" Copyright (c) 2022-2023 Mitsubishi Electric Research Laboratories (MERL) Copyright (c) 2022 Srishti Gautam, Marina Hohne, Robert Jenssen, Michael Kampffmeyer SPDX-License-Identifier: AGPL-3.0-or-later SPDX-License-Identifier: MIT """ def imshow_im(hm, q=100): hm = hm.squeeze().sum(dim=0).detach() return hm # partial replacement of BN, use own classes, no pretrained loading class TorchModuleNotFoundError(Exception): pass class BasicBlockFused(BasicBlock): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlockFused, self).__init__(inplanes, planes, stride, downsample) # own self.elt = SumStacked2() # eltwisesum2() def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: identity = self.downsample(x) out = self.elt(torch.stack([out, identity], dim=0)) # self.elt(out,identity) out = self.relu(out) return out
""" Copyright (c) 2022-2023 Mitsubishi Electric Research Laboratories (MERL) Copyright (c) 2022 Srishti Gautam, Marina Hohne, Robert Jenssen, Michael Kampffmeyer SPDX-License-Identifier: AGPL-3.0-or-later SPDX-License-Identifier: MIT """ def imshow_im(hm, q=100): hm = hm.squeeze().sum(dim=0).detach() return hm # partial replacement of BN, use own classes, no pretrained loading class TorchModuleNotFoundError(Exception): pass class BasicBlockFused(BasicBlock): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlockFused, self).__init__(inplanes, planes, stride, downsample) # own self.elt = SumStacked2() # eltwisesum2() def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: identity = self.downsample(x) out = self.elt(torch.stack([out, identity], dim=0)) # self.elt(out,identity) out = self.relu(out) return out
class BottleneckFused(Bottleneck):
14
2023-12-06 23:49:31+00:00
12k
dvmazur/mixtral-offloading
src/build_model.py
[ { "identifier": "ExpertCache", "path": "src/expert_cache.py", "snippet": "class ExpertCache:\n def __init__(self, make_module: callable, main_size: int, offload_size: int, buffer_size: int):\n \"\"\"Dynamically loads an array of modules with identical hyperparameters\"\"\"\n self.module...
import os import json import typing as tp import torch from functools import cache from dataclasses import dataclass from torch import nn from transformers import AutoConfig from transformers.models.mixtral import MixtralForCausalLM, MixtralConfig from safetensors.torch import load_file from torch import nn from tqdm.auto import trange from hqq.core.quantize import BaseQuantizeConfig from .expert_cache import ExpertCache from .expert_wrapper import MixtralExpertWrapper from .custom_layers import ( HQQLinearTritonSavable, MixtralBLockSparseTop2MLP_HQQ, SparseMoeWrapper, ) from .utils import with_default_dtype
7,444
for layer in model.model.layers: layer.block_sparse_moe.gate = nn.Linear( config.hidden_size, config.num_local_experts, dtype=torch.float16, device=device, bias=False, ) layer.self_attn.q_proj = patch_fct_hqq( (hidden_size, num_heads * head_dim), attn_quant_config ) layer.self_attn.k_proj = patch_fct_hqq( (hidden_size, num_key_value_heads * head_dim), attn_quant_config ) layer.self_attn.v_proj = patch_fct_hqq( (hidden_size, num_key_value_heads * head_dim), attn_quant_config ) layer.self_attn.o_proj = patch_fct_hqq( (hidden_size, num_heads * head_dim), attn_quant_config ) @cache def get_default_ffn_quant_config(ffn_dim: int = 14336, hidden_dim: int = 4096): quant_config = BaseQuantizeConfig( nbits=2, group_size=16, quant_zero=True, quant_scale=True, ) meta1 = HQQLinearTritonSavable.get_hqq_meta((hidden_dim, ffn_dim), quant_config) meta2 = HQQLinearTritonSavable.get_hqq_meta((ffn_dim, hidden_dim), quant_config) return quant_config, meta1, meta2 def make_empty_expert( model_config: MixtralConfig, quant_config: QuantConfig ) -> MixtralBLockSparseTop2MLP_HQQ: meta1, meta2 = quant_config.get_ffn_metas( model_config.hidden_size, model_config.intermediate_size ) return MixtralBLockSparseTop2MLP_HQQ( model_config, quant_config.ffn_config, meta1, meta2, ) def make_and_load_expert_wrapper( config: MixtralConfig, quant_config: QuantConfig, states_dir: str, expert_uid: tuple[int, int], device: torch.device, ) -> MixtralExpertWrapper: layer_idx, expert_idx = expert_uid index_path = os.path.join(states_dir, "model.safetensors.index.json") with open(index_path) as f: module_idx = f"model.layers.{layer_idx}.block_sparse_moe.experts.{expert_idx}" state_fpath = json.load(f)["weight_map"][f"{module_idx}.w1.W_q"] state_dict = load_file(os.path.join(states_dir, state_fpath), device=str(device)) expert = make_empty_expert(config, quant_config) expert.load_state_dict(state_dict, strict=True) return MixtralExpertWrapper(expert, device) def load_00_expert_state_dict(states_dir: str, device: torch.device): index_path = os.path.join(states_dir, "model.safetensors.index.json") with open(index_path) as f: module_idx = f"model.layers.0.block_sparse_moe.experts.0" state_fpath = json.load(f)["weight_map"][f"{module_idx}.w1.W_q"] return load_file(os.path.join(states_dir, state_fpath), device=str(device)) def build_model( device: torch.device, quant_config: QuantConfig, offload_config: OffloadConfig, state_path: str, ): model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1" state_dict_00 = load_00_expert_state_dict(state_path, device) def _make_module(): config = AutoConfig.from_pretrained(model_name) expert = make_empty_expert(config, quant_config) expert.load_state_dict(state_dict_00) return MixtralExpertWrapper(expert, device=device) with device, with_default_dtype(torch.float16): model = MixtralForCausalLM( AutoConfig.from_pretrained( model_name, num_local_experts=0, torch_dtype=torch.float16, device_map=device, ), ) model_config = AutoConfig.from_pretrained(model_name) replace_attn_layers(model, model_config, quant_config, device) state_index_path = os.path.join(state_path, "model.safetensors.index.json") with open(state_index_path) as f: weight_map = json.load(f)["weight_map"] trunk_state_path = os.path.join( state_path, weight_map["model.embed_tokens.weight"], ) model.load_state_dict(load_file(trunk_state_path, device=str(device)), strict=True)
@dataclass(frozen=True) class OffloadConfig: main_size: int offload_size: int buffer_size: int offload_per_layer: int class QuantConfig: def __init__( self, ffn_config: BaseQuantizeConfig, attn_config: BaseQuantizeConfig, ): self.ffn_config = ffn_config self.attn_config = attn_config @cache def get_ffn_metas(self, hidden_dim: int, ffn_dim: int) -> tuple[tp.Any, tp.Any]: return ( HQQLinearTritonSavable.get_hqq_meta((hidden_dim, ffn_dim), self.ffn_config), HQQLinearTritonSavable.get_hqq_meta((ffn_dim, hidden_dim), self.ffn_config), ) def replace_attn_layers( model: MixtralForCausalLM, config: MixtralConfig, quant_config: QuantConfig, device: torch.device, ) -> None: attn_quant_config = quant_config.attn_config hidden_size = config.hidden_size num_heads = config.num_attention_heads head_dim = hidden_size // num_heads num_key_value_heads = config.num_key_value_heads shapes = [ (hidden_size, num_heads * head_dim), (hidden_size, num_key_value_heads * head_dim), (hidden_size, num_key_value_heads * head_dim), (num_heads * head_dim, hidden_size), ] shape_to_meta = { shape: HQQLinearTritonSavable.get_hqq_meta(shape, attn_quant_config) for shape in shapes } def patch_fct_hqq(shape, quant_config): meta = shape_to_meta[shape] layer = HQQLinearTritonSavable(None, quant_config, meta=meta) return layer for layer in model.model.layers: layer.block_sparse_moe.gate = nn.Linear( config.hidden_size, config.num_local_experts, dtype=torch.float16, device=device, bias=False, ) layer.self_attn.q_proj = patch_fct_hqq( (hidden_size, num_heads * head_dim), attn_quant_config ) layer.self_attn.k_proj = patch_fct_hqq( (hidden_size, num_key_value_heads * head_dim), attn_quant_config ) layer.self_attn.v_proj = patch_fct_hqq( (hidden_size, num_key_value_heads * head_dim), attn_quant_config ) layer.self_attn.o_proj = patch_fct_hqq( (hidden_size, num_heads * head_dim), attn_quant_config ) @cache def get_default_ffn_quant_config(ffn_dim: int = 14336, hidden_dim: int = 4096): quant_config = BaseQuantizeConfig( nbits=2, group_size=16, quant_zero=True, quant_scale=True, ) meta1 = HQQLinearTritonSavable.get_hqq_meta((hidden_dim, ffn_dim), quant_config) meta2 = HQQLinearTritonSavable.get_hqq_meta((ffn_dim, hidden_dim), quant_config) return quant_config, meta1, meta2 def make_empty_expert( model_config: MixtralConfig, quant_config: QuantConfig ) -> MixtralBLockSparseTop2MLP_HQQ: meta1, meta2 = quant_config.get_ffn_metas( model_config.hidden_size, model_config.intermediate_size ) return MixtralBLockSparseTop2MLP_HQQ( model_config, quant_config.ffn_config, meta1, meta2, ) def make_and_load_expert_wrapper( config: MixtralConfig, quant_config: QuantConfig, states_dir: str, expert_uid: tuple[int, int], device: torch.device, ) -> MixtralExpertWrapper: layer_idx, expert_idx = expert_uid index_path = os.path.join(states_dir, "model.safetensors.index.json") with open(index_path) as f: module_idx = f"model.layers.{layer_idx}.block_sparse_moe.experts.{expert_idx}" state_fpath = json.load(f)["weight_map"][f"{module_idx}.w1.W_q"] state_dict = load_file(os.path.join(states_dir, state_fpath), device=str(device)) expert = make_empty_expert(config, quant_config) expert.load_state_dict(state_dict, strict=True) return MixtralExpertWrapper(expert, device) def load_00_expert_state_dict(states_dir: str, device: torch.device): index_path = os.path.join(states_dir, "model.safetensors.index.json") with open(index_path) as f: module_idx = f"model.layers.0.block_sparse_moe.experts.0" state_fpath = json.load(f)["weight_map"][f"{module_idx}.w1.W_q"] return load_file(os.path.join(states_dir, state_fpath), device=str(device)) def build_model( device: torch.device, quant_config: QuantConfig, offload_config: OffloadConfig, state_path: str, ): model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1" state_dict_00 = load_00_expert_state_dict(state_path, device) def _make_module(): config = AutoConfig.from_pretrained(model_name) expert = make_empty_expert(config, quant_config) expert.load_state_dict(state_dict_00) return MixtralExpertWrapper(expert, device=device) with device, with_default_dtype(torch.float16): model = MixtralForCausalLM( AutoConfig.from_pretrained( model_name, num_local_experts=0, torch_dtype=torch.float16, device_map=device, ), ) model_config = AutoConfig.from_pretrained(model_name) replace_attn_layers(model, model_config, quant_config, device) state_index_path = os.path.join(state_path, "model.safetensors.index.json") with open(state_index_path) as f: weight_map = json.load(f)["weight_map"] trunk_state_path = os.path.join( state_path, weight_map["model.embed_tokens.weight"], ) model.load_state_dict(load_file(trunk_state_path, device=str(device)), strict=True)
expert_cache = ExpertCache(
0
2023-12-15 03:32:35+00:00
12k
open-mmlab/PIA
app.py
[ { "identifier": "I2VPipeline", "path": "animatediff/pipelines/i2v_pipeline.py", "snippet": "class I2VPipeline(DiffusionPipeline, IPAdapterMixin, TextualInversionLoaderMixin):\n _optional_components = []\n\n def __init__(\n self,\n vae: AutoencoderKL,\n text_encoder: CLIPTextMo...
import json import os import os.path as osp import random import gradio as gr import numpy as np import torch from argparse import ArgumentParser from datetime import datetime from glob import glob from diffusers import DDIMScheduler, EulerDiscreteScheduler, PNDMScheduler from omegaconf import OmegaConf from PIL import Image from animatediff.pipelines import I2VPipeline from animatediff.utils.util import save_videos_grid
9,273
self.basedir, args.save_path, datetime.now().strftime("Gradio-%Y-%m-%dT%H-%M-%S")) self.savedir_sample = os.path.join(self.savedir, "sample") os.makedirs(self.savedir, exist_ok=True) self.stable_diffusion_list = [] self.motion_module_list = [] self.personalized_model_list = [] self.refresh_personalized_model() self.pipeline = None self.inference_config = OmegaConf.load(args.config) self.stable_diffusion_dir = self.inference_config.pretrained_model_path self.pia_path = self.inference_config.generate.model_path self.loaded = False def refresh_personalized_model(self): personalized_model_list = glob(os.path.join( self.personalized_model_dir, "*.safetensors")) self.personalized_model_list = [ os.path.basename(p) for p in personalized_model_list] def get_ip_apdater_folder(self): file_list = os.listdir(self.ip_adapter_dir) if not file_list: return False if not 'ip-adapter_sd15.bin' not in file_list: print('Cannot find "ip-adapter_sd15.bin" ' f'under {self.ip_adapter_dir}') return False if not 'image_encoder' not in file_list: print(f'Cannot find "image_encoder" under {self.ip_adapter_dir}') return False return True def load_model(self, dreambooth_path=None, lora_path=None, lora_alpha=1.0, enable_ip_adapter=True): gr.Info('Start Load Models...') print('Start Load Models...') if lora_path and lora_path.upper() != 'NONE': lora_path = osp.join(self.personalized_model_dir, lora_path) else: lora_path = None if dreambooth_path and dreambooth_path.upper() != 'NONE': dreambooth_path = osp.join( self.personalized_model_dir, dreambooth_path) else: dreambooth_path = None if enable_ip_adapter: if not self.get_ip_apdater_folder(): print('Load IP-Adapter from remote.') ip_adapter_path = 'h94/IP-Adapter' else: ip_adapter_path = self.ip_adapter_dir else: ip_adapter_path = None self.pipeline = I2VPipeline.build_pipeline( self.inference_config, self.stable_diffusion_dir, unet_path=self.pia_path, dreambooth_path=dreambooth_path, lora_path=lora_path, lora_alpha=lora_alpha, ip_adapter_path=ip_adapter_path) gr.Info('Load Finish!') print('Load Finish!') self.loaded = True return 'Load' def animate( self, init_img, motion_scale, prompt_textbox, negative_prompt_textbox, sampler_dropdown, sample_step_slider, length_slider, cfg_scale_slider, seed_textbox, ip_adapter_scale, max_size, progress=gr.Progress(), ): if not self.loaded: raise gr.Error(f"Please load model first!") if seed_textbox != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox)) else: torch.seed() seed = torch.initial_seed() init_img, h, w = preprocess_img(init_img, max_size) sample = self.pipeline( image=init_img, prompt=prompt_textbox, negative_prompt=negative_prompt_textbox, num_inference_steps=sample_step_slider, guidance_scale=cfg_scale_slider, width=w, height=h, video_length=16, mask_sim_template_idx=motion_scale, ip_adapter_scale=ip_adapter_scale, progress_fn=progress, ).videos save_sample_path = os.path.join( self.savedir_sample, f"{sample_idx}.mp4")
sample_idx = 0 scheduler_dict = { "DDIM": DDIMScheduler, "Euler": EulerDiscreteScheduler, "PNDM": PNDMScheduler, } css = """ .toolbutton { margin-buttom: 0em 0em 0em 0em; max-width: 2.5em; min-width: 2.5em !important; height: 2.5em; } """ parser = ArgumentParser() parser.add_argument('--config', type=str, default='example/config/base.yaml') parser.add_argument('--server-name', type=str, default='0.0.0.0') parser.add_argument('--port', type=int, default=7860) parser.add_argument('--share', action='store_true') parser.add_argument('--save-path', default='samples') args = parser.parse_args() N_PROMPT = ('wrong white balance, dark, sketches,worst quality,low quality, ' 'deformed, distorted, disfigured, bad eyes, wrong lips, ' 'weird mouth, bad teeth, mutated hands and fingers, bad anatomy,' 'wrong anatomy, amputation, extra limb, missing limb, ' 'floating,limbs, disconnected limbs, mutation, ugly, disgusting, ' 'bad_pictures, negative_hand-neg') def preprocess_img(img_np, max_size: int = 512): ori_image = Image.fromarray(img_np).convert('RGB') width, height = ori_image.size long_edge = max(width, height) if long_edge > max_size: scale_factor = max_size / long_edge else: scale_factor = 1 width = int(width * scale_factor) height = int(height * scale_factor) ori_image = ori_image.resize((width, height)) if (width % 8 != 0) or (height % 8 != 0): in_width = (width // 8) * 8 in_height = (height // 8) * 8 else: in_width = width in_height = height in_image = ori_image in_image = ori_image.resize((in_width, in_height)) in_image_np = np.array(in_image) return in_image_np, in_height, in_width class AnimateController: def __init__(self): # config dirs self.basedir = os.getcwd() self.personalized_model_dir = os.path.join( self.basedir, "models", "DreamBooth_LoRA") self.ip_adapter_dir = os.path.join( self.basedir, "models", "IP_Adapter") self.savedir = os.path.join( self.basedir, args.save_path, datetime.now().strftime("Gradio-%Y-%m-%dT%H-%M-%S")) self.savedir_sample = os.path.join(self.savedir, "sample") os.makedirs(self.savedir, exist_ok=True) self.stable_diffusion_list = [] self.motion_module_list = [] self.personalized_model_list = [] self.refresh_personalized_model() self.pipeline = None self.inference_config = OmegaConf.load(args.config) self.stable_diffusion_dir = self.inference_config.pretrained_model_path self.pia_path = self.inference_config.generate.model_path self.loaded = False def refresh_personalized_model(self): personalized_model_list = glob(os.path.join( self.personalized_model_dir, "*.safetensors")) self.personalized_model_list = [ os.path.basename(p) for p in personalized_model_list] def get_ip_apdater_folder(self): file_list = os.listdir(self.ip_adapter_dir) if not file_list: return False if not 'ip-adapter_sd15.bin' not in file_list: print('Cannot find "ip-adapter_sd15.bin" ' f'under {self.ip_adapter_dir}') return False if not 'image_encoder' not in file_list: print(f'Cannot find "image_encoder" under {self.ip_adapter_dir}') return False return True def load_model(self, dreambooth_path=None, lora_path=None, lora_alpha=1.0, enable_ip_adapter=True): gr.Info('Start Load Models...') print('Start Load Models...') if lora_path and lora_path.upper() != 'NONE': lora_path = osp.join(self.personalized_model_dir, lora_path) else: lora_path = None if dreambooth_path and dreambooth_path.upper() != 'NONE': dreambooth_path = osp.join( self.personalized_model_dir, dreambooth_path) else: dreambooth_path = None if enable_ip_adapter: if not self.get_ip_apdater_folder(): print('Load IP-Adapter from remote.') ip_adapter_path = 'h94/IP-Adapter' else: ip_adapter_path = self.ip_adapter_dir else: ip_adapter_path = None self.pipeline = I2VPipeline.build_pipeline( self.inference_config, self.stable_diffusion_dir, unet_path=self.pia_path, dreambooth_path=dreambooth_path, lora_path=lora_path, lora_alpha=lora_alpha, ip_adapter_path=ip_adapter_path) gr.Info('Load Finish!') print('Load Finish!') self.loaded = True return 'Load' def animate( self, init_img, motion_scale, prompt_textbox, negative_prompt_textbox, sampler_dropdown, sample_step_slider, length_slider, cfg_scale_slider, seed_textbox, ip_adapter_scale, max_size, progress=gr.Progress(), ): if not self.loaded: raise gr.Error(f"Please load model first!") if seed_textbox != -1 and seed_textbox != "": torch.manual_seed(int(seed_textbox)) else: torch.seed() seed = torch.initial_seed() init_img, h, w = preprocess_img(init_img, max_size) sample = self.pipeline( image=init_img, prompt=prompt_textbox, negative_prompt=negative_prompt_textbox, num_inference_steps=sample_step_slider, guidance_scale=cfg_scale_slider, width=w, height=h, video_length=16, mask_sim_template_idx=motion_scale, ip_adapter_scale=ip_adapter_scale, progress_fn=progress, ).videos save_sample_path = os.path.join( self.savedir_sample, f"{sample_idx}.mp4")
save_videos_grid(sample, save_sample_path)
1
2023-12-21 03:29:34+00:00
12k
xinghaochen/TinySAM
tinysam/hierarchical_mask_generator.py
[ { "identifier": "Sam", "path": "tinysam/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: Union[ImageEncoderViT, TinyViT],\n prompt_encoder: PromptEncoder,\n mask...
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
10,399
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_side = points_per_side self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.high_score_thresh = high_score_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 def set_point_grids(self, point_grids): self.point_grids = point_grids def set_points_per_side(self, points_per_side): self.point_grids = build_all_layer_point_grids( points_per_side, 0, 1, ) @torch.no_grad() def set_image(self, image: np.ndarray) -> MaskData: # Crop the image and calculate embeddings self.predictor.set_image(image) @torch.no_grad() def hierarchical_generate(self, image: np.ndarray) -> List[Dict[str, Any]]: self.set_image(image) self.set_points_per_side(self.points_per_side // 4) ori_masks, or_results = self.generate(image, True) ih, iw, _ = image.shape hstride = ih // self.points_per_side wstride = iw // self.points_per_side new_points = [] pass_counter = 0 full_point_grids = np.array(self.point_grids) for mask in range(full_point_grids.shape[1]): point_coords = [full_point_grids[0, mask, 0] * iw, full_point_grids[0, mask, 1] * ih] for sy in [-1, 0, 1]: for sx in [-1, 0, 1]: if (sy == 0 and sx == 0) or or_results[int(point_coords[0] + wstride * sy), int(point_coords[1] + hstride * sx)]: continue new_points.append([(point_coords[0] + wstride * sy) / iw, (point_coords[1] + hstride * sx) / ih]) if point_coords[0] + wstride * 2 < iw: for sx in [-1, 0, 1]: if or_results[int(point_coords[0] + wstride * 2), int(point_coords[1] + hstride * sx)]: continue new_points.append([(point_coords[0] + wstride * 2) / iw, (point_coords[1] + hstride * sx) / ih]) if point_coords[1] + hstride * 2 < ih: for sy in [-1, 0, 1]: if or_results[int(point_coords[0] + wstride * sy), int(point_coords[1] + hstride * 2)]: continue new_points.append([(point_coords[0] + wstride * sy) / iw, (point_coords[1] + hstride * 2) / ih]) if point_coords[0] + wstride * 2 < iw and point_coords[1] + hstride * 2 < ih: if or_results[int(point_coords[0] + wstride * 2), int(point_coords[1] + hstride * 2)]: continue new_points.append([(point_coords[0] + wstride * 2) / iw, (point_coords[1] + hstride * 2) / ih]) self.set_point_grids([np.array(new_points)]) new_masks = self.generate(image, False) new_masks.cat(ori_masks) new_masks = self.post_process(image, new_masks) return new_masks @torch.no_grad() def generate(self, image: np.ndarray, need_high: bool) -> MaskData: orig_size = image.shape[:2] # Get points for this crop points_scale = np.array(orig_size)[None, ::-1] points_for_image = self.point_grids[0] * points_scale # Generate masks for this crop in batches data = MaskData() for (points,) in batch_iterator(self.points_per_batch, points_for_image): orig_h, orig_w = orig_size # Run model on this batch transformed_points = self.predictor.transform.apply_coords(points, orig_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], return_logits=True, ) # Serialize predictions and store in MaskData batch_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 if self.pred_iou_thresh > 0.0: keep_mask = batch_data["iou_preds"] > self.pred_iou_thresh batch_data.filter(keep_mask) # Calculate stability score
# Copyright 2023 Huawei Technologies Co., Ltd # # 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. # ============================================================================ class SamHierarchicalMaskGenerator: def __init__( self, model: Sam, points_per_side: Optional[int] = 32, points_per_batch: int = 64, pred_iou_thresh: float = 0.88, high_score_thresh: float = 8.5, 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. high_score_thresh (float): A filtering threshold in [-inf,inf], to find out the unmasked area for the next generation. 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_side = points_per_side self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.high_score_thresh = high_score_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 def set_point_grids(self, point_grids): self.point_grids = point_grids def set_points_per_side(self, points_per_side): self.point_grids = build_all_layer_point_grids( points_per_side, 0, 1, ) @torch.no_grad() def set_image(self, image: np.ndarray) -> MaskData: # Crop the image and calculate embeddings self.predictor.set_image(image) @torch.no_grad() def hierarchical_generate(self, image: np.ndarray) -> List[Dict[str, Any]]: self.set_image(image) self.set_points_per_side(self.points_per_side // 4) ori_masks, or_results = self.generate(image, True) ih, iw, _ = image.shape hstride = ih // self.points_per_side wstride = iw // self.points_per_side new_points = [] pass_counter = 0 full_point_grids = np.array(self.point_grids) for mask in range(full_point_grids.shape[1]): point_coords = [full_point_grids[0, mask, 0] * iw, full_point_grids[0, mask, 1] * ih] for sy in [-1, 0, 1]: for sx in [-1, 0, 1]: if (sy == 0 and sx == 0) or or_results[int(point_coords[0] + wstride * sy), int(point_coords[1] + hstride * sx)]: continue new_points.append([(point_coords[0] + wstride * sy) / iw, (point_coords[1] + hstride * sx) / ih]) if point_coords[0] + wstride * 2 < iw: for sx in [-1, 0, 1]: if or_results[int(point_coords[0] + wstride * 2), int(point_coords[1] + hstride * sx)]: continue new_points.append([(point_coords[0] + wstride * 2) / iw, (point_coords[1] + hstride * sx) / ih]) if point_coords[1] + hstride * 2 < ih: for sy in [-1, 0, 1]: if or_results[int(point_coords[0] + wstride * sy), int(point_coords[1] + hstride * 2)]: continue new_points.append([(point_coords[0] + wstride * sy) / iw, (point_coords[1] + hstride * 2) / ih]) if point_coords[0] + wstride * 2 < iw and point_coords[1] + hstride * 2 < ih: if or_results[int(point_coords[0] + wstride * 2), int(point_coords[1] + hstride * 2)]: continue new_points.append([(point_coords[0] + wstride * 2) / iw, (point_coords[1] + hstride * 2) / ih]) self.set_point_grids([np.array(new_points)]) new_masks = self.generate(image, False) new_masks.cat(ori_masks) new_masks = self.post_process(image, new_masks) return new_masks @torch.no_grad() def generate(self, image: np.ndarray, need_high: bool) -> MaskData: orig_size = image.shape[:2] # Get points for this crop points_scale = np.array(orig_size)[None, ::-1] points_for_image = self.point_grids[0] * points_scale # Generate masks for this crop in batches data = MaskData() for (points,) in batch_iterator(self.points_per_batch, points_for_image): orig_h, orig_w = orig_size # Run model on this batch transformed_points = self.predictor.transform.apply_coords(points, orig_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], return_logits=True, ) # Serialize predictions and store in MaskData batch_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 if self.pred_iou_thresh > 0.0: keep_mask = batch_data["iou_preds"] > self.pred_iou_thresh batch_data.filter(keep_mask) # Calculate stability score
batch_data["stability_score"] = calculate_stability_score(
8
2023-12-19 11:25:54+00:00
12k
dcharatan/pixelsplat
src/model/model_wrapper.py
[ { "identifier": "get_data_shim", "path": "src/dataset/data_module.py", "snippet": "def get_data_shim(encoder: nn.Module) -> DataShim:\n \"\"\"Get functions that modify the batch. It's sometimes necessary to modify batches\n outside the data loader because GPU computations are required to modify th...
from dataclasses import dataclass from pathlib import Path from typing import Optional, Protocol, runtime_checkable from einops import pack, rearrange, repeat from jaxtyping import Float from pytorch_lightning import LightningModule from pytorch_lightning.loggers.wandb import WandbLogger from pytorch_lightning.utilities import rank_zero_only from torch import Tensor, nn, optim from ..dataset.data_module import get_data_shim from ..dataset.types import BatchedExample from ..evaluation.metrics import compute_lpips, compute_psnr, compute_ssim from ..global_cfg import get_cfg from ..loss import Loss from ..misc.benchmarker import Benchmarker from ..misc.image_io import prep_image, save_image from ..misc.LocalLogger import LOG_PATH, LocalLogger from ..misc.step_tracker import StepTracker from ..visualization.annotation import add_label from ..visualization.camera_trajectory.interpolation import ( interpolate_extrinsics, interpolate_intrinsics, ) from ..visualization.camera_trajectory.wobble import ( generate_wobble, generate_wobble_transformation, ) from ..visualization.color_map import apply_color_map_to_image from ..visualization.layout import add_border, hcat, vcat from ..visualization.validation_in_3d import render_cameras, render_projections from .decoder.decoder import Decoder, DepthRenderingMode from .encoder import Encoder from .encoder.visualization.encoder_visualizer import EncoderVisualizer import moviepy.editor as mpy import torch import wandb
7,684
self.render_video_interpolation_exaggerated(batch) @rank_zero_only def render_video_wobble(self, batch: BatchedExample) -> None: # Two views are needed to get the wobble radius. _, v, _, _ = batch["context"]["extrinsics"].shape if v != 2: return def trajectory_fn(t): origin_a = batch["context"]["extrinsics"][:, 0, :3, 3] origin_b = batch["context"]["extrinsics"][:, 1, :3, 3] delta = (origin_a - origin_b).norm(dim=-1) extrinsics = generate_wobble( batch["context"]["extrinsics"][:, 0], delta * 0.25, t, ) intrinsics = repeat( batch["context"]["intrinsics"][:, 0], "b i j -> b v i j", v=t.shape[0], ) return extrinsics, intrinsics return self.render_video_generic(batch, trajectory_fn, "wobble", num_frames=60) @rank_zero_only def render_video_interpolation(self, batch: BatchedExample) -> None: _, v, _, _ = batch["context"]["extrinsics"].shape def trajectory_fn(t): extrinsics = interpolate_extrinsics( batch["context"]["extrinsics"][0, 0], batch["context"]["extrinsics"][0, 1] if v == 2 else batch["target"]["extrinsics"][0, 0], t, ) intrinsics = interpolate_intrinsics( batch["context"]["intrinsics"][0, 0], batch["context"]["intrinsics"][0, 1] if v == 2 else batch["target"]["intrinsics"][0, 0], t, ) return extrinsics[None], intrinsics[None] return self.render_video_generic(batch, trajectory_fn, "rgb") @rank_zero_only def render_video_interpolation_exaggerated(self, batch: BatchedExample) -> None: # Two views are needed to get the wobble radius. _, v, _, _ = batch["context"]["extrinsics"].shape if v != 2: return def trajectory_fn(t): origin_a = batch["context"]["extrinsics"][:, 0, :3, 3] origin_b = batch["context"]["extrinsics"][:, 1, :3, 3] delta = (origin_a - origin_b).norm(dim=-1) tf = generate_wobble_transformation( delta * 0.5, t, 5, scale_radius_with_t=False, ) extrinsics = interpolate_extrinsics( batch["context"]["extrinsics"][0, 0], batch["context"]["extrinsics"][0, 1] if v == 2 else batch["target"]["extrinsics"][0, 0], t * 5 - 2, ) intrinsics = interpolate_intrinsics( batch["context"]["intrinsics"][0, 0], batch["context"]["intrinsics"][0, 1] if v == 2 else batch["target"]["intrinsics"][0, 0], t * 5 - 2, ) return extrinsics @ tf, intrinsics[None] return self.render_video_generic( batch, trajectory_fn, "interpolation_exagerrated", num_frames=300, smooth=False, loop_reverse=False, ) @rank_zero_only def render_video_generic( self, batch: BatchedExample, trajectory_fn: TrajectoryFn, name: str, num_frames: int = 30, smooth: bool = True, loop_reverse: bool = True, ) -> None: # Render probabilistic estimate of scene. gaussians_prob = self.encoder(batch["context"], self.global_step, False) gaussians_det = self.encoder(batch["context"], self.global_step, True) t = torch.linspace(0, 1, num_frames, dtype=torch.float32, device=self.device) if smooth: t = (torch.cos(torch.pi * (t + 1)) + 1) / 2 extrinsics, intrinsics = trajectory_fn(t) _, _, _, h, w = batch["context"]["image"].shape # Color-map the result. def depth_map(result): near = result[result > 0][:16_000_000].quantile(0.01).log() far = result.view(-1)[:16_000_000].quantile(0.99).log() result = result.log() result = 1 - (result - near) / (far - near)
@dataclass class OptimizerCfg: lr: float warm_up_steps: int @dataclass class TestCfg: output_path: Path @dataclass class TrainCfg: depth_mode: DepthRenderingMode | None extended_visualization: bool @runtime_checkable class TrajectoryFn(Protocol): def __call__( self, t: Float[Tensor, " t"], ) -> tuple[ Float[Tensor, "batch view 4 4"], # extrinsics Float[Tensor, "batch view 3 3"], # intrinsics ]: pass class ModelWrapper(LightningModule): logger: Optional[WandbLogger] encoder: nn.Module encoder_visualizer: Optional[EncoderVisualizer] decoder: Decoder losses: nn.ModuleList optimizer_cfg: OptimizerCfg test_cfg: TestCfg train_cfg: TrainCfg step_tracker: StepTracker | None def __init__( self, optimizer_cfg: OptimizerCfg, test_cfg: TestCfg, train_cfg: TrainCfg, encoder: Encoder, encoder_visualizer: Optional[EncoderVisualizer], decoder: Decoder, losses: list[Loss], step_tracker: StepTracker | None, ) -> None: super().__init__() self.optimizer_cfg = optimizer_cfg self.test_cfg = test_cfg self.train_cfg = train_cfg self.step_tracker = step_tracker # Set up the model. self.encoder = encoder self.encoder_visualizer = encoder_visualizer self.decoder = decoder self.data_shim = get_data_shim(self.encoder) self.losses = nn.ModuleList(losses) # This is used for testing. self.benchmarker = Benchmarker() def training_step(self, batch, batch_idx): batch: BatchedExample = self.data_shim(batch) _, _, _, h, w = batch["target"]["image"].shape # Run the model. gaussians = self.encoder(batch["context"], self.global_step, False) output = self.decoder.forward( gaussians, batch["target"]["extrinsics"], batch["target"]["intrinsics"], batch["target"]["near"], batch["target"]["far"], (h, w), depth_mode=self.train_cfg.depth_mode, ) target_gt = batch["target"]["image"] # Compute metrics. psnr_probabilistic = compute_psnr( rearrange(target_gt, "b v c h w -> (b v) c h w"), rearrange(output.color, "b v c h w -> (b v) c h w"), ) self.log("train/psnr_probabilistic", psnr_probabilistic.mean()) # Compute and log loss. total_loss = 0 for loss_fn in self.losses: loss = loss_fn.forward(output, batch, gaussians, self.global_step) self.log(f"loss/{loss_fn.name}", loss) total_loss = total_loss + loss self.log("loss/total", total_loss) if self.global_rank == 0: print( f"train step {self.global_step}; " f"scene = {batch['scene']}; " f"context = {batch['context']['index'].tolist()}; " f"loss = {total_loss:.6f}" ) # Tell the data loader processes about the current step. if self.step_tracker is not None: self.step_tracker.set_step(self.global_step) return total_loss def test_step(self, batch, batch_idx): batch: BatchedExample = self.data_shim(batch) b, v, _, h, w = batch["target"]["image"].shape assert b == 1 if batch_idx % 100 == 0: print(f"Test step {batch_idx:0>6}.") # Render Gaussians. with self.benchmarker.time("encoder"): gaussians = self.encoder( batch["context"], self.global_step, deterministic=False, ) with self.benchmarker.time("decoder", num_calls=v): output = self.decoder.forward( gaussians, batch["target"]["extrinsics"], batch["target"]["intrinsics"], batch["target"]["near"], batch["target"]["far"], (h, w), ) # Save images. (scene,) = batch["scene"] name = get_cfg()["wandb"]["name"] path = self.test_cfg.output_path / name for index, color in zip(batch["target"]["index"][0], output.color[0]): save_image(color, path / scene / f"color/{index:0>6}.png") def on_test_end(self) -> None: name = get_cfg()["wandb"]["name"] self.benchmarker.dump(self.test_cfg.output_path / name / "benchmark.json") self.benchmarker.dump_memory( self.test_cfg.output_path / name / "peak_memory.json" ) @rank_zero_only def validation_step(self, batch, batch_idx): batch: BatchedExample = self.data_shim(batch) if self.global_rank == 0: print( f"validation step {self.global_step}; " f"scene = {batch['scene']}; " f"context = {batch['context']['index'].tolist()}" ) # Render Gaussians. b, _, _, h, w = batch["target"]["image"].shape assert b == 1 gaussians_probabilistic = self.encoder( batch["context"], self.global_step, deterministic=False, ) output_probabilistic = self.decoder.forward( gaussians_probabilistic, batch["target"]["extrinsics"], batch["target"]["intrinsics"], batch["target"]["near"], batch["target"]["far"], (h, w), ) rgb_probabilistic = output_probabilistic.color[0] gaussians_deterministic = self.encoder( batch["context"], self.global_step, deterministic=True, ) output_deterministic = self.decoder.forward( gaussians_deterministic, batch["target"]["extrinsics"], batch["target"]["intrinsics"], batch["target"]["near"], batch["target"]["far"], (h, w), ) rgb_deterministic = output_deterministic.color[0] # Compute validation metrics. rgb_gt = batch["target"]["image"][0] for tag, rgb in zip( ("deterministic", "probabilistic"), (rgb_deterministic, rgb_probabilistic) ): psnr = compute_psnr(rgb_gt, rgb).mean() self.log(f"val/psnr_{tag}", psnr) lpips = compute_lpips(rgb_gt, rgb).mean() self.log(f"val/lpips_{tag}", lpips) ssim = compute_ssim(rgb_gt, rgb).mean() self.log(f"val/ssim_{tag}", ssim) # Construct comparison image. comparison = hcat( add_label(vcat(*batch["context"]["image"][0]), "Context"), add_label(vcat(*rgb_gt), "Target (Ground Truth)"), add_label(vcat(*rgb_probabilistic), "Target (Probabilistic)"), add_label(vcat(*rgb_deterministic), "Target (Deterministic)"), ) self.logger.log_image( "comparison", [prep_image(add_border(comparison))], step=self.global_step, caption=batch["scene"], ) # Render projections and construct projection image. # These are disabled for now, since RE10k scenes are effectively unbounded. projections = vcat( hcat( *render_projections( gaussians_probabilistic, 256, extra_label="(Probabilistic)", )[0] ), hcat( *render_projections( gaussians_deterministic, 256, extra_label="(Deterministic)" )[0] ), align="left", ) self.logger.log_image( "projection", [prep_image(add_border(projections))], step=self.global_step, ) # Draw cameras. cameras = hcat(*render_cameras(batch, 256)) self.logger.log_image( "cameras", [prep_image(add_border(cameras))], step=self.global_step ) if self.encoder_visualizer is not None: for k, image in self.encoder_visualizer.visualize( batch["context"], self.global_step ).items(): self.logger.log_image(k, [prep_image(image)], step=self.global_step) # Run video validation step. self.render_video_interpolation(batch) self.render_video_wobble(batch) if self.train_cfg.extended_visualization: self.render_video_interpolation_exaggerated(batch) @rank_zero_only def render_video_wobble(self, batch: BatchedExample) -> None: # Two views are needed to get the wobble radius. _, v, _, _ = batch["context"]["extrinsics"].shape if v != 2: return def trajectory_fn(t): origin_a = batch["context"]["extrinsics"][:, 0, :3, 3] origin_b = batch["context"]["extrinsics"][:, 1, :3, 3] delta = (origin_a - origin_b).norm(dim=-1) extrinsics = generate_wobble( batch["context"]["extrinsics"][:, 0], delta * 0.25, t, ) intrinsics = repeat( batch["context"]["intrinsics"][:, 0], "b i j -> b v i j", v=t.shape[0], ) return extrinsics, intrinsics return self.render_video_generic(batch, trajectory_fn, "wobble", num_frames=60) @rank_zero_only def render_video_interpolation(self, batch: BatchedExample) -> None: _, v, _, _ = batch["context"]["extrinsics"].shape def trajectory_fn(t): extrinsics = interpolate_extrinsics( batch["context"]["extrinsics"][0, 0], batch["context"]["extrinsics"][0, 1] if v == 2 else batch["target"]["extrinsics"][0, 0], t, ) intrinsics = interpolate_intrinsics( batch["context"]["intrinsics"][0, 0], batch["context"]["intrinsics"][0, 1] if v == 2 else batch["target"]["intrinsics"][0, 0], t, ) return extrinsics[None], intrinsics[None] return self.render_video_generic(batch, trajectory_fn, "rgb") @rank_zero_only def render_video_interpolation_exaggerated(self, batch: BatchedExample) -> None: # Two views are needed to get the wobble radius. _, v, _, _ = batch["context"]["extrinsics"].shape if v != 2: return def trajectory_fn(t): origin_a = batch["context"]["extrinsics"][:, 0, :3, 3] origin_b = batch["context"]["extrinsics"][:, 1, :3, 3] delta = (origin_a - origin_b).norm(dim=-1) tf = generate_wobble_transformation( delta * 0.5, t, 5, scale_radius_with_t=False, ) extrinsics = interpolate_extrinsics( batch["context"]["extrinsics"][0, 0], batch["context"]["extrinsics"][0, 1] if v == 2 else batch["target"]["extrinsics"][0, 0], t * 5 - 2, ) intrinsics = interpolate_intrinsics( batch["context"]["intrinsics"][0, 0], batch["context"]["intrinsics"][0, 1] if v == 2 else batch["target"]["intrinsics"][0, 0], t * 5 - 2, ) return extrinsics @ tf, intrinsics[None] return self.render_video_generic( batch, trajectory_fn, "interpolation_exagerrated", num_frames=300, smooth=False, loop_reverse=False, ) @rank_zero_only def render_video_generic( self, batch: BatchedExample, trajectory_fn: TrajectoryFn, name: str, num_frames: int = 30, smooth: bool = True, loop_reverse: bool = True, ) -> None: # Render probabilistic estimate of scene. gaussians_prob = self.encoder(batch["context"], self.global_step, False) gaussians_det = self.encoder(batch["context"], self.global_step, True) t = torch.linspace(0, 1, num_frames, dtype=torch.float32, device=self.device) if smooth: t = (torch.cos(torch.pi * (t + 1)) + 1) / 2 extrinsics, intrinsics = trajectory_fn(t) _, _, _, h, w = batch["context"]["image"].shape # Color-map the result. def depth_map(result): near = result[result > 0][:16_000_000].quantile(0.01).log() far = result.view(-1)[:16_000_000].quantile(0.99).log() result = result.log() result = 1 - (result - near) / (far - near)
return apply_color_map_to_image(result, "turbo")
18
2023-12-20 19:45:59+00:00
12k
hutaiHang/Faster-Diffusion
if_demo.py
[ { "identifier": "register_if1", "path": "utils_if.py", "snippet": "def register_if1(pipe):\r\n def new_call(self):\r\n @torch.no_grad()\r\n def call(\r\n prompt: Union[str, List[str]] = None,\r\n num_inference_steps: int = 100,\r\n timesteps: List[int] =...
from diffusers import DiffusionPipeline , IFPipeline, IFSuperResolutionPipeline, StableDiffusionUpscalePipeline from diffusers.utils import pt_to_pil from diffusers import DPMSolverMultistepScheduler from utils_if import register_if1, register_if2,register_if3, register_faster_forward, seed_everything import torch
9,980
seed_everything(2023) prompt = "a lone sailboat drifting on calm waters" stage_1 = DiffusionPipeline.from_pretrained( "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16, ).to('cuda') stage_2 = DiffusionPipeline.from_pretrained( "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16, ).to('cuda') # stage 3 safety_modules = { "feature_extractor": stage_1.feature_extractor, "safety_checker": None, "watermarker": stage_1.watermarker, } stage_3 = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16 ).to('cuda') register_faster_forward(stage_1.unet, mod = '100ls') register_if1(stage_1) register_faster_forward(stage_2.unet, mod = 's2') register_if2(stage_2)
seed_everything(2023) prompt = "a lone sailboat drifting on calm waters" stage_1 = DiffusionPipeline.from_pretrained( "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16, ).to('cuda') stage_2 = DiffusionPipeline.from_pretrained( "DeepFloyd/IF-II-L-v1.0", text_encoder=None, variant="fp16", torch_dtype=torch.float16, ).to('cuda') # stage 3 safety_modules = { "feature_extractor": stage_1.feature_extractor, "safety_checker": None, "watermarker": stage_1.watermarker, } stage_3 = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-x4-upscaler", **safety_modules, torch_dtype=torch.float16 ).to('cuda') register_faster_forward(stage_1.unet, mod = '100ls') register_if1(stage_1) register_faster_forward(stage_2.unet, mod = 's2') register_if2(stage_2)
register_if3(stage_3)
2
2023-12-15 05:03:37+00:00
12k
FoundationVision/GLEE
app/GLEE/glee/models/transformer_decoder/maskdino_decoder.py
[ { "identifier": "TransformerDecoder", "path": "app/GLEE/glee/models/transformer_decoder/dino_decoder.py", "snippet": "class TransformerDecoder(nn.Module):\r\n\r\n def __init__(self, decoder_layer, num_layers, norm=None,\r\n return_intermediate=False,\r\n d_model=256, q...
import logging import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from detectron2.config import configurable from detectron2.layers import Conv2d from detectron2.utils.registry import Registry from detectron2.structures import BitMasks from timm.models.layers import trunc_normal_ from .dino_decoder import TransformerDecoder, DeformableTransformerDecoderLayer from ...utils.utils import MLP, gen_encoder_output_proposals, inverse_sigmoid from ...utils import box_ops
8,017
} self.mask_embed = MLP(hidden_dim, hidden_dim, mask_dim, 3) # init decoder self.decoder_norm = decoder_norm = nn.LayerNorm(hidden_dim) decoder_layer = DeformableTransformerDecoderLayer(hidden_dim, dim_feedforward, dropout, activation, self.num_feature_levels, nhead, dec_n_points) self.decoder = TransformerDecoder(decoder_layer, self.num_layers, decoder_norm, return_intermediate=return_intermediate_dec, d_model=hidden_dim, query_dim=query_dim, num_feature_levels=self.num_feature_levels, dec_layer_share=dec_layer_share, cross_track_layer = cross_track_layer, n_levels=self.num_feature_levels, n_heads=nhead, n_points=dec_n_points ) self.cross_track_layer = cross_track_layer self.hidden_dim = hidden_dim self._bbox_embed = _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3) nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0) nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0) box_embed_layerlist = [_bbox_embed for i in range(self.num_layers)] # share box prediction each layer self.bbox_embed = nn.ModuleList(box_embed_layerlist) self.decoder.bbox_embed = self.bbox_embed @classmethod def from_config(cls, cfg, in_channels, lang_encoder, mask_classification): ret = {} ret["in_channels"] = in_channels ret["lang_encoder"] = lang_encoder ret["mask_classification"] = mask_classification ret["dim_projection"] = cfg.MODEL.DIM_PROJ ret["num_classes"] = cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES ret["hidden_dim"] = cfg.MODEL.MaskDINO.HIDDEN_DIM ret["num_queries"] = cfg.MODEL.MaskDINO.NUM_OBJECT_QUERIES # Transformer parameters: ret["nheads"] = cfg.MODEL.MaskDINO.NHEADS ret["dim_feedforward"] = cfg.MODEL.MaskDINO.DIM_FEEDFORWARD ret["dec_layers"] = cfg.MODEL.MaskDINO.DEC_LAYERS ret["enforce_input_project"] = cfg.MODEL.MaskDINO.ENFORCE_INPUT_PROJ ret["mask_dim"] = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM ret["two_stage"] =cfg.MODEL.MaskDINO.TWO_STAGE ret["initialize_box_type"] = cfg.MODEL.MaskDINO.INITIALIZE_BOX_TYPE # ['no', 'bitmask', 'mask2box'] ret["dn"]=cfg.MODEL.MaskDINO.DN ret["noise_scale"] =cfg.MODEL.MaskDINO.DN_NOISE_SCALE ret["dn_num"] =cfg.MODEL.MaskDINO.DN_NUM ret["initial_pred"] =cfg.MODEL.MaskDINO.INITIAL_PRED ret["learn_tgt"] = cfg.MODEL.MaskDINO.LEARN_TGT ret["total_num_feature_levels"] = cfg.MODEL.SEM_SEG_HEAD.TOTAL_NUM_FEATURE_LEVELS ret["semantic_ce_loss"] = cfg.MODEL.MaskDINO.TEST.SEMANTIC_ON and cfg.MODEL.MaskDINO.SEMANTIC_CE_LOSS and ~cfg.MODEL.MaskDINO.TEST.PANOPTIC_ON ret["cross_track_layer"] = cfg.MODEL.CROSS_TRACK return ret def prepare_for_dn(self, targets, tgt, refpoint_emb, batch_size,task): """ modified from dn-detr. You can refer to dn-detr https://github.com/IDEA-Research/DN-DETR/blob/main/models/dn_dab_deformable_detr/dn_components.py for more details :param dn_args: scalar, noise_scale :param tgt: original tgt (content) in the matching part :param refpoint_emb: positional anchor queries in the matching part :param batch_size: bs """ if self.training: scalar, noise_scale = self.dn_num,self.noise_scale known = [(torch.ones_like(t['labels'])).cuda() for t in targets] know_idx = [torch.nonzero(t) for t in known] known_num = [sum(k) for k in known] # use fix number of dn queries if max(known_num)>0: scalar = scalar//(int(max(known_num))) else: scalar = 0 if scalar == 0: input_query_label = None input_query_bbox = None attn_mask = None mask_dict = None return input_query_label, input_query_bbox, attn_mask, mask_dict # can be modified to selectively denosie some label or boxes; also known label prediction unmask_bbox = unmask_label = torch.cat(known) labels = torch.cat([t['labels'] for t in targets]) boxes = torch.cat([t['boxes'] for t in targets]) batch_idx = torch.cat([torch.full_like(t['labels'].long(), i) for i, t in enumerate(targets)]) # known known_indice = torch.nonzero(unmask_label + unmask_bbox) known_indice = known_indice.view(-1) # noise known_indice = known_indice.repeat(scalar, 1).view(-1) known_labels = labels.repeat(scalar, 1).view(-1) known_bid = batch_idx.repeat(scalar, 1).view(-1) known_bboxs = boxes.repeat(scalar, 1) known_labels_expaned = known_labels.clone() known_bbox_expand = known_bboxs.clone() # noise on the label if noise_scale > 0: p = torch.rand_like(known_labels_expaned.float()) chosen_indice = torch.nonzero(p < (noise_scale * 0.5)).view(-1) # half of bbox prob new_label = torch.randint_like(chosen_indice, 0, self.num_classes[task]) # randomly put a new one here known_labels_expaned.scatter_(0, chosen_indice, new_label) if noise_scale > 0: diff = torch.zeros_like(known_bbox_expand) diff[:, :2] = known_bbox_expand[:, 2:] / 2 diff[:, 2:] = known_bbox_expand[:, 2:] known_bbox_expand += torch.mul((torch.rand_like(known_bbox_expand) * 2 - 1.0), diff).cuda() * noise_scale known_bbox_expand = known_bbox_expand.clamp(min=0.0, max=1.0) m = known_labels_expaned.long().to('cuda') input_label_embed = self.label_enc[task](m)
# ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from Mask2Former https://github.com/facebookresearch/Mask2Former by Feng Li and Hao Zhang. TRANSFORMER_DECODER_REGISTRY = Registry("TRANSFORMER_MODULE") TRANSFORMER_DECODER_REGISTRY.__doc__ = """ Registry for transformer module in MaskDINO. """ def build_transformer_decoder(cfg, in_channels, lang_encoder, mask_classification=True): """ Build a instance embedding branch from `cfg.MODEL.INS_EMBED_HEAD.NAME`. """ name = cfg.MODEL.MaskDINO.TRANSFORMER_DECODER_NAME return TRANSFORMER_DECODER_REGISTRY.get(name)(cfg, in_channels, lang_encoder, mask_classification) @TRANSFORMER_DECODER_REGISTRY.register() class MaskDINODecoder(nn.Module): @configurable def __init__( self, in_channels, lang_encoder, mask_classification=True, *, num_classes: int, hidden_dim: int, num_queries: int, nheads: int, dim_feedforward: int, dec_layers: int, mask_dim: int, dim_projection: int, enforce_input_project: bool, two_stage: bool, dn: str, noise_scale:float, dn_num:int, initialize_box_type:bool, initial_pred:bool, learn_tgt: bool, total_num_feature_levels: int = 4, dropout: float = 0.0, activation: str = 'relu', nhead: int = 8, dec_n_points: int = 4, return_intermediate_dec: bool = True, query_dim: int = 4, dec_layer_share: bool = False, semantic_ce_loss: bool = False, cross_track_layer: bool = False, ): """ NOTE: this interface is experimental. Args: in_channels: channels of the input features mask_classification: whether to add mask classifier or not num_classes: number of classes hidden_dim: Transformer feature dimension num_queries: number of queries nheads: number of heads dim_feedforward: feature dimension in feedforward network enc_layers: number of Transformer encoder layers dec_layers: number of Transformer decoder layers pre_norm: whether to use pre-LayerNorm or not mask_dim: mask feature dimension enforce_input_project: add input project 1x1 conv even if input channels and hidden dim is identical d_model: transformer dimension dropout: dropout rate activation: activation function nhead: num heads in multi-head attention dec_n_points: number of sampling points in decoder return_intermediate_dec: return the intermediate results of decoder query_dim: 4 -> (x, y, w, h) dec_layer_share: whether to share each decoder layer semantic_ce_loss: use ce loss for semantic segmentation """ super().__init__() assert mask_classification, "Only support mask classification model" self.mask_classification = mask_classification self.num_feature_levels = total_num_feature_levels self.initial_pred = initial_pred self.lang_encoder = lang_encoder # define Transformer decoder here self.dn=dn self.learn_tgt = learn_tgt self.noise_scale=noise_scale self.dn_num=dn_num self.num_heads = nheads self.num_layers = dec_layers self.two_stage=two_stage self.initialize_box_type = initialize_box_type self.total_num_feature_levels = total_num_feature_levels self.num_queries = num_queries self.semantic_ce_loss = semantic_ce_loss # learnable query features if not two_stage or self.learn_tgt: self.query_feat = nn.Embedding(num_queries, hidden_dim) if not two_stage and initialize_box_type == 'no': self.query_embed = nn.Embedding(num_queries, 4) if two_stage: self.enc_output = nn.Linear(hidden_dim, hidden_dim) self.enc_output_norm = nn.LayerNorm(hidden_dim) self.input_proj = nn.ModuleList() for _ in range(self.num_feature_levels): if in_channels != hidden_dim or enforce_input_project: self.input_proj.append(Conv2d(in_channels, hidden_dim, kernel_size=1)) weight_init.c2_xavier_fill(self.input_proj[-1]) else: self.input_proj.append(nn.Sequential()) self.num_classes = { 'obj365':100, 'obj365_clip':100, 'lvis':100, 'openimage':100, 'lvis_clip':100, 'openimage_clip':100, 'grit':100, 'vg':200, 'coco':80, 'coco_clip':80, 'grounding':1, 'rvos':1, 'sa1b':1, 'sa1b_clip':1, 'bdd_det':10, 'bdd_inst':8, 'ytvis19':40, 'image_yt19':40, 'image_yt21':40, 'bdd_track_seg':8, 'bdd_track_box':8, 'ovis':25, 'image_o':25, 'ytvis21':40, 'uvo_video': 81, 'ytbvos':1, } # output FFNs assert self.mask_classification, "why not class embedding?" self.confidence_score = MLP(hidden_dim, hidden_dim, 1, 2) self.category_embed = nn.Parameter(torch.rand(hidden_dim, dim_projection)) # trunc_normal_(self.category_embed, std=.02) # self.track_embed = MLP(hidden_dim, hidden_dim, hidden_dim, 3) self.coco_label_enc = nn.Embedding(80,hidden_dim) self.obj365_label_enc = nn.Embedding(100, hidden_dim) self.vg_label_enc = nn.Embedding(200, hidden_dim) self.grounding_label_enc = nn.Embedding(1,hidden_dim) self.ytvis19_label_enc = nn.Embedding(40,hidden_dim) self.ytvis21_label_enc = nn.Embedding(40,hidden_dim) self.ovis_label_enc = nn.Embedding(25,hidden_dim) self.uvo_label_enc = nn.Embedding(81,hidden_dim) self.bdd_det = nn.Embedding(10,hidden_dim) self.bdd_inst = nn.Embedding(8,hidden_dim) self.label_enc = { 'coco': self.coco_label_enc, 'coco_clip': self.coco_label_enc, 'coconomask': self.coco_label_enc, 'obj365': self.obj365_label_enc, 'lvis': self.obj365_label_enc, 'openimage': self.obj365_label_enc, 'grit': self.obj365_label_enc, 'vg': self.vg_label_enc, 'obj365_clip': self.obj365_label_enc, 'lvis_clip': self.obj365_label_enc, 'openimage_clip': self.obj365_label_enc, 'bdd_det':self.bdd_det, 'bdd_inst':self.bdd_inst, 'bdd_track_seg':self.bdd_inst, 'bdd_track_box':self.bdd_inst, 'sa1b': self.grounding_label_enc, 'sa1b_clip': self.grounding_label_enc, 'grounding': self.grounding_label_enc, 'rvos': self.grounding_label_enc, 'uvo_video':self.uvo_label_enc, 'ytvis19':self.ytvis19_label_enc, 'image_yt19': self.ytvis19_label_enc, 'ytvis21':self.ytvis21_label_enc, 'image_yt21':self.ytvis21_label_enc, 'ovis':self.ovis_label_enc, 'image_o': self.ovis_label_enc, 'burst':self.grounding_label_enc, 'ytbvos':self.grounding_label_enc, } self.mask_embed = MLP(hidden_dim, hidden_dim, mask_dim, 3) # init decoder self.decoder_norm = decoder_norm = nn.LayerNorm(hidden_dim) decoder_layer = DeformableTransformerDecoderLayer(hidden_dim, dim_feedforward, dropout, activation, self.num_feature_levels, nhead, dec_n_points) self.decoder = TransformerDecoder(decoder_layer, self.num_layers, decoder_norm, return_intermediate=return_intermediate_dec, d_model=hidden_dim, query_dim=query_dim, num_feature_levels=self.num_feature_levels, dec_layer_share=dec_layer_share, cross_track_layer = cross_track_layer, n_levels=self.num_feature_levels, n_heads=nhead, n_points=dec_n_points ) self.cross_track_layer = cross_track_layer self.hidden_dim = hidden_dim self._bbox_embed = _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3) nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0) nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0) box_embed_layerlist = [_bbox_embed for i in range(self.num_layers)] # share box prediction each layer self.bbox_embed = nn.ModuleList(box_embed_layerlist) self.decoder.bbox_embed = self.bbox_embed @classmethod def from_config(cls, cfg, in_channels, lang_encoder, mask_classification): ret = {} ret["in_channels"] = in_channels ret["lang_encoder"] = lang_encoder ret["mask_classification"] = mask_classification ret["dim_projection"] = cfg.MODEL.DIM_PROJ ret["num_classes"] = cfg.MODEL.SEM_SEG_HEAD.NUM_CLASSES ret["hidden_dim"] = cfg.MODEL.MaskDINO.HIDDEN_DIM ret["num_queries"] = cfg.MODEL.MaskDINO.NUM_OBJECT_QUERIES # Transformer parameters: ret["nheads"] = cfg.MODEL.MaskDINO.NHEADS ret["dim_feedforward"] = cfg.MODEL.MaskDINO.DIM_FEEDFORWARD ret["dec_layers"] = cfg.MODEL.MaskDINO.DEC_LAYERS ret["enforce_input_project"] = cfg.MODEL.MaskDINO.ENFORCE_INPUT_PROJ ret["mask_dim"] = cfg.MODEL.SEM_SEG_HEAD.MASK_DIM ret["two_stage"] =cfg.MODEL.MaskDINO.TWO_STAGE ret["initialize_box_type"] = cfg.MODEL.MaskDINO.INITIALIZE_BOX_TYPE # ['no', 'bitmask', 'mask2box'] ret["dn"]=cfg.MODEL.MaskDINO.DN ret["noise_scale"] =cfg.MODEL.MaskDINO.DN_NOISE_SCALE ret["dn_num"] =cfg.MODEL.MaskDINO.DN_NUM ret["initial_pred"] =cfg.MODEL.MaskDINO.INITIAL_PRED ret["learn_tgt"] = cfg.MODEL.MaskDINO.LEARN_TGT ret["total_num_feature_levels"] = cfg.MODEL.SEM_SEG_HEAD.TOTAL_NUM_FEATURE_LEVELS ret["semantic_ce_loss"] = cfg.MODEL.MaskDINO.TEST.SEMANTIC_ON and cfg.MODEL.MaskDINO.SEMANTIC_CE_LOSS and ~cfg.MODEL.MaskDINO.TEST.PANOPTIC_ON ret["cross_track_layer"] = cfg.MODEL.CROSS_TRACK return ret def prepare_for_dn(self, targets, tgt, refpoint_emb, batch_size,task): """ modified from dn-detr. You can refer to dn-detr https://github.com/IDEA-Research/DN-DETR/blob/main/models/dn_dab_deformable_detr/dn_components.py for more details :param dn_args: scalar, noise_scale :param tgt: original tgt (content) in the matching part :param refpoint_emb: positional anchor queries in the matching part :param batch_size: bs """ if self.training: scalar, noise_scale = self.dn_num,self.noise_scale known = [(torch.ones_like(t['labels'])).cuda() for t in targets] know_idx = [torch.nonzero(t) for t in known] known_num = [sum(k) for k in known] # use fix number of dn queries if max(known_num)>0: scalar = scalar//(int(max(known_num))) else: scalar = 0 if scalar == 0: input_query_label = None input_query_bbox = None attn_mask = None mask_dict = None return input_query_label, input_query_bbox, attn_mask, mask_dict # can be modified to selectively denosie some label or boxes; also known label prediction unmask_bbox = unmask_label = torch.cat(known) labels = torch.cat([t['labels'] for t in targets]) boxes = torch.cat([t['boxes'] for t in targets]) batch_idx = torch.cat([torch.full_like(t['labels'].long(), i) for i, t in enumerate(targets)]) # known known_indice = torch.nonzero(unmask_label + unmask_bbox) known_indice = known_indice.view(-1) # noise known_indice = known_indice.repeat(scalar, 1).view(-1) known_labels = labels.repeat(scalar, 1).view(-1) known_bid = batch_idx.repeat(scalar, 1).view(-1) known_bboxs = boxes.repeat(scalar, 1) known_labels_expaned = known_labels.clone() known_bbox_expand = known_bboxs.clone() # noise on the label if noise_scale > 0: p = torch.rand_like(known_labels_expaned.float()) chosen_indice = torch.nonzero(p < (noise_scale * 0.5)).view(-1) # half of bbox prob new_label = torch.randint_like(chosen_indice, 0, self.num_classes[task]) # randomly put a new one here known_labels_expaned.scatter_(0, chosen_indice, new_label) if noise_scale > 0: diff = torch.zeros_like(known_bbox_expand) diff[:, :2] = known_bbox_expand[:, 2:] / 2 diff[:, 2:] = known_bbox_expand[:, 2:] known_bbox_expand += torch.mul((torch.rand_like(known_bbox_expand) * 2 - 1.0), diff).cuda() * noise_scale known_bbox_expand = known_bbox_expand.clamp(min=0.0, max=1.0) m = known_labels_expaned.long().to('cuda') input_label_embed = self.label_enc[task](m)
input_bbox_embed = inverse_sigmoid(known_bbox_expand)
4
2023-12-15 01:12:36+00:00
12k
SHI-Labs/VCoder
vcoder_llava/train/vcoder_ds_train.py
[ { "identifier": "IGNORE_INDEX", "path": "vcoder_llava/constants.py", "snippet": "IGNORE_INDEX = -100" }, { "identifier": "DEFAULT_IMAGE_TOKEN", "path": "vcoder_llava/constants.py", "snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\"" }, { "identifier": "DEFAULT_SEG_TOKEN", "path": ...
import os import copy import pathlib import numpy as np import random import torch import transformers import json import re from dataclasses import dataclass, field from typing import Dict, Optional, Sequence from vcoder_llava.constants import IGNORE_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_SEG_TOKEN, DEFAULT_DEPTH_TOKEN from torch.utils.data import Dataset from vcoder_llava.train.vcoder_ds_llava_trainer import VCoderDSLLaVATrainer from vcoder_llava import vcoder_conversation as conversation_lib from vcoder_llava.model import * from vcoder_llava.mm_utils import tokenizer_image_token, tokenizer_seg_token, tokenizer_depth_seg_token from vcoder_llava.data_utils import generate_qa_pairs from .train import ( get_peft_state_maybe_zero_3, get_peft_state_non_lora_maybe_zero_3, get_mm_adapter_state_maybe_zero_3, find_all_linear_names, ) from vcoder_llava.questions import DEPTH_QUESTIONS, SEMANTIC_QUESTIONS, INSTANCE_QUESTIONS, PANOPTIC_QUESTIONS from PIL import Image from transformers import BitsAndBytesConfig from peft import prepare_model_for_kbit_training from peft import LoraConfig, get_peft_model from peft.tuners.lora import LoraLayer
8,151
else: tokenizer = transformers.AutoTokenizer.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right", use_fast=False, ) tokenizer.pad_token = tokenizer.unk_token if model_args.version in conversation_lib.conv_templates: conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] else: conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] # vision modules model.get_vision_tower().load_model() data_args.image_processor = model.get_vision_tower().image_processor data_args.is_multimodal = True vision_tower = model.get_vision_tower() vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) model.config.image_aspect_ratio = data_args.image_aspect_ratio model.config.image_grid_pinpoints = data_args.image_grid_pinpoints model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter if model_args.tune_mm_mlp_adapter: model.requires_grad_(False) for p in model.get_model().mm_projector.parameters(): p.requires_grad = True model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter if training_args.freeze_mm_mlp_adapter: for p in model.get_model().mm_projector.parameters(): p.requires_grad = False if training_args.bits in [4, 8]: model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) if model_args.seg_tune_adapter is not None: model.get_model().initialize_seg_modules( model_args=model_args, fsdp=training_args.fsdp ) if model_args.seg_tune_adapter: if getattr(model_args, "freeze_llm", False): model.requires_grad_(False) for p in model.get_model().seg_mm_projector.parameters(): p.requires_grad = True for p in model.get_model().vcoder_lm_emb.parameters(): p.requires_grad = True data_args.seg_image_processor = model.get_vision_tower().image_processor model.config.use_mm2_proj = model_args.use_mm2_proj model.config.mm_vcoder_lm_emb = True model.config.seg_tune_adapter = training_args.seg_tune_adapter = model_args.seg_tune_adapter model.config.freeze_seg_mm_mlp_adapter = training_args.freeze_seg_mm_mlp_adapter if training_args.freeze_seg_mm_mlp_adapter: for p in model.get_model().seg_mm_projector.parameters(): p.requires_grad = False if model_args.use_mm2_proj: for p in model.get_model().mm2_projector.parameters(): p.requires_grad = False if training_args.bits in [4, 8]: model.get_model().seg_mm_projector.to(dtype=compute_dtype, device=training_args.device) else: # seg modules data_args.seg_image_processor = model.get_vision_tower().image_processor if training_args.bits in [4, 8]: model.get_model().seg_mm_projector.to(dtype=compute_dtype, device=training_args.device) if model_args.depth_tune_adapter is not None: model.get_model().initialize_depth_modules( model_args=model_args, fsdp=training_args.fsdp ) if getattr(model_args, "freeze_llm", False): model.requires_grad_(False) for p in model.get_model().depth_mm_projector.parameters(): p.requires_grad = True for p in model.get_model().vcoder_lm_emb.parameters(): p.requires_grad = True if model_args.seg_tune_adapter: for p in model.get_model().seg_mm_projector.parameters(): p.requires_grad = True data_args.depth_image_processor = model.get_vision_tower().image_processor model.config.depth_tune_adapter = training_args.depth_tune_adapter = model_args.depth_tune_adapter model.config.freeze_depth_mm_mlp_adapter = training_args.freeze_depth_mm_mlp_adapter if training_args.freeze_depth_mm_mlp_adapter: for p in model.get_model().depth_mm_projector.parameters(): p.requires_grad = False if training_args.bits in [4, 8]: model.get_model().depth_mm_projector.to(dtype=compute_dtype, device=training_args.device) if training_args.bits in [4, 8]: for name, module in model.named_modules(): if isinstance(module, LoraLayer): if training_args.bf16: module = module.to(torch.bfloat16) if 'norm' in name: module = module.to(torch.float32) if 'lm_head' in name or 'embed_tokens' in name: if hasattr(module, 'weight'): if training_args.bf16 and module.weight.dtype == torch.float32: module = module.to(torch.bfloat16) data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: # 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. local_rank = None def rank0_print(*args): if local_rank == 0: print(*args) @dataclass class ModelArguments: model_name_or_path: Optional[str] = field(default="facebook/opt-125m") version: Optional[str] = field(default="v1") freeze_backbone: bool = field(default=False) tune_mm_mlp_adapter: bool = field(default=False) mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer mm_projector_type: Optional[str] = field(default='linear') freeze_llm: bool = field(default=False) use_mm2_proj: bool = field(default=False) pretrain_mm2_mlp_adapter: Optional[str] = field(default=None) seg_tune_adapter: bool = field(default=False) mm_seg_select_layer: Optional[int] = field(default=-2) # default to the last layer seg_mm_projector_type: Optional[str] = field(default='linear') depth_tune_adapter: bool = field(default=False) mm_depth_select_layer: Optional[int] = field(default=-2) # default to the last layer depth_mm_projector_type: Optional[str] = field(default='linear') mm_vision_select_feature: Optional[str] = field(default="patch") mm_seg_select_feature: Optional[str] = field(default="patch") mm_depth_select_feature: Optional[str] = field(default="patch") @dataclass class DataArguments: data_path: str = field(default=None, metadata={"help": "Path to the training data."}) depth_data_path: str = field(default=None, metadata={"help": "Path to the seg training data."}) lazy_preprocess: bool = False is_multimodal: bool = False image_folder: Optional[str] = field(default=None) seg_image_folder: Optional[str] = field(default=None) depth_image_folder: Optional[str] = field(default=None) image_aspect_ratio: str = 'square' image_grid_pinpoints: Optional[str] = field(default=None) @dataclass class TrainingArguments(transformers.TrainingArguments): cache_dir: Optional[str] = field(default=None) optim: str = field(default="adamw_torch") remove_unused_columns: bool = field(default=False) freeze_mm_mlp_adapter: bool = field(default=False) freeze_seg_mm_mlp_adapter: bool = field(default=False) freeze_depth_mm_mlp_adapter: bool = field(default=False) mpt_attn_impl: Optional[str] = field(default="triton") model_max_length: int = field( default=512, metadata={ "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)." }, ) double_quant: bool = field( default=True, metadata={"help": "Compress the quantization statistics through double quantization."} ) quant_type: str = field( default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} ) bits: int = field( default=16, metadata={"help": "How many bits to use."} ) lora_enable: bool = False lora_r: int = 64 lora_alpha: int = 16 lora_dropout: float = 0.05 lora_weight_path: str = "" lora_bias: str = "none" group_by_modality_length: bool = field(default=False) def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): """Collects the state dict and dump to disk.""" if trainer.deepspeed: torch.cuda.synchronize() trainer.save_model(output_dir) return state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = { key: value.cpu() for key, value in state_dict.items() } del state_dict trainer._save(output_dir, state_dict=cpu_state_dict) # noqa def depth_seg_preprocess_v1( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, has_seg: bool = False, has_depth: bool = False, ) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]} # Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:] conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt()) # Tokenize conversations if has_image and has_seg: if has_depth: input_ids = torch.stack([tokenizer_depth_seg_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) else: input_ids = torch.stack([tokenizer_seg_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) elif has_image: input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) else: input_ids = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids targets = input_ids.clone() assert conv.sep_style == conversation_lib.SeparatorStyle.TWO # Mask targets sep = conv.sep + conv.roles[1] + ": " for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum()) rounds = conversation.split(conv.sep2) cur_len = 1 target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(rounds): if rou == "": break parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep if has_image and has_seg: if has_depth: round_len = len(tokenizer_depth_seg_token(rou, tokenizer)) instruction_len = len(tokenizer_depth_seg_token(parts[0], tokenizer)) - 3 else: round_len = len(tokenizer_seg_token(rou, tokenizer)) instruction_len = len(tokenizer_seg_token(parts[0], tokenizer)) - 2 elif has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 else: round_len = len(tokenizer(rou).input_ids) instruction_len = len(tokenizer(parts[0]).input_ids) - 2 target[cur_len : cur_len + instruction_len] = IGNORE_INDEX cur_len += round_len target[cur_len:] = IGNORE_INDEX if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX print( f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)" ) return dict( input_ids=input_ids, labels=targets, ) def vcoder_ds_preprocess_multimodal( sources: Sequence[str], data_args: DataArguments ) -> Dict: is_multimodal = data_args.is_multimodal if not is_multimodal: return sources for source in sources: for sentence in source: if DEFAULT_IMAGE_TOKEN in sentence['value']: sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] sentence['value'] = sentence['value'].strip() replace_token = DEFAULT_IMAGE_TOKEN sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) if DEFAULT_SEG_TOKEN in sentence['value']: sentence['value'] = sentence['value'].replace(DEFAULT_SEG_TOKEN, '').strip() sentence['value'] = DEFAULT_SEG_TOKEN + '\n' + sentence['value'] sentence['value'] = sentence['value'].strip() replace_token = DEFAULT_SEG_TOKEN sentence["value"] = sentence["value"].replace(DEFAULT_SEG_TOKEN, replace_token) if DEFAULT_DEPTH_TOKEN in sentence['value']: sentence['value'] = sentence['value'].replace(DEFAULT_DEPTH_TOKEN, '').strip() sentence['value'] = DEFAULT_DEPTH_TOKEN + '\n' + sentence['value'] sentence['value'] = sentence['value'].strip() replace_token = DEFAULT_DEPTH_TOKEN sentence["value"] = sentence["value"].replace(DEFAULT_DEPTH_TOKEN, replace_token) return sources def preprocess( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False, has_seg: bool = False, has_depth: bool = False ) -> Dict: """ Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; 2. Concatenate conversations together; 3. Tokenize the concatenated conversation; 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. """ if conversation_lib.default_conversation.version.startswith("v1"): return depth_seg_preprocess_v1(sources, tokenizer, has_image=has_image, has_seg=has_seg, has_depth=has_depth) raise ValueError(f"Unknown conversation version: {conversation_lib.default_conversation.version}") def _obtain_depth_texts(file_path): with open(file_path) as f: lines = f.readlines() depth_labels = {} for line in lines: key = line.split("<IMG>")[1].strip("\n") label = line.split("<IMG>")[2].strip("\n") depth_labels[key] = label return depth_labels def _obtain_seg_texts(file_path): def _remove_specific_word(text, word_to_remove): tokens = re.findall(r'\b\w+\b|[,.]', text) result_tokens = [] word_found = False for i, token in enumerate(tokens): if token == word_to_remove: if not word_found: # Keep the first occurrence and mark it as found result_tokens.append(token) word_found = True else: # Remove any preceding punctuation if it's just before this word if i > 0 and tokens[i-1] in {',', '.'}: result_tokens.pop() else: result_tokens.append(token) # Join tokens and clean up spaces before punctuation result_text = ' '.join(result_tokens) result_text = re.sub(r'\s([,.](?:\s|$))', r'\1', result_text) return result_text with open(file_path) as f: lines = f.readlines() seg_labels = {} for line in lines: key = line.split("<IMG>")[1].strip("\n") label = line.split("<IMG>")[2].strip("\n") label = _remove_specific_word(label, "wall") label = _remove_specific_word(label, "window") seg_labels[key] = label return seg_labels def obtain_seg_data_splits(data_args): def _get_labels(folder): return _obtain_seg_texts(os.path.join(data_args.seg_image_folder, folder, "panoptic.txt")) list_data_dict = [] data_dict = json.load(open(data_args.data_path, "r")) for l in data_dict: if "image" in l.keys(): if os.path.exists(os.path.join(data_args.image_folder, l["image"])): l["seg"] = l["image"].split("/")[-1] if "coco" in l["image"]: l["seg_folder"] = "coco_segm_text/train/panoptic_inference" elif "gqa" in l["image"]: l["seg_folder"] = "gqa/seg_images/panoptic_inference" elif "VG_100K_2" in l["image"]: l["seg_folder"] = "vg/vg/SEG_VG_100K_2/panoptic_inference" elif "VG_100K" in l["image"]: l["seg_folder"] = "vg/vg/SEG_VG_100K/panoptic_inference" elif "ocr_vqa" in l["image"]: l["seg_folder"] = "ocr_vqa/seg_images/panoptic_inference" if "textvqa" in l["image"]: l["seg_folder"] = "textvqa/seg_images/panoptic_inference" conversations = [] for c in l["conversations"]: if "<image>" in c["value"]: c["value"] = c["value"].replace("<image>", "<image>\n<seg>") conversations.append(c) l["conversations"] = conversations if len(conversations) > 0: list_data_dict.append(l) labels_dict = { "coco_segm_text/train": _get_labels("coco_segm_text/train/"), "gqa/seg_images": _get_labels("gqa/seg_images/"), "vg/vg/SEG_VG_100K": _get_labels("vg/vg/SEG_VG_100K/"), "vg/vg/SEG_VG_100K_2": _get_labels("vg/vg/SEG_VG_100K_2/"), "ocr_vqa/seg_images": _get_labels("ocr_vqa/seg_images"), "textvqa/seg_images": _get_labels("textvqa/seg_images/"), } random.shuffle(list_data_dict) list_data_dict = list_data_dict[:200000] final_list_data_dict = [] for l in list_data_dict: prob_add = np.random.uniform(0,1.) if prob_add > 0.7: labels = labels_dict[l["seg_folder"].split("/panoptic_inference")[0]] conversations = l["conversations"] even_indices = list(range(2, len(conversations) + 1, 2)) random_even_index = random.choice(even_indices) question_prob = np.random.uniform(0,1.) if question_prob > 0.90: question = "What objects can be seen in the image?" else: question = random.choice(PANOPTIC_QUESTIONS) conv = [{ "from": "human", "value": question }, { "from": "gpt", "value": labels[l["seg"]] }] final_conversations = conversations[:random_even_index] + conv + conversations[random_even_index:] l["conversations"] = final_conversations final_list_data_dict.append(l) return final_list_data_dict def obtain_seg_depth_data_splits(data_args): data_dict = json.load(open(data_args.data_path, "r")) list_data_dict = [] labels = _obtain_depth_texts(os.path.join(data_args.depth_data_path, "coco_segm_text", "depth", "train", "panoptic_order.txt")) for l in data_dict: if "image" in l.keys(): if os.path.exists(os.path.join(data_args.image_folder, l["image"])): if "coco" in l["image"]: l["depth"] = l["image"].split("/")[-1] l["seg"] = l["image"].split("/")[-1] l["seg_folder"] = "coco_segm_text/train/panoptic_inference" l["depth_folder"] = "coco_segm_text/depth/train/depth" conversations = [] for c in l["conversations"]: if "<image>" in c["value"]: c["value"] = c["value"].replace("<image>", "<image>\n<seg>\n<depth>") conversations.append(c) l["conversations"] = conversations if len(conversations) > 0: list_data_dict.append(l) random.shuffle(list_data_dict) list_data_dict = list_data_dict[:100000] final_list_data_dict = [] for l in list_data_dict: prob_add = np.random.uniform(0,1.) if prob_add > 0.7: conversations = l["conversations"] even_indices = list(range(2, len(conversations) + 1, 2)) random_even_index = random.choice(even_indices) conv = [{ "from": "human", "value": random.choice(DEPTH_QUESTIONS) }, { "from": "gpt", "value": labels[l["seg"]] }] final_conversations = conversations[:random_even_index] + conv + conversations[random_even_index:] l["conversations"] = final_conversations final_list_data_dict.append(l) return final_list_data_dict def get_object_data_depth_split(data_args): list_data_dict = [] for bucket in ["train", "unlabeled", "test"]: panoptic_labels = _obtain_seg_texts(os.path.join(data_args.seg_image_folder, "coco_segm_text", bucket, "panoptic.txt")) for key in panoptic_labels.keys(): question_prob = np.random.uniform(0,1.) answer = panoptic_labels[key] if question_prob > 0.90: question = "What objects can be seen in the image?" else: question = random.choice(PANOPTIC_QUESTIONS) seg_folder = "panoptic_inference" question += "\n<image>\n<seg>\n<depth>" conversations = [ { "from": "human", "value": question }, { "from": "gpt", "value": answer }, ] list_data_dict.append( { "conversations": conversations, "image": "coco/" + bucket + "2017/" + key, "seg": key, "depth": key, "seg_folder": "coco_segm_text/" + bucket + "/" + seg_folder, "depth_folder": "coco_segm_text/depth/" + bucket + "/" + "depth" } ) random.shuffle(list_data_dict) return list_data_dict[:50000] def get_object_data_split(data_args): list_data_dict = [] for bucket in ["train", "unlabeled", "test"]: panoptic_labels = _obtain_seg_texts(os.path.join(data_args.seg_image_folder, "coco_segm_text", bucket, "panoptic.txt")) semantic_labels = _obtain_seg_texts(os.path.join(data_args.seg_image_folder, "coco_segm_text", bucket, "semantic.txt")) instance_labels = _obtain_seg_texts(os.path.join(data_args.seg_image_folder, "coco_segm_text", bucket, "instance.txt")) for key in panoptic_labels.keys(): assert key in semantic_labels.keys() and key in instance_labels.keys(), "Instance, semantic, and panoptic labels should have the same keys." prob_task = np.random.uniform(0,1.) question_prob = np.random.uniform(0,1.) if prob_task < 0.33: answer = semantic_labels[key] if question_prob > 0.90: question = "What objects can be seen in the image?" else: question = random.choice(SEMANTIC_QUESTIONS) seg_folder = "semantic_inference" elif prob_task < 0.66: answer = instance_labels[key] if question_prob > 0.90: question = "What objects can be seen in the image?" else: question = random.choice(INSTANCE_QUESTIONS) seg_folder = "instance_inference" else: answer = panoptic_labels[key] if question_prob > 0.90: question = "What objects can be seen in the image?" else: question = random.choice(PANOPTIC_QUESTIONS) seg_folder = "panoptic_inference" question += "\n<image>\n<seg>" conversations = [ { "from": "human", "value": question }, { "from": "gpt", "value": answer }, ] list_data_dict.append( { "conversations": conversations, "image": "coco/" + bucket + "2017/" + key, "seg": key, "seg_folder": "coco_segm_text/" + bucket + "/" + seg_folder } ) random.shuffle(list_data_dict) return list_data_dict def get_depth_data_split(data_args): list_data_dict = [] for bucket in ["train", "unlabeled", "test"]: labels = _obtain_depth_texts(os.path.join(data_args.depth_data_path, "coco_segm_text", "depth", bucket, "panoptic_order.txt")) for key in labels.keys(): answer = labels[key] question = random.choice(DEPTH_QUESTIONS) question += "\n<image>\n<seg>\n<depth>" seg_folder = "panoptic_inference" conversations = [ { "from": "human", "value": question }, { "from": "gpt", "value": answer }, ] list_data_dict.append( { "conversations": conversations, "image": "coco/" + bucket + "2017/" + key, "seg": key, "depth": key, "seg_folder": "coco_segm_text/" + bucket + "/" + seg_folder, "depth_folder": "coco_segm_text/depth/" + bucket + "/" + "depth" } ) random.shuffle(list_data_dict) return list_data_dict def get_extra_count_data_split(data_args): list_data_dict = [] bucket = "train" panoptic_labels = _obtain_seg_texts(os.path.join(data_args.seg_image_folder, "coco_segm_text", bucket, "panoptic.txt")) for key in panoptic_labels.keys(): prob = np.random.uniform(0,1.) if prob > 0.99: answer = panoptic_labels[key] seg_folder = "panoptic_inference" qa_pairs = generate_qa_pairs(answer) if len(qa_pairs) >= 1: conversations = [] for idx, qa_pair in enumerate(qa_pairs): conversations.append( { "from": "human", "value": qa_pair[0] + "\n<image>\n<seg>" if idx == 0 else qa_pair[0] } ) conversations.append( { "from": "gpt", "value": qa_pair[1] } ) list_data_dict.append( { "conversations": conversations, "image": "coco/" + bucket + "2017/" + key, "seg": key, "seg_folder": "coco_segm_text/" + bucket + "/" + seg_folder } ) random.shuffle(list_data_dict) return list_data_dict class LazyDepthSegSupervisedDataset(Dataset): """Dataset for supervised fine-tuning.""" def __init__(self, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments): super(LazyDepthSegSupervisedDataset, self).__init__() list_data_dict = [] if data_args.data_path is not None: print("Preparing dataset, this may take upto 5 minutes...") seg_data_list = obtain_seg_data_splits(data_args) list_data_dict.extend(seg_data_list) depth_data_list = obtain_seg_depth_data_splits(data_args) list_data_dict.extend(depth_data_list) depth_object_list = get_object_data_depth_split(data_args) list_data_dict.extend(depth_object_list) object_data_list = get_object_data_split(data_args) list_data_dict.extend(object_data_list) depth_order_list = get_depth_data_split(data_args) list_data_dict.extend(depth_order_list) extra_object_list = get_extra_count_data_split(data_args) list_data_dict.extend(extra_object_list) rank0_print("Formatting inputs...Skip in lazy mode") self.tokenizer = tokenizer random.shuffle(list_data_dict) self.list_data_dict = list_data_dict self.data_args = data_args def __len__(self): return len(self.list_data_dict) @property def lengths(self): length_list = [] for sample in self.list_data_dict: seg_tokens = 128 if 'seg' in sample else 0 img_tokens = 128 if 'image' in sample else 0 depth_tokens = 128 if 'depth' in sample else 0 length_list.append(sum(len(conv['value'].split()) for conv in sample['conversations']) + img_tokens + seg_tokens + depth_tokens) return length_list @property def modality_lengths(self): length_list = [] for sample in self.list_data_dict: cur_len = sum(len(conv['value'].split()) for conv in sample['conversations']) cur_len = cur_len if 'image' in sample else -cur_len cur_len = cur_len if 'seg' in sample else -cur_len length_list.append(cur_len) return length_list def __getitem__(self, i) -> Dict[str, torch.Tensor]: sources = self.list_data_dict[i] if isinstance(i, int): sources = [sources] assert len(sources) == 1, "Don't know why it is wrapped to a list" # FIXME if 'image' in sources[0]: image_file = self.list_data_dict[i]['image'] image_folder = self.data_args.image_folder processor = self.data_args.image_processor image = Image.open(os.path.join(image_folder, image_file)).convert('RGB') seg_file = self.list_data_dict[i]['seg'] seg_folder = self.data_args.seg_image_folder seg = Image.open(os.path.join(seg_folder, self.list_data_dict[i]['seg_folder'], seg_file)).convert('RGB') seg_processor = self.data_args.seg_image_processor if 'depth' in sources[0]: depth_file = self.list_data_dict[i]['depth'] depth_folder = self.data_args.depth_data_path depth = Image.open(os.path.join(depth_folder, self.list_data_dict[i]['depth_folder'], depth_file)).convert('RGB') depth_processor = self.data_args.depth_image_processor else: depth = None if self.data_args.image_aspect_ratio == 'pad': def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result image = expand2square(image, tuple(int(x*255) for x in processor.image_mean)) image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] seg = expand2square(seg, tuple(int(x*255) for x in seg_processor.image_mean)) seg = seg_processor.preprocess(seg, return_tensors='pt')['pixel_values'][0] if depth is not None: depth = expand2square(depth, tuple(int(x*255) for x in depth_processor.image_mean)) depth = depth_processor.preprocess(depth, return_tensors='pt')['pixel_values'][0] else: image = processor.preprocess(image, return_tensors='pt')['pixel_values'][0] seg = seg_processor.preprocess(seg, return_tensors='pt')['pixel_values'][0] if depth is not None: depth = depth_processor.preprocess(depth, return_tensors='pt')['pixel_values'][0] sources = vcoder_ds_preprocess_multimodal( copy.deepcopy([e["conversations"] for e in sources]), self.data_args) else: sources = copy.deepcopy([e["conversations"] for e in sources]) data_dict = preprocess( sources, self.tokenizer, has_image=('image' in self.list_data_dict[i]), has_seg=('seg' in self.list_data_dict[i]), has_depth=('depth' in self.list_data_dict[i]) ) if isinstance(i, int): data_dict = dict(input_ids=data_dict["input_ids"][0], labels=data_dict["labels"][0]) if 'image' in self.list_data_dict[i]: data_dict['image'] = image elif self.data_args.is_multimodal: crop_size = self.data_args.image_processor.crop_size data_dict['image'] = torch.zeros(3, crop_size['height'], crop_size['width']) if 'seg' in self.list_data_dict[i]: data_dict['seg'] = seg elif self.data_args.is_multimodal: crop_size = self.data_args.seg_image_processor.crop_size data_dict['seg'] = torch.zeros(3, crop_size['height'], crop_size['width']) if 'depth' in self.list_data_dict[i]: data_dict['depth'] = depth elif self.data_args.is_multimodal: crop_size = self.data_args.depth_image_processor.crop_size data_dict['depth'] = torch.zeros(3, crop_size['height'], crop_size['width']) return data_dict @dataclass class DataCollatorForDepthSegSupervisedDataset(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) input_ids = input_ids[:, :self.tokenizer.model_max_length] labels = labels[:, :self.tokenizer.model_max_length] batch = dict( input_ids=input_ids, labels=labels, attention_mask=input_ids.ne(self.tokenizer.pad_token_id), ) if 'image' in instances[0]: images = [instance['image'] for instance in instances] if all(x is not None and x.shape == images[0].shape for x in images): batch['images'] = torch.stack(images) else: batch['images'] = images if 'seg' in instances[0]: segs = [instance['seg'] for instance in instances] if all(x is not None and x.shape == segs[0].shape for x in segs): batch['segs'] = torch.stack(segs) else: batch['segs'] = segs if 'depth' in instances[0]: depths = [instance['depth'] for instance in instances] if all(x is not None and x.shape == depths[0].shape for x in depths): batch['depths'] = torch.stack(depths) else: batch['depths'] = depths return batch def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict: """Make dataset and collator for supervised fine-tuning.""" train_dataset = LazyDepthSegSupervisedDataset(tokenizer=tokenizer, data_args=data_args) data_collator = DataCollatorForDepthSegSupervisedDataset(tokenizer=tokenizer) return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator) def vcoder_ds_train(): global local_rank parser = transformers.HfArgumentParser( (ModelArguments, DataArguments, TrainingArguments)) model_args, data_args, training_args = parser.parse_args_into_dataclasses() local_rank = training_args.local_rank compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) bnb_model_from_pretrained_args = {} if training_args.bits in [4, 8]: bnb_model_from_pretrained_args.update(dict( device_map={"": training_args.device}, load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, quantization_config=BitsAndBytesConfig( load_in_4bit=training_args.bits == 4, load_in_8bit=training_args.bits == 8, llm_int8_threshold=6.0, llm_int8_has_fp16_weight=False, bnb_4bit_compute_dtype=compute_dtype, bnb_4bit_use_double_quant=training_args.double_quant, bnb_4bit_quant_type=training_args.quant_type # {'fp4', 'nf4'} ) )) if model_args.depth_tune_adapter is not None: if 'mpt' in model_args.model_name_or_path: raise ValueError("MPT is not supported for VCoder Adapted Training.") else: model = VCoderDSLlavaLlamaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) else: model = transformers.LlamaForCausalLM.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, **bnb_model_from_pretrained_args ) model.config.use_cache = False if model_args.freeze_backbone: model.model.requires_grad_(False) if training_args.bits in [4, 8]: model.config.torch_dtype=(torch.float32 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32)) model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=training_args.gradient_checkpointing) if training_args.gradient_checkpointing: 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) if training_args.lora_enable: lora_config = LoraConfig( r=training_args.lora_r, lora_alpha=training_args.lora_alpha, target_modules=find_all_linear_names(model), lora_dropout=training_args.lora_dropout, bias=training_args.lora_bias, task_type="CAUSAL_LM", ) if training_args.bits == 16: if training_args.bf16: model.to(torch.bfloat16) if training_args.fp16: model.to(torch.float16) rank0_print("Adding LoRA adapters...") model = get_peft_model(model, lora_config) if 'mpt' in model_args.model_name_or_path: raise ValueError("MPT is not supported for VCoder Adapted Training.") else: tokenizer = transformers.AutoTokenizer.from_pretrained( model_args.model_name_or_path, cache_dir=training_args.cache_dir, model_max_length=training_args.model_max_length, padding_side="right", use_fast=False, ) tokenizer.pad_token = tokenizer.unk_token if model_args.version in conversation_lib.conv_templates: conversation_lib.default_conversation = conversation_lib.conv_templates[model_args.version] else: conversation_lib.default_conversation = conversation_lib.conv_templates["vicuna_v1"] # vision modules model.get_vision_tower().load_model() data_args.image_processor = model.get_vision_tower().image_processor data_args.is_multimodal = True vision_tower = model.get_vision_tower() vision_tower.to(dtype=torch.bfloat16 if training_args.bf16 else torch.float16, device=training_args.device) model.config.image_aspect_ratio = data_args.image_aspect_ratio model.config.image_grid_pinpoints = data_args.image_grid_pinpoints model.config.tune_mm_mlp_adapter = training_args.tune_mm_mlp_adapter = model_args.tune_mm_mlp_adapter if model_args.tune_mm_mlp_adapter: model.requires_grad_(False) for p in model.get_model().mm_projector.parameters(): p.requires_grad = True model.config.freeze_mm_mlp_adapter = training_args.freeze_mm_mlp_adapter if training_args.freeze_mm_mlp_adapter: for p in model.get_model().mm_projector.parameters(): p.requires_grad = False if training_args.bits in [4, 8]: model.get_model().mm_projector.to(dtype=compute_dtype, device=training_args.device) if model_args.seg_tune_adapter is not None: model.get_model().initialize_seg_modules( model_args=model_args, fsdp=training_args.fsdp ) if model_args.seg_tune_adapter: if getattr(model_args, "freeze_llm", False): model.requires_grad_(False) for p in model.get_model().seg_mm_projector.parameters(): p.requires_grad = True for p in model.get_model().vcoder_lm_emb.parameters(): p.requires_grad = True data_args.seg_image_processor = model.get_vision_tower().image_processor model.config.use_mm2_proj = model_args.use_mm2_proj model.config.mm_vcoder_lm_emb = True model.config.seg_tune_adapter = training_args.seg_tune_adapter = model_args.seg_tune_adapter model.config.freeze_seg_mm_mlp_adapter = training_args.freeze_seg_mm_mlp_adapter if training_args.freeze_seg_mm_mlp_adapter: for p in model.get_model().seg_mm_projector.parameters(): p.requires_grad = False if model_args.use_mm2_proj: for p in model.get_model().mm2_projector.parameters(): p.requires_grad = False if training_args.bits in [4, 8]: model.get_model().seg_mm_projector.to(dtype=compute_dtype, device=training_args.device) else: # seg modules data_args.seg_image_processor = model.get_vision_tower().image_processor if training_args.bits in [4, 8]: model.get_model().seg_mm_projector.to(dtype=compute_dtype, device=training_args.device) if model_args.depth_tune_adapter is not None: model.get_model().initialize_depth_modules( model_args=model_args, fsdp=training_args.fsdp ) if getattr(model_args, "freeze_llm", False): model.requires_grad_(False) for p in model.get_model().depth_mm_projector.parameters(): p.requires_grad = True for p in model.get_model().vcoder_lm_emb.parameters(): p.requires_grad = True if model_args.seg_tune_adapter: for p in model.get_model().seg_mm_projector.parameters(): p.requires_grad = True data_args.depth_image_processor = model.get_vision_tower().image_processor model.config.depth_tune_adapter = training_args.depth_tune_adapter = model_args.depth_tune_adapter model.config.freeze_depth_mm_mlp_adapter = training_args.freeze_depth_mm_mlp_adapter if training_args.freeze_depth_mm_mlp_adapter: for p in model.get_model().depth_mm_projector.parameters(): p.requires_grad = False if training_args.bits in [4, 8]: model.get_model().depth_mm_projector.to(dtype=compute_dtype, device=training_args.device) if training_args.bits in [4, 8]: for name, module in model.named_modules(): if isinstance(module, LoraLayer): if training_args.bf16: module = module.to(torch.bfloat16) if 'norm' in name: module = module.to(torch.float32) if 'lm_head' in name or 'embed_tokens' in name: if hasattr(module, 'weight'): if training_args.bf16 and module.weight.dtype == torch.float32: module = module.to(torch.bfloat16) data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
trainer = VCoderDSLLaVATrainer(model=model,
4
2023-12-17 07:46:27+00:00
12k
DeepWok/mase
machop/chop/models/manual/opt_lora/modeling_opt_lora.py
[ { "identifier": "LoraLayer", "path": "machop/chop/models/manual/lora_modules.py", "snippet": "class LoraLayer:\n def __init__(self, in_features: int, out_features: int, **kwargs):\n self.r = {}\n self.lora_alpha = {}\n self.scaling = {}\n self.lora_dropout = nn.ModuleDict(...
import random import torch import torch.utils.checkpoint from typing import Optional, Tuple, Union from torch import nn from torch.nn import CrossEntropyLoss from transformers.activations import ACT2FN from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import logging, replace_return_docstrings from ..lora_modules import LoraLayer, LinearLora from .configuration_opt_lora import OPTLoraConfig from .utils_opt import ( OPTAttention_attention_get_dtype_min, OPTAttention_attention_mask_shape_check, OPTAttention_attn_output_shape_check, OPTAttention_attn_weight_dtype_check, OPTAttention_attn_weights_shape_check, OPTAttention_layer_head_mask_shape_check, OPTAttention_reshape_qkv_back_for_bmm, OPTAttention_self_shape, OPTDecoder_check_head_mask, OPTDecoder_self_prepare_decoder_attention, OPTForCasualLM_compute_loss, )
7,224
self.lm_head = nn.Linear( config.word_embed_proj_dim, config.vocab_size, bias=False ) # self.loss_fct = CrossEntropyLoss() # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.decoder.embed_tokens def set_input_embeddings(self, value): self.model.decoder.embed_tokens = value def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings def set_decoder(self, decoder): self.model.decoder = decoder def get_decoder(self): return self.model.decoder @replace_return_docstrings( output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC ) def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor = None, labels: torch.LongTensor = None, head_mask: Optional[torch.Tensor] = None, # inputs_embeds: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = False, output_hidden_states: Optional[bool] = False, return_dict: Optional[bool] = True, ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. Returns: Example: ```python >>> from transformers import AutoTokenizer, OPTForCausalLM >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") >>> prompt = "Hey, are you consciours? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." ```""" return_dict = self.config.return_dict if return_dict is None else return_dict output_attentions = ( self.config.output_attentions if output_attentions is None else output_attentions ) output_hidden_states = ( self.config.output_hidden_states if output_hidden_states is None else output_hidden_states ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model.decoder( input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, # inputs_embeds=inputs_embeds, ) logits = self.lm_head(outputs[0]).contiguous() loss = None if labels is not None: # # Shift so that tokens < n predict n
# coding=utf-8 # ---------------------------------------------- # This is a traceable version of OPTModel and OPTForCausalLanguageModeling # modified code based on HuggingFace's opt # ---------------------------------------------- # Copyright 2022 The Fairseq Authors and The HuggingFace Inc. 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. """ PyTorch OPT model.""" logger = logging.get_logger(__name__) _CHECKPOINT_FOR_DOC = "facebook/opt-350m" _CONFIG_FOR_DOC = "OPTLoraConfig" # Base model docstring _EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ "facebook/opt-125m", "facebook/opt-350m", "facebook/opt-1.3b", "facebook/opt-2.7b", "facebook/opt-6.7b", "facebook/opt-13b", "facebook/opt-30b", # See all OPT models at https://huggingface.co/models?filter=opt ] class OPTLearnedPositionalEmbedding(nn.Embedding): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, num_embeddings: int, embedding_dim: int): # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 # and adjust num_embeddings appropriately. Other models don't have this hack self.offset = 2 super().__init__(num_embeddings + self.offset, embedding_dim) def forward( self, attention_mask: torch.LongTensor, past_key_values_length: int = 0 ): """`input_ids_shape` is expected to be [bsz x seqlen].""" attention_mask = attention_mask.long() # create positions depending on attention_mask positions = ( torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask ).long() - 1 # cut positions if `past_key_values_length` is > 0 positions = positions[:, past_key_values_length:] return super().forward(positions + self.offset) class OPTAttention(nn.Module): """ - FX-traceable Multi-headed attention from 'Attention Is All You Need' paper - This module includes multi-head (k, q, v linear, attention), concat, and attention output linear - To make this module traceable, `mode` must be one of integer 0, 1, 2, or 3. - The default mode `None` (un-traceable mode) can be used for training (testing), but not for modify-sw. """ custom_node_leaf_patch = [ ("embeddings", "BertEmbeddingsPatched", OPTLearnedPositionalEmbedding) ] def __init__( self, config: OPTLoraConfig, embed_dim: int, num_heads: int, layer_id: int = 0, dropout: float = 0.0, is_decoder: bool = False, bias: bool = False, ): super().__init__() self.config = config self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads if (self.head_dim * num_heads) != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" f" and `num_heads`: {num_heads})." ) self.scaling = self.head_dim**-0.5 self.is_decoder = is_decoder lora_config = config.lora_config[f"model_layer_{layer_id}"]["self_attn"] self.k_proj = LinearLora( in_features=embed_dim, out_features=embed_dim, bias=bias, config=lora_config["k_proj"], ) self.v_proj = LinearLora( in_features=embed_dim, out_features=embed_dim, bias=bias, config=lora_config["v_proj"], ) self.q_proj = LinearLora( in_features=embed_dim, out_features=embed_dim, bias=bias, config=lora_config["q_proj"], ) self.o_proj = LinearLora( in_features=embed_dim, out_features=embed_dim, bias=bias, config=lora_config["o_proj"], ) self.lora_config = lora_config def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, # key_value_states: Optional[torch.Tensor] = None, # past_key_value: Optional[Tuple[torch.Tensor]] = None, layer_head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: """Input shape: Batch x Time x Channel""" bsz, tgt_len, _ = hidden_states.shape # get query proj query_states = self.q_proj(hidden_states) * self.scaling # self_attention # key_value_states is None, past_key_value is None key_states = OPTAttention_self_shape( self.k_proj(hidden_states), seq_len=-1, bsz=bsz, num_heads=self.num_heads, head_dim=self.head_dim, ) value_states = OPTAttention_self_shape( self.v_proj(hidden_states), seq_len=-1, bsz=bsz, num_heads=self.num_heads, head_dim=self.head_dim, ) # proj_shape = OPTAttention_construct_proj_shape( # bsz, self.num_heads, self.head_dim # ) proj_shape = (bsz * self.num_heads, -1, self.head_dim) query_states, key_states, value_states = OPTAttention_reshape_qkv_back_for_bmm( query_states, key_states, value_states, proj_shape=proj_shape, tgt_len=tgt_len, bsz=bsz, num_heads=self.num_heads, head_dim=self.head_dim, ) src_len = key_states.shape[1] attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) OPTAttention_attn_weights_shape_check( attn_weights, bsz, self.num_heads, tgt_len, src_len ) if attention_mask is not None: OPTAttention_attention_mask_shape_check( attention_mask, bsz, tgt_len, src_len ) attn_weights = ( attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask ) attn_weights = torch.max( attn_weights, OPTAttention_attention_get_dtype_min(attn_weights) ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) # Patched OPTAttention does not support FP16 # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437 OPTAttention_attn_weight_dtype_check(attn_weights) # *: Currently this model does not support torch.float16 # if attn_weights.dtype == torch.float16: # attn_weights = nn.functional.softmax( # attn_weights, dim=-1, dtype=torch.float32 # ).to(torch.float16) # else: # attn_weights = nn.functional.softmax(attn_weights, dim=-1) attn_weights = nn.functional.softmax(attn_weights, dim=-1) if layer_head_mask is not None: OPTAttention_layer_head_mask_shape_check(layer_head_mask, self.num_heads) attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view( bsz, self.num_heads, tgt_len, src_len ) attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) if output_attentions: # this operation is a bit awkward, but it's required to # make sure that attn_weights keeps its gradient. # In order to do so, attn_weights have to be reshaped # twice and have to be reused in the following attn_weights_reshaped = attn_weights.view( bsz, self.num_heads, tgt_len, src_len ) attn_weights = attn_weights_reshaped.view( bsz * self.num_heads, tgt_len, src_len ) else: attn_weights_reshaped = None attn_probs = nn.functional.dropout( attn_weights, p=self.dropout, training=self.training ) attn_output = torch.bmm(attn_probs, value_states) OPTAttention_attn_output_shape_check( attn_output, bsz, self.num_heads, tgt_len, self.head_dim ) attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) attn_output = attn_output.transpose(1, 2) # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be # partitioned aross GPUs when using tensor-parallelism. attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) attn_output = self.o_proj(attn_output) return attn_output, attn_weights_reshaped class OPTDecoderLayer(nn.Module): def __init__(self, config: OPTLoraConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = OPTAttention( config=config, embed_dim=self.embed_dim, num_heads=config.num_attention_heads, dropout=config.attention_dropout, is_decoder=True, bias=config.enable_bias, ) self.do_layer_norm_before = config.do_layer_norm_before self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.self_attn_layer_norm = nn.LayerNorm( self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine ) self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim, bias=config.enable_bias) self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim, bias=config.enable_bias) self.final_layer_norm = nn.LayerNorm( self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine ) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, layer_head_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ) -> Tuple[ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] ]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size `(encoder_attention_heads,)`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention if self.do_layer_norm_before: hidden_states = self.self_attn_layer_norm(hidden_states) # Self Attention # *: key_value_states is always None hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, # past_key_value=None, attention_mask=attention_mask, layer_head_mask=layer_head_mask, output_attentions=output_attentions, # key_value_states=None, ) hidden_states = nn.functional.dropout( hidden_states, p=self.dropout, training=self.training ) hidden_states = residual + hidden_states # 350m applies layer norm AFTER attention if not self.do_layer_norm_before: hidden_states = self.self_attn_layer_norm(hidden_states) # Fully Connected hidden_states_shape = hidden_states.shape hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1]) residual = hidden_states # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention if self.do_layer_norm_before: hidden_states = self.final_layer_norm(hidden_states) hidden_states = self.fc1(hidden_states) hidden_states = self.activation_fn(hidden_states) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout( hidden_states, p=self.dropout, training=self.training ) hidden_states = (residual + hidden_states).view(hidden_states_shape) # 350m applies layer norm AFTER attention if not self.do_layer_norm_before: hidden_states = self.final_layer_norm(hidden_states) outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) return outputs class OPTPreTrainedModel(PreTrainedModel): config_class = OPTLoraConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["OPTDecoderLayer"] _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] def _init_weights(self, module): std = self.config.init_std if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, OPTDecoder): module.gradient_checkpointing = value class OPTDecoder(OPTPreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`] Args: config: OPTConfig """ custom_node_leaf_patch = [ ( "embed_positions", "OPTLearnedPositionalEmbedding", OPTLearnedPositionalEmbedding, ) ] def __init__(self, config: OPTLoraConfig): super().__init__(config) self.dropout = config.dropout self.layerdrop = config.layerdrop self.padding_idx = config.pad_token_id self.max_target_positions = config.max_position_embeddings self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding( config.vocab_size, config.word_embed_proj_dim, self.padding_idx ) self.embed_positions = OPTLearnedPositionalEmbedding( config.max_position_embeddings, config.hidden_size ) if config.word_embed_proj_dim != config.hidden_size: self.project_out = nn.Linear( config.hidden_size, config.word_embed_proj_dim, bias=False ) else: self.project_out = None if config.word_embed_proj_dim != config.hidden_size: self.project_in = nn.Linear( config.word_embed_proj_dim, config.hidden_size, bias=False ) else: self.project_in = None # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility # with checkpoints that have been fine-tuned before transformers v4.20.1 # see https://github.com/facebookresearch/metaseq/pull/164 if config.do_layer_norm_before and not config._remove_final_layer_norm: self.final_layer_norm = nn.LayerNorm( config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine, ) else: self.final_layer_norm = None self.layers = nn.ModuleList( [OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)] ) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, value): self.embed_tokens = value def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor = None, head_mask: Optional[torch.Tensor] = None, # inputs_embeds: Optional[torch.FloatTensor] = None, return_dict: Optional[bool] = True, output_attentions: Optional[bool] = False, output_hidden_states: Optional[bool] = False, ) -> Union[Tuple, BaseModelOutputWithPast]: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. """ return_dict = self.config.return_dict if return_dict is None else return_dict output_attentions = ( self.config.output_attentions if output_attentions is None else output_attentions ) output_hidden_states = ( self.config.output_hidden_states if output_hidden_states is None else output_hidden_states ) input_shape = input_ids.shape input_ids = input_ids.view(-1, input_shape[-1]) # input_ids = OPTDecoder_view_input_ids( # input_ids=input_ids, input_shape=input_shape # ) past_key_values_length = 0 inputs_embeds = self.embed_tokens(input_ids) # embed positions # TODO: check this? if attention_mask is None: attention_mask = torch.ones( inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device ) pos_embeds = self.embed_positions(attention_mask, past_key_values_length) attention_mask = OPTDecoder_self_prepare_decoder_attention( attention_mask, input_shape, inputs_embeds, past_key_values_length ) if self.project_in is not None: inputs_embeds = self.project_in(inputs_embeds) hidden_states = inputs_embeds + pos_embeds # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None # check if head_mask has a correct number of layers specified if desired OPTDecoder_check_head_mask(head_mask, self.layers) for idx, decoder_layer in enumerate(self.layers): # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) if output_hidden_states: all_hidden_states += (hidden_states,) dropout_probability = random.uniform(0, 1) if self.training and (dropout_probability < self.layerdrop): continue layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, layer_head_mask=(head_mask[idx] if head_mask is not None else None), output_attentions=output_attentions, ) hidden_states = layer_outputs[0] if output_attentions: all_self_attns += (layer_outputs[1],) if self.final_layer_norm is not None: hidden_states = self.final_layer_norm(hidden_states) if self.project_out is not None: hidden_states = self.project_out(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = None if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) class OPTModel(OPTPreTrainedModel): def __init__(self, config: OPTLoraConfig): super().__init__(config) self.decoder = OPTDecoder(config) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.decoder.embed_tokens def set_input_embeddings(self, value): self.decoder.embed_tokens = value def get_decoder(self): return self.decoder def forward( self, input_ids: torch.LongTensor = None, attention_mask: torch.Tensor = None, head_mask: Optional[torch.Tensor] = None, return_dict: Optional[bool] = True, output_attentions: Optional[bool] = False, output_hidden_states: Optional[bool] = False, ) -> Union[Tuple, BaseModelOutputWithPast]: output_attentions = ( self.config.output_attentions if output_attentions is None else output_attentions ) output_hidden_states = ( self.config.output_hidden_states if output_hidden_states is None else output_hidden_states ) return_dict = self.config.return_dict if return_dict is None else return_dict # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) decoder_outputs = self.decoder( input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) if not return_dict: return decoder_outputs return BaseModelOutputWithPast( last_hidden_state=decoder_outputs.last_hidden_state, past_key_values=decoder_outputs.past_key_values, hidden_states=decoder_outputs.hidden_states, attentions=decoder_outputs.attentions, ) class OPTForCausalLM(OPTPreTrainedModel): _keys_to_ignore_on_load_missing = [r"lm_head.weight"] def __init__(self, config): super().__init__(config) self.model = OPTModel(config) # the lm_head weight is automatically tied to the embed tokens weight self.lm_head = nn.Linear( config.word_embed_proj_dim, config.vocab_size, bias=False ) # self.loss_fct = CrossEntropyLoss() # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.decoder.embed_tokens def set_input_embeddings(self, value): self.model.decoder.embed_tokens = value def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings def set_decoder(self, decoder): self.model.decoder = decoder def get_decoder(self): return self.model.decoder @replace_return_docstrings( output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC ) def forward( self, input_ids: torch.LongTensor, attention_mask: torch.Tensor = None, labels: torch.LongTensor = None, head_mask: Optional[torch.Tensor] = None, # inputs_embeds: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = False, output_hidden_states: Optional[bool] = False, return_dict: Optional[bool] = True, ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. Returns: Example: ```python >>> from transformers import AutoTokenizer, OPTForCausalLM >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") >>> prompt = "Hey, are you consciours? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." ```""" return_dict = self.config.return_dict if return_dict is None else return_dict output_attentions = ( self.config.output_attentions if output_attentions is None else output_attentions ) output_hidden_states = ( self.config.output_hidden_states if output_hidden_states is None else output_hidden_states ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model.decoder( input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, # inputs_embeds=inputs_embeds, ) logits = self.lm_head(outputs[0]).contiguous() loss = None if labels is not None: # # Shift so that tokens < n predict n
loss = OPTForCasualLM_compute_loss(
13
2023-12-18 12:50:53+00:00
12k
byeongjun-park/HarmonyView
ldm/models/diffusion/sync_dreamer.py
[ { "identifier": "read_pickle", "path": "ldm/base_utils.py", "snippet": "def read_pickle(pkl_path):\n with open(pkl_path, 'rb') as f:\n return pickle.load(f)" }, { "identifier": "concat_images_list", "path": "ldm/base_utils.py", "snippet": "def concat_images_list(*args,vert=Fals...
from pathlib import Path from skimage.io import imsave from torch.optim.lr_scheduler import LambdaLR from tqdm import tqdm from ldm.base_utils import read_pickle, concat_images_list from ldm.models.diffusion.sync_dreamer_utils import get_warp_coordinates, create_target_volume from ldm.models.diffusion.sync_dreamer_network import NoisyTargetViewEncoder, SpatialTime3DNet, FrustumTV3DNet from ldm.modules.diffusionmodules.util import make_ddim_timesteps, timestep_embedding from ldm.modules.encoders.modules import FrozenCLIPImageEmbedder from ldm.util import instantiate_from_config import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F import numpy as np
7,436
volume_xyz, volume_depth = create_target_volume(D, self.frustum_volume_size, self.input_image_size, poses_, Ks_, near, far) # B*TN,3 or 1,D,H,W volume_xyz_ = volume_xyz / self.spatial_volume_length # since the spatial volume is constructed in [-spatial_volume_length,spatial_volume_length] volume_xyz_ = volume_xyz_.permute(0, 2, 3, 4, 1) # B*TN,D,H,W,3 spatial_volume_ = spatial_volume.unsqueeze(1).repeat(1, TN, 1, 1, 1, 1).view(B * TN, -1, V, V, V) volume_feats = F.grid_sample(spatial_volume_, volume_xyz_, mode='bilinear', padding_mode='zeros', align_corners=True) # B*TN,C,D,H,W v_embed_ = v_embed[torch.arange(B)[:,None], target_indices.view(B,TN)].view(B*TN, -1) # B*TN t_embed_ = t_embed.unsqueeze(1).repeat(1,TN,1).view(B*TN,-1) volume_feats_dict = self.frustum_volume_feats(volume_feats, t_embed_, v_embed_) return volume_feats_dict, volume_depth class SyncMultiviewDiffusion(pl.LightningModule): def __init__(self, unet_config, scheduler_config, finetune_unet=False, finetune_projection=True, view_num=16, image_size=256, cfg_scale=3.0, output_num=8, batch_view_num=4, drop_conditions=False, drop_scheme='default', clip_image_encoder_path="/apdcephfs/private_rondyliu/projects/clip/ViT-L-14.pt", sample_type='ddim', sample_steps=200): super().__init__() self.finetune_unet = finetune_unet self.finetune_projection = finetune_projection self.view_num = view_num self.viewpoint_dim = 4 self.output_num = output_num self.image_size = image_size self.batch_view_num = batch_view_num self.cfg_scale = cfg_scale self.clip_image_encoder_path = clip_image_encoder_path self._init_time_step_embedding() self._init_first_stage() self._init_schedule() self._init_multiview() self._init_clip_image_encoder() self._init_clip_projection() self.spatial_volume = SpatialVolumeNet(self.time_embed_dim, self.viewpoint_dim, self.view_num) self.model = UNetWrapper(unet_config, drop_conditions=drop_conditions, drop_scheme=drop_scheme) self.scheduler_config = scheduler_config latent_size = image_size//8 if sample_type=='ddim': self.sampler = SyncDDIMSampler(self, sample_steps , "uniform", 1.0, latent_size=latent_size) else: raise NotImplementedError def _init_clip_projection(self): self.cc_projection = nn.Linear(772, 768) nn.init.eye_(list(self.cc_projection.parameters())[0][:768, :768]) nn.init.zeros_(list(self.cc_projection.parameters())[1]) self.cc_projection.requires_grad_(True) if not self.finetune_projection: disable_training_module(self.cc_projection) def _init_multiview(self): K, azs, _, _, poses = read_pickle(f'meta_info/camera-{self.view_num}.pkl') default_image_size = 256 ratio = self.image_size/default_image_size K = np.diag([ratio,ratio,1]) @ K K = torch.from_numpy(K.astype(np.float32)) # [3,3] K = K.unsqueeze(0).repeat(self.view_num,1,1) # N,3,3 poses = torch.from_numpy(poses.astype(np.float32)) # N,3,4 self.register_buffer('poses', poses) self.register_buffer('Ks', K) azs = (azs + np.pi) % (np.pi * 2) - np.pi # scale to [-pi,pi] and the index=0 has az=0 self.register_buffer('azimuth', torch.from_numpy(azs.astype(np.float32))) def get_viewpoint_embedding(self, batch_size, elevation_ref): """ @param batch_size: @param elevation_ref: B @return: """ azimuth_input = self.azimuth[0].unsqueeze(0) # 1 azimuth_target = self.azimuth # N elevation_input = -elevation_ref # note that zero123 use a negative elevation here!!! elevation_target = -np.deg2rad(30) d_e = elevation_target - elevation_input # B N = self.azimuth.shape[0] B = batch_size d_e = d_e.unsqueeze(1).repeat(1, N) d_a = azimuth_target - azimuth_input # N d_a = d_a.unsqueeze(0).repeat(B, 1) d_z = torch.zeros_like(d_a) embedding = torch.stack([d_e, torch.sin(d_a), torch.cos(d_a), d_z], -1) # B,N,4 return embedding def _init_first_stage(self): first_stage_config={ "target": "ldm.models.autoencoder.AutoencoderKL", "params": { "embed_dim": 4, "monitor": "val/rec_loss", "ddconfig":{ "double_z": True, "z_channels": 4, "resolution": self.image_size, "in_channels": 3, "out_ch": 3, "ch": 128, "ch_mult": [1,2,4,4], "num_res_blocks": 2, "attn_resolutions": [], "dropout": 0.0 }, "lossconfig": {"target": "torch.nn.Identity"}, } } self.first_stage_scale_factor = 0.18215 self.first_stage_model = instantiate_from_config(first_stage_config) self.first_stage_model = disable_training_module(self.first_stage_model) def _init_clip_image_encoder(self):
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 disable_training_module(module: nn.Module): module = module.eval() module.train = disabled_train for para in module.parameters(): para.requires_grad = False return module def repeat_to_batch(tensor, B, VN): t_shape = tensor.shape ones = [1 for _ in range(len(t_shape)-1)] tensor_new = tensor.view(B,1,*t_shape[1:]).repeat(1,VN,*ones).view(B*VN,*t_shape[1:]) return tensor_new class UNetWrapper(nn.Module): def __init__(self, diff_model_config, drop_conditions=False, drop_scheme='default', use_zero_123=True): super().__init__() self.diffusion_model = instantiate_from_config(diff_model_config) self.drop_conditions = drop_conditions self.drop_scheme=drop_scheme self.use_zero_123 = use_zero_123 def drop(self, cond, mask): shape = cond.shape B = shape[0] cond = mask.view(B,*[1 for _ in range(len(shape)-1)]) * cond return cond def get_trainable_parameters(self): return self.diffusion_model.get_trainable_parameters() def get_drop_scheme(self, B, device): if self.drop_scheme=='default': random = torch.rand(B, dtype=torch.float32, device=device) drop_clip = (random > 0.15) & (random <= 0.2) drop_volume = (random > 0.1) & (random <= 0.15) drop_concat = (random > 0.05) & (random <= 0.1) drop_all = random <= 0.05 else: raise NotImplementedError return drop_clip, drop_volume, drop_concat, drop_all def forward(self, x, t, clip_embed, volume_feats, x_concat, is_train=False): """ @param x: B,4,H,W @param t: B, @param clip_embed: B,M,768 @param volume_feats: B,C,D,H,W @param x_concat: B,C,H,W @param is_train: @return: """ if self.drop_conditions and is_train: B = x.shape[0] drop_clip, drop_volume, drop_concat, drop_all = self.get_drop_scheme(B, x.device) clip_mask = 1.0 - (drop_clip | drop_all).float() clip_embed = self.drop(clip_embed, clip_mask) volume_mask = 1.0 - (drop_volume | drop_all).float() for k, v in volume_feats.items(): volume_feats[k] = self.drop(v, mask=volume_mask) concat_mask = 1.0 - (drop_concat | drop_all).float() x_concat = self.drop(x_concat, concat_mask) if self.use_zero_123: # zero123 does not multiply this when encoding, maybe a bug for zero123 first_stage_scale_factor = 0.18215 x_concat_ = x_concat * 1.0 x_concat_[:, :4] = x_concat_[:, :4] / first_stage_scale_factor else: x_concat_ = x_concat x = torch.cat([x, x_concat_], 1) pred = self.diffusion_model(x, t, clip_embed, source_dict=volume_feats) return pred def predict_with_unconditional_scale(self, x, t, clip_embed, volume_feats, x_concat, unconditional_scale): x_ = torch.cat([x] * 2, 0) t_ = torch.cat([t] * 2, 0) clip_embed_ = torch.cat([clip_embed, torch.zeros_like(clip_embed)], 0) v_ = {} for k, v in volume_feats.items(): v_[k] = torch.cat([v, torch.zeros_like(v)], 0) x_concat_ = torch.cat([x_concat, torch.zeros_like(x_concat)], 0) if self.use_zero_123: # zero123 does not multiply this when encoding, maybe a bug for zero123 first_stage_scale_factor = 0.18215 x_concat_[:, :4] = x_concat_[:, :4] / first_stage_scale_factor x_ = torch.cat([x_, x_concat_], 1) s, s_uc = self.diffusion_model(x_, t_, clip_embed_, source_dict=v_).chunk(2) s = s_uc + unconditional_scale * (s - s_uc) return s def predict_with_decomposed_unconditional_scales(self, x, t, clip_embed, volume_feats, x_concat, unconditional_scales): x_ = torch.cat([x] * 3, 0) t_ = torch.cat([t] * 3, 0) clip_embed_ = torch.cat([clip_embed, torch.zeros_like(clip_embed), clip_embed], 0) x_concat_ = torch.cat([x_concat, torch.zeros_like(x_concat), x_concat*4], 0) v_ = {} for k, v in volume_feats.items(): v_[k] = torch.cat([v, v, torch.zeros_like(v)], 0) if self.use_zero_123: # zero123 does not multiply this when encoding, maybe a bug for zero123 first_stage_scale_factor = 0.18215 x_concat_[:, :4] = x_concat_[:, :4] / first_stage_scale_factor x_ = torch.cat([x_, x_concat_], 1) s, s_uc1, s_uc2 = self.diffusion_model(x_, t_, clip_embed_, source_dict=v_).chunk(3) s = s + unconditional_scales[0] * (s - s_uc1) + unconditional_scales[1] * (s - s_uc2) return s class SpatialVolumeNet(nn.Module): def __init__(self, time_dim, view_dim, view_num, input_image_size=256, frustum_volume_depth=48, spatial_volume_size=32, spatial_volume_length=0.5, frustum_volume_length=0.86603 # sqrt(3)/2 ): super().__init__() self.target_encoder = NoisyTargetViewEncoder(time_dim, view_dim, output_dim=16) self.spatial_volume_feats = SpatialTime3DNet(input_dim=16 * view_num, time_dim=time_dim, dims=(64, 128, 256, 512)) self.frustum_volume_feats = FrustumTV3DNet(64, time_dim, view_dim, dims=(64, 128, 256, 512)) self.frustum_volume_length = frustum_volume_length self.input_image_size = input_image_size self.spatial_volume_size = spatial_volume_size self.spatial_volume_length = spatial_volume_length self.frustum_volume_size = self.input_image_size // 8 self.frustum_volume_depth = frustum_volume_depth self.time_dim = time_dim self.view_dim = view_dim self.default_origin_depth = 1.5 # our rendered images are 1.5 away from the origin, we assume camera is 1.5 away from the origin def construct_spatial_volume(self, x, t_embed, v_embed, target_poses, target_Ks): """ @param x: B,N,4,H,W @param t_embed: B,t_dim @param v_embed: B,N,v_dim @param target_poses: N,3,4 @param target_Ks: N,3,3 @return: """ B, N, _, H, W = x.shape V = self.spatial_volume_size device = x.device spatial_volume_verts = torch.linspace(-self.spatial_volume_length, self.spatial_volume_length, V, dtype=torch.float32, device=device) spatial_volume_verts = torch.stack(torch.meshgrid(spatial_volume_verts, spatial_volume_verts, spatial_volume_verts, indexing='ij'), -1) spatial_volume_verts = spatial_volume_verts.reshape(1, V ** 3, 3)[:, :, (2, 1, 0)] spatial_volume_verts = spatial_volume_verts.view(1, V, V, V, 3).permute(0, 4, 1, 2, 3).repeat(B, 1, 1, 1, 1) # encode source features t_embed_ = t_embed.view(B, 1, self.time_dim).repeat(1, N, 1).view(B, N, self.time_dim) v_embed_ = v_embed target_Ks = target_Ks.unsqueeze(0).repeat(B, 1, 1, 1) target_poses = target_poses.unsqueeze(0).repeat(B, 1, 1, 1) # extract 2D image features spatial_volume_feats = [] # project source features for ni in range(0, N): pose_source_ = target_poses[:, ni] K_source_ = target_Ks[:, ni] x_ = self.target_encoder(x[:, ni], t_embed_[:, ni], v_embed_[:, ni]) C = x_.shape[1] coords_source = get_warp_coordinates(spatial_volume_verts, x_.shape[-1], self.input_image_size, K_source_, pose_source_).view(B, V, V * V, 2) unproj_feats_ = F.grid_sample(x_, coords_source, mode='bilinear', padding_mode='zeros', align_corners=True) unproj_feats_ = unproj_feats_.view(B, C, V, V, V) spatial_volume_feats.append(unproj_feats_) spatial_volume_feats = torch.stack(spatial_volume_feats, 1) # B,N,C,V,V,V N = spatial_volume_feats.shape[1] spatial_volume_feats = spatial_volume_feats.view(B, N*C, V, V, V) spatial_volume_feats = self.spatial_volume_feats(spatial_volume_feats, t_embed) # b,64,32,32,32 return spatial_volume_feats def construct_view_frustum_volume(self, spatial_volume, t_embed, v_embed, poses, Ks, target_indices): """ @param spatial_volume: B,C,V,V,V @param t_embed: B,t_dim @param v_embed: B,N,v_dim @param poses: N,3,4 @param Ks: N,3,3 @param target_indices: B,TN @return: B*TN,C,H,W """ B, TN = target_indices.shape H, W = self.frustum_volume_size, self.frustum_volume_size D = self.frustum_volume_depth V = self.spatial_volume_size near = torch.ones(B * TN, 1, H, W, dtype=spatial_volume.dtype, device=spatial_volume.device) * self.default_origin_depth - self.frustum_volume_length far = torch.ones(B * TN, 1, H, W, dtype=spatial_volume.dtype, device=spatial_volume.device) * self.default_origin_depth + self.frustum_volume_length target_indices = target_indices.view(B*TN) # B*TN poses_ = poses[target_indices] # B*TN,3,4 Ks_ = Ks[target_indices] # B*TN,3,4 volume_xyz, volume_depth = create_target_volume(D, self.frustum_volume_size, self.input_image_size, poses_, Ks_, near, far) # B*TN,3 or 1,D,H,W volume_xyz_ = volume_xyz / self.spatial_volume_length # since the spatial volume is constructed in [-spatial_volume_length,spatial_volume_length] volume_xyz_ = volume_xyz_.permute(0, 2, 3, 4, 1) # B*TN,D,H,W,3 spatial_volume_ = spatial_volume.unsqueeze(1).repeat(1, TN, 1, 1, 1, 1).view(B * TN, -1, V, V, V) volume_feats = F.grid_sample(spatial_volume_, volume_xyz_, mode='bilinear', padding_mode='zeros', align_corners=True) # B*TN,C,D,H,W v_embed_ = v_embed[torch.arange(B)[:,None], target_indices.view(B,TN)].view(B*TN, -1) # B*TN t_embed_ = t_embed.unsqueeze(1).repeat(1,TN,1).view(B*TN,-1) volume_feats_dict = self.frustum_volume_feats(volume_feats, t_embed_, v_embed_) return volume_feats_dict, volume_depth class SyncMultiviewDiffusion(pl.LightningModule): def __init__(self, unet_config, scheduler_config, finetune_unet=False, finetune_projection=True, view_num=16, image_size=256, cfg_scale=3.0, output_num=8, batch_view_num=4, drop_conditions=False, drop_scheme='default', clip_image_encoder_path="/apdcephfs/private_rondyliu/projects/clip/ViT-L-14.pt", sample_type='ddim', sample_steps=200): super().__init__() self.finetune_unet = finetune_unet self.finetune_projection = finetune_projection self.view_num = view_num self.viewpoint_dim = 4 self.output_num = output_num self.image_size = image_size self.batch_view_num = batch_view_num self.cfg_scale = cfg_scale self.clip_image_encoder_path = clip_image_encoder_path self._init_time_step_embedding() self._init_first_stage() self._init_schedule() self._init_multiview() self._init_clip_image_encoder() self._init_clip_projection() self.spatial_volume = SpatialVolumeNet(self.time_embed_dim, self.viewpoint_dim, self.view_num) self.model = UNetWrapper(unet_config, drop_conditions=drop_conditions, drop_scheme=drop_scheme) self.scheduler_config = scheduler_config latent_size = image_size//8 if sample_type=='ddim': self.sampler = SyncDDIMSampler(self, sample_steps , "uniform", 1.0, latent_size=latent_size) else: raise NotImplementedError def _init_clip_projection(self): self.cc_projection = nn.Linear(772, 768) nn.init.eye_(list(self.cc_projection.parameters())[0][:768, :768]) nn.init.zeros_(list(self.cc_projection.parameters())[1]) self.cc_projection.requires_grad_(True) if not self.finetune_projection: disable_training_module(self.cc_projection) def _init_multiview(self): K, azs, _, _, poses = read_pickle(f'meta_info/camera-{self.view_num}.pkl') default_image_size = 256 ratio = self.image_size/default_image_size K = np.diag([ratio,ratio,1]) @ K K = torch.from_numpy(K.astype(np.float32)) # [3,3] K = K.unsqueeze(0).repeat(self.view_num,1,1) # N,3,3 poses = torch.from_numpy(poses.astype(np.float32)) # N,3,4 self.register_buffer('poses', poses) self.register_buffer('Ks', K) azs = (azs + np.pi) % (np.pi * 2) - np.pi # scale to [-pi,pi] and the index=0 has az=0 self.register_buffer('azimuth', torch.from_numpy(azs.astype(np.float32))) def get_viewpoint_embedding(self, batch_size, elevation_ref): """ @param batch_size: @param elevation_ref: B @return: """ azimuth_input = self.azimuth[0].unsqueeze(0) # 1 azimuth_target = self.azimuth # N elevation_input = -elevation_ref # note that zero123 use a negative elevation here!!! elevation_target = -np.deg2rad(30) d_e = elevation_target - elevation_input # B N = self.azimuth.shape[0] B = batch_size d_e = d_e.unsqueeze(1).repeat(1, N) d_a = azimuth_target - azimuth_input # N d_a = d_a.unsqueeze(0).repeat(B, 1) d_z = torch.zeros_like(d_a) embedding = torch.stack([d_e, torch.sin(d_a), torch.cos(d_a), d_z], -1) # B,N,4 return embedding def _init_first_stage(self): first_stage_config={ "target": "ldm.models.autoencoder.AutoencoderKL", "params": { "embed_dim": 4, "monitor": "val/rec_loss", "ddconfig":{ "double_z": True, "z_channels": 4, "resolution": self.image_size, "in_channels": 3, "out_ch": 3, "ch": 128, "ch_mult": [1,2,4,4], "num_res_blocks": 2, "attn_resolutions": [], "dropout": 0.0 }, "lossconfig": {"target": "torch.nn.Identity"}, } } self.first_stage_scale_factor = 0.18215 self.first_stage_model = instantiate_from_config(first_stage_config) self.first_stage_model = disable_training_module(self.first_stage_model) def _init_clip_image_encoder(self):
self.clip_image_encoder = FrozenCLIPImageEmbedder(model=self.clip_image_encoder_path)
9
2023-12-21 04:44:00+00:00
12k
OPPOMKLab/u-LLaVA
models/segment_anything/automatic_mask_generator.py
[ { "identifier": "Sam", "path": "models/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...
from typing import Any, Dict, List, Optional, Tuple from torchvision.ops.boxes import batched_nms, box_area # type: ignore 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 import numpy as np import torch import cv2 # type: ignore # noqa: F401
10,173
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]
# 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(
10
2023-12-21 08:10:23+00:00
12k
chinhsuanwu/ifusion
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, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities 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 ( 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 ldm.modules.attention import CrossAttention
10,343
""" 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_target", 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.0, v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1.0, conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0.0, make_it_fit=False, ucg_training=None, ): 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)
""" 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_target", 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.0, v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1.0, conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0.0, make_it_fit=False, ucg_training=None, ): 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)
6
2023-12-17 12:45:38+00:00
12k
wangzhecheng/SkyScript
test_zero_shot_classification.py
[ { "identifier": "get_cast_dtype", "path": "src/open_clip/model.py", "snippet": "def get_cast_dtype(precision: str):\n cast_dtype = None\n if precision == 'bf16':\n cast_dtype = torch.bfloat16\n elif precision == 'fp16':\n cast_dtype = torch.float16\n return cast_dtype" }, {...
import torch import numpy as np import os import sys import pandas as pd import pickle import matplotlib.pyplot as plt import torch.nn.functional as F import random from PIL import Image from os.path import join, exists from tqdm import tqdm from torch.utils.data import Dataset, DataLoader from src.open_clip.model import get_cast_dtype, trace_model from src.open_clip.factory import create_model_and_transforms from src.training.zero_shot import zero_shot_classifier from src.training.logger import setup_logging from src.training.distributed import is_master, init_distributed_device, broadcast_object from src.training.precision import get_autocast from params import parse_args from prompt_templates import template_dict from benchmark_dataset_info import BENCHMARK_DATASET_INFOMATION
7,681
Image.MAX_IMAGE_PIXELS = 1000000000 def random_seed(seed=42, rank=0): torch.manual_seed(seed + rank) np.random.seed(seed + rank) random.seed(seed + rank) class CsvDatasetForClassification(Dataset): """Dataset for multiclass classification""" def __init__(self, input_filename, transforms, img_key, label_key, classnames, sep="\t", debugging=False, root_data_dir=None): # logging.debug(f'Loading csv data from {input_filename}.') df = pd.read_csv(input_filename, sep=sep) df = df[df[label_key].isnull() == False] if root_data_dir is not None: df[img_key] = df[img_key].apply(lambda x: join(root_data_dir, x)) self.images = df[img_key].tolist() self.labels = df[label_key].tolist() self.transforms = transforms self.debugging = debugging # mapping classname to class index if type(self.labels[0]) == str: self.label2idx = {x: i for i, x in enumerate(classnames)} self.label_indices = [self.label2idx[x] for x in self.labels] else: self.idx2label = {i: x for i, x in enumerate(classnames)} self.label_indices = self.labels # logging.debug('Done loading data.') def __len__(self): return len(self.label_indices) def __getitem__(self, idx): images = self.transforms(Image.open(str(self.images[idx]))) if self.debugging: return images, self.label_indices[idx], self.images[idx] else: return images, self.label_indices[idx] class CsvDatasetForClassificationBinary(Dataset): """Dataset for binary classification""" def __init__(self, input_filename, transforms, img_key, label_key, actual_label_key, classnames, sep="\t", debugging=False, root_data_dir=None): # logging.debug(f'Loading csv data from {input_filename}.') df = pd.read_csv(input_filename, sep=sep) df = df[df[label_key].isnull() == False] if root_data_dir is not None: df[img_key] = df[img_key].apply(lambda x: join(root_data_dir, x)) self.images = df[img_key].tolist() self.labels = df[label_key].tolist() self.actual_labels = df[actual_label_key].tolist() self.transforms = transforms self.debugging = debugging def __len__(self): return len(self.labels) def __getitem__(self, idx): images = self.transforms(Image.open(str(self.images[idx]))) if self.debugging: return images, self.actual_labels[idx], self.images[idx] else: return images, self.actual_labels[idx] def test_zero_shot_classification(model, dataloader, label_list, is_binary, args, dataset_name='unnamed', debugging=False): # logging.info('Starting zero-shot classification test.') templates = template_dict[dataset_name] model.eval() classifier = zero_shot_classifier(model, label_list, templates, args) # [dim_embedding, N_class] if is_binary: results = run_binary(model, classifier, dataloader, args, dataset_name=dataset_name, debugging=debugging) else: results = run(model, classifier, dataloader, args, dataset_name=dataset_name, debugging=debugging) return results def accuracy(output, target, topk=(1,)): pred = output.topk(max(topk), 1, True, True)[1].t() correct = pred.eq(target.view(1, -1).expand_as(pred)) return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk] def run(model, classifier, dataloader, args, dataset_name='unnamed', debugging=False):
Image.MAX_IMAGE_PIXELS = 1000000000 def random_seed(seed=42, rank=0): torch.manual_seed(seed + rank) np.random.seed(seed + rank) random.seed(seed + rank) class CsvDatasetForClassification(Dataset): """Dataset for multiclass classification""" def __init__(self, input_filename, transforms, img_key, label_key, classnames, sep="\t", debugging=False, root_data_dir=None): # logging.debug(f'Loading csv data from {input_filename}.') df = pd.read_csv(input_filename, sep=sep) df = df[df[label_key].isnull() == False] if root_data_dir is not None: df[img_key] = df[img_key].apply(lambda x: join(root_data_dir, x)) self.images = df[img_key].tolist() self.labels = df[label_key].tolist() self.transforms = transforms self.debugging = debugging # mapping classname to class index if type(self.labels[0]) == str: self.label2idx = {x: i for i, x in enumerate(classnames)} self.label_indices = [self.label2idx[x] for x in self.labels] else: self.idx2label = {i: x for i, x in enumerate(classnames)} self.label_indices = self.labels # logging.debug('Done loading data.') def __len__(self): return len(self.label_indices) def __getitem__(self, idx): images = self.transforms(Image.open(str(self.images[idx]))) if self.debugging: return images, self.label_indices[idx], self.images[idx] else: return images, self.label_indices[idx] class CsvDatasetForClassificationBinary(Dataset): """Dataset for binary classification""" def __init__(self, input_filename, transforms, img_key, label_key, actual_label_key, classnames, sep="\t", debugging=False, root_data_dir=None): # logging.debug(f'Loading csv data from {input_filename}.') df = pd.read_csv(input_filename, sep=sep) df = df[df[label_key].isnull() == False] if root_data_dir is not None: df[img_key] = df[img_key].apply(lambda x: join(root_data_dir, x)) self.images = df[img_key].tolist() self.labels = df[label_key].tolist() self.actual_labels = df[actual_label_key].tolist() self.transforms = transforms self.debugging = debugging def __len__(self): return len(self.labels) def __getitem__(self, idx): images = self.transforms(Image.open(str(self.images[idx]))) if self.debugging: return images, self.actual_labels[idx], self.images[idx] else: return images, self.actual_labels[idx] def test_zero_shot_classification(model, dataloader, label_list, is_binary, args, dataset_name='unnamed', debugging=False): # logging.info('Starting zero-shot classification test.') templates = template_dict[dataset_name] model.eval() classifier = zero_shot_classifier(model, label_list, templates, args) # [dim_embedding, N_class] if is_binary: results = run_binary(model, classifier, dataloader, args, dataset_name=dataset_name, debugging=debugging) else: results = run(model, classifier, dataloader, args, dataset_name=dataset_name, debugging=debugging) return results def accuracy(output, target, topk=(1,)): pred = output.topk(max(topk), 1, True, True)[1].t() correct = pred.eq(target.view(1, -1).expand_as(pred)) return [float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy()) for k in topk] def run(model, classifier, dataloader, args, dataset_name='unnamed', debugging=False):
autocast = get_autocast(args.precision)
8
2023-12-19 11:50:56+00:00
12k
Lavreniuk/EVP
depth/models_depth/model.py
[ { "identifier": "UNetWrapper", "path": "evp/models.py", "snippet": "class UNetWrapper(nn.Module):\n def __init__(self, unet, use_attn=True, base_size=512, max_attn_size=None, attn_selector='up_cross+down_cross') -> None:\n super().__init__()\n self.unet = unet\n self.attention_st...
import torch import torch.nn as nn import torch.nn.functional as F import os from timm.models.layers import trunc_normal_, DropPath from mmcv.cnn import (build_conv_layer, build_norm_layer, build_upsample_layer, constant_init, normal_init) from omegaconf import OmegaConf from ldm.util import instantiate_from_config from evp.models import UNetWrapper, TextAdapterRefer, FrozenCLIPEmbedder from .miniViT import mViT from .attractor import AttractorLayer, AttractorLayerUnnormed from .dist_layers import ConditionalLogBinomial from .localbins_layers import (Projector, SeedBinRegressor, SeedBinRegressorUnnormed)
7,819
if dataset == 'kitti': self.unet = UNetWrapper(sd_model.model, use_attn=True, base_size=384) del sd_model.cond_stage_model del self.encoder_vq.decoder del self.unet.unet.diffusion_model.out del self.encoder_vq.post_quant_conv.weight del self.encoder_vq.post_quant_conv.bias for param in self.encoder_vq.parameters(): param.requires_grad = True self.text_adapter = TextAdapterRefer(text_dim=text_dim) self.gamma = nn.Parameter(torch.ones(text_dim) * 1e-4) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if caption_aggregation: class_embeddings = torch.load(f'{dataset}_class_embeddings_my_captions.pth', map_location=device) #class_embeddings_list = [value['class_embeddings'] for key, value in class_embeddings.items()] #stacked_embeddings = torch.stack(class_embeddings_list, dim=0) #class_embeddings = torch.mean(stacked_embeddings, dim=0).unsqueeze(0) if 'aggregated' in class_embeddings: class_embeddings = class_embeddings['aggregated'] else: clip_model = FrozenCLIPEmbedder(max_length=40,pool=False).to(device) class_embeddings_new = [clip_model.encode(value['caption'][0]) for key, value in class_embeddings.items()] class_embeddings_new = torch.mean(torch.stack(class_embeddings_new, dim=0), dim=0) class_embeddings['aggregated'] = class_embeddings_new torch.save(class_embeddings, f'{dataset}_class_embeddings_my_captions.pth') class_embeddings = class_embeddings['aggregated'] self.register_buffer('class_embeddings', class_embeddings) else: self.class_embeddings = torch.load(f'{dataset}_class_embeddings_my_captions.pth', map_location=device) self.clip_model = FrozenCLIPEmbedder(max_length=40,pool=False) for param in self.clip_model.parameters(): param.requires_grad = True #if dataset == 'kitti': # self.text_adapter_ = TextAdapterRefer(text_dim=text_dim) # self.gamma_ = nn.Parameter(torch.ones(text_dim) * 1e-4) self.caption_aggregation = caption_aggregation self.dataset = dataset def _init_weights(self, m): if isinstance(m, (nn.Conv2d, nn.Linear)): trunc_normal_(m.weight, std=.02) nn.init.constant_(m.bias, 0) def forward_features(self, feats): x = self.ldm_to_net[0](feats[0]) for i in range(3): if i > 0: x = x + self.ldm_to_net[i](feats[i]) x = self.layers[i](x) x = self.upsample_layers[i](x) return self.out_conv(x) def forward(self, x, class_ids=None, img_paths=None): latents = self.encoder_vq.encode(x).mode() # add division by std if self.dataset == 'nyu': latents = latents / 5.07543 elif self.dataset == 'kitti': latents = latents / 4.6211 else: print('Please calculate the STD for the dataset!') if class_ids is not None: if self.caption_aggregation: class_embeddings = self.class_embeddings[[0]*len(class_ids.tolist())]#[class_ids.tolist()] else: class_embeddings = [] for img_path in img_paths: class_embeddings.extend([value['caption'][0] for key, value in self.class_embeddings.items() if key in img_path.replace('//', '/')]) class_embeddings = self.clip_model.encode(class_embeddings) else: class_embeddings = self.class_embeddings c_crossattn = self.text_adapter(latents, class_embeddings, self.gamma) t = torch.ones((x.shape[0],), device=x.device).long() #if self.dataset == 'kitti': # c_crossattn_last = self.text_adapter_(latents, class_embeddings, self.gamma_) # outs = self.unet(latents, t, c_crossattn=[c_crossattn, c_crossattn_last]) #else: outs = self.unet(latents, t, c_crossattn=[c_crossattn]) outs = self.aggregation(outs) feats = [outs[0], outs[1], torch.cat([outs[2], F.interpolate(outs[3], scale_factor=2)], dim=1)] x = torch.cat([self.layer1(feats[0]), self.layer2(feats[1]), feats[2]], dim=1) return self.out_layer(x) def get_latent(self, x): return self.encoder_vq.encode(x).mode() class EVPDepth(nn.Module): def __init__(self, args=None, caption_aggregation=False): super().__init__() self.max_depth = args.max_depth self.min_depth = args.min_depth_eval embed_dim = 192 channels_in = embed_dim*8 channels_out = embed_dim if args.dataset == 'nyudepthv2': self.encoder = EVPDepthEncoder(out_dim=channels_in, dataset='nyu', caption_aggregation=caption_aggregation) else: self.encoder = EVPDepthEncoder(out_dim=channels_in, dataset='kitti', caption_aggregation=caption_aggregation) self.decoder = Decoder(channels_in, channels_out, args) self.decoder.init_weights()
# ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # The deconvolution code is based on Simple Baseline. # (https://github.com/microsoft/human-pose-estimation.pytorch/blob/master/lib/models/pose_resnet.py) # Modified by Zigang Geng (zigang@mail.ustc.edu.cn). # ------------------------------------------------------------------------------ def icnr(x, scale=2, init=nn.init.kaiming_normal_): """ Checkerboard artifact free sub-pixel convolution https://arxiv.org/abs/1707.02937 """ ni,nf,h,w = x.shape ni2 = int(ni/(scale**2)) k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1) k = k.contiguous().view(ni2, nf, -1) k = k.repeat(1, 1, scale**2) k = k.contiguous().view([nf,ni,h,w]).transpose(0, 1) x.data.copy_(k) class PixelShuffle(nn.Module): """ Real-Time Single Image and Video Super-Resolution https://arxiv.org/abs/1609.05158 """ def __init__(self, n_channels, scale): super(PixelShuffle, self).__init__() self.conv = nn.Conv2d(n_channels, n_channels*(scale**2), kernel_size=1) icnr(self.conv.weight) self.shuf = nn.PixelShuffle(scale) self.relu = nn.ReLU() def forward(self,x): x = self.shuf(self.relu(self.conv(x))) return x class AttentionModule(nn.Module): def __init__(self, in_channels, out_channels): super(AttentionModule, self).__init__() # Convolutional Layers self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) # Group Normalization self.group_norm = nn.GroupNorm(20, out_channels) # ReLU Activation self.relu = nn.ReLU() # Spatial Attention self.spatial_attention = nn.Sequential( nn.Conv2d(in_channels, 1, kernel_size=1), nn.Sigmoid() ) def forward(self, x): # Apply spatial attention spatial_attention = self.spatial_attention(x) x = x * spatial_attention # Apply convolutional layer x = self.conv1(x) x = self.group_norm(x) x = self.relu(x) return x class AttentionDownsamplingModule(nn.Module): def __init__(self, in_channels, out_channels, scale_factor=2): super(AttentionDownsamplingModule, self).__init__() # Spatial Attention self.spatial_attention = nn.Sequential( nn.Conv2d(in_channels, 1, kernel_size=1), nn.Sigmoid() ) # Channel Attention self.channel_attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels, in_channels // 8, kernel_size=1), nn.ReLU(inplace=True), nn.Conv2d(in_channels // 8, in_channels, kernel_size=1), nn.Sigmoid() ) # Convolutional Layers if scale_factor == 2: self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) elif scale_factor == 4: self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=2, padding=1) # Group Normalization self.group_norm = nn.GroupNorm(20, out_channels) # ReLU Activation self.relu = nn.ReLU(inplace=True) def forward(self, x): # Apply spatial attention spatial_attention = self.spatial_attention(x) x = x * spatial_attention # Apply channel attention channel_attention = self.channel_attention(x) x = x * channel_attention # Apply convolutional layers x = self.conv1(x) x = self.group_norm(x) x = self.relu(x) x = self.conv2(x) x = self.group_norm(x) x = self.relu(x) return x class AttentionUpsamplingModule(nn.Module): def __init__(self, in_channels, out_channels): super(AttentionUpsamplingModule, self).__init__() # Spatial Attention for outs[2] self.spatial_attention = nn.Sequential( nn.Conv2d(in_channels, 1, kernel_size=1), nn.Sigmoid() ) # Channel Attention for outs[2] self.channel_attention = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels, in_channels // 8, kernel_size=1), nn.ReLU(), nn.Conv2d(in_channels // 8, in_channels, kernel_size=1), nn.Sigmoid() ) self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1) # Group Normalization self.group_norm = nn.GroupNorm(20, out_channels) # ReLU Activation self.relu = nn.ReLU() self.upscale = PixelShuffle(in_channels, 2) def forward(self, x): # Apply spatial attention spatial_attention = self.spatial_attention(x) x = x * spatial_attention # Apply channel attention channel_attention = self.channel_attention(x) x = x * channel_attention # Apply convolutional layers x = self.conv1(x) x = self.group_norm(x) x = self.relu(x) x = self.conv2(x) x = self.group_norm(x) x = self.relu(x) # Upsample x = self.upscale(x) return x class ConvLayer(nn.Module): def __init__(self, in_channels, out_channels): super(ConvLayer, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(in_channels, out_channels, 1), nn.GroupNorm(20, out_channels), nn.ReLU(), ) def forward(self, x): x = self.conv1(x) return x class InverseMultiAttentiveFeatureRefinement(nn.Module): def __init__(self, in_channels_list): super(InverseMultiAttentiveFeatureRefinement, self).__init__() self.layer1 = AttentionModule(in_channels_list[0], in_channels_list[0]) self.layer2 = AttentionDownsamplingModule(in_channels_list[0], in_channels_list[0]//2, scale_factor = 2) self.layer3 = ConvLayer(in_channels_list[0]//2 + in_channels_list[1], in_channels_list[1]) self.layer4 = AttentionDownsamplingModule(in_channels_list[1], in_channels_list[1]//2, scale_factor = 2) self.layer5 = ConvLayer(in_channels_list[1]//2 + in_channels_list[2], in_channels_list[2]) self.layer6 = AttentionDownsamplingModule(in_channels_list[2], in_channels_list[2]//2, scale_factor = 2) self.layer7 = ConvLayer(in_channels_list[2]//2 + in_channels_list[3], in_channels_list[3]) ''' self.layer8 = AttentionUpsamplingModule(in_channels_list[3], in_channels_list[3]) self.layer9 = ConvLayer(in_channels_list[2] + in_channels_list[3], in_channels_list[2]) self.layer10 = AttentionUpsamplingModule(in_channels_list[2], in_channels_list[2]) self.layer11 = ConvLayer(in_channels_list[1] + in_channels_list[2], in_channels_list[1]) self.layer12 = AttentionUpsamplingModule(in_channels_list[1], in_channels_list[1]) self.layer13 = ConvLayer(in_channels_list[0] + in_channels_list[1], in_channels_list[0]) ''' def forward(self, inputs): x_c4, x_c3, x_c2, x_c1 = inputs x_c4 = self.layer1(x_c4) x_c4_3 = self.layer2(x_c4) x_c3 = torch.cat([x_c4_3, x_c3], dim=1) x_c3 = self.layer3(x_c3) x_c3_2 = self.layer4(x_c3) x_c2 = torch.cat([x_c3_2, x_c2], dim=1) x_c2 = self.layer5(x_c2) x_c2_1 = self.layer6(x_c2) x_c1 = torch.cat([x_c2_1, x_c1], dim=1) x_c1 = self.layer7(x_c1) ''' x_c1_2 = self.layer8(x_c1) x_c2 = torch.cat([x_c1_2, x_c2], dim=1) x_c2 = self.layer9(x_c2) x_c2_3 = self.layer10(x_c2) x_c3 = torch.cat([x_c2_3, x_c3], dim=1) x_c3 = self.layer11(x_c3) x_c3_4 = self.layer12(x_c3) x_c4 = torch.cat([x_c3_4, x_c4], dim=1) x_c4 = self.layer13(x_c4) ''' return [x_c4, x_c3, x_c2, x_c1] class EVPDepthEncoder(nn.Module): def __init__(self, out_dim=1024, ldm_prior=[320, 680, 1320+1280], sd_path=None, text_dim=768, dataset='nyu', caption_aggregation=False ): super().__init__() self.layer1 = nn.Sequential( nn.Conv2d(ldm_prior[0], ldm_prior[0], 3, stride=2, padding=1), nn.GroupNorm(16, ldm_prior[0]), nn.ReLU(), nn.Conv2d(ldm_prior[0], ldm_prior[0], 3, stride=2, padding=1), ) self.layer2 = nn.Sequential( nn.Conv2d(ldm_prior[1], ldm_prior[1], 3, stride=2, padding=1), ) self.out_layer = nn.Sequential( nn.Conv2d(sum(ldm_prior), out_dim, 1), nn.GroupNorm(16, out_dim), nn.ReLU(), ) self.aggregation = InverseMultiAttentiveFeatureRefinement([320, 680, 1320, 1280]) self.apply(self._init_weights) ### stable diffusion layers config = OmegaConf.load('./v1-inference.yaml') if sd_path is None: if os.path.exists('../checkpoints/v1-5-pruned-emaonly.ckpt'): config.model.params.ckpt_path = '../checkpoints/v1-5-pruned-emaonly.ckpt' else: config.model.params.ckpt_path = None else: config.model.params.ckpt_path = f'../{sd_path}' sd_model = instantiate_from_config(config.model) self.encoder_vq = sd_model.first_stage_model self.unet = UNetWrapper(sd_model.model, use_attn=True) if dataset == 'kitti': self.unet = UNetWrapper(sd_model.model, use_attn=True, base_size=384) del sd_model.cond_stage_model del self.encoder_vq.decoder del self.unet.unet.diffusion_model.out del self.encoder_vq.post_quant_conv.weight del self.encoder_vq.post_quant_conv.bias for param in self.encoder_vq.parameters(): param.requires_grad = True self.text_adapter = TextAdapterRefer(text_dim=text_dim) self.gamma = nn.Parameter(torch.ones(text_dim) * 1e-4) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if caption_aggregation: class_embeddings = torch.load(f'{dataset}_class_embeddings_my_captions.pth', map_location=device) #class_embeddings_list = [value['class_embeddings'] for key, value in class_embeddings.items()] #stacked_embeddings = torch.stack(class_embeddings_list, dim=0) #class_embeddings = torch.mean(stacked_embeddings, dim=0).unsqueeze(0) if 'aggregated' in class_embeddings: class_embeddings = class_embeddings['aggregated'] else: clip_model = FrozenCLIPEmbedder(max_length=40,pool=False).to(device) class_embeddings_new = [clip_model.encode(value['caption'][0]) for key, value in class_embeddings.items()] class_embeddings_new = torch.mean(torch.stack(class_embeddings_new, dim=0), dim=0) class_embeddings['aggregated'] = class_embeddings_new torch.save(class_embeddings, f'{dataset}_class_embeddings_my_captions.pth') class_embeddings = class_embeddings['aggregated'] self.register_buffer('class_embeddings', class_embeddings) else: self.class_embeddings = torch.load(f'{dataset}_class_embeddings_my_captions.pth', map_location=device) self.clip_model = FrozenCLIPEmbedder(max_length=40,pool=False) for param in self.clip_model.parameters(): param.requires_grad = True #if dataset == 'kitti': # self.text_adapter_ = TextAdapterRefer(text_dim=text_dim) # self.gamma_ = nn.Parameter(torch.ones(text_dim) * 1e-4) self.caption_aggregation = caption_aggregation self.dataset = dataset def _init_weights(self, m): if isinstance(m, (nn.Conv2d, nn.Linear)): trunc_normal_(m.weight, std=.02) nn.init.constant_(m.bias, 0) def forward_features(self, feats): x = self.ldm_to_net[0](feats[0]) for i in range(3): if i > 0: x = x + self.ldm_to_net[i](feats[i]) x = self.layers[i](x) x = self.upsample_layers[i](x) return self.out_conv(x) def forward(self, x, class_ids=None, img_paths=None): latents = self.encoder_vq.encode(x).mode() # add division by std if self.dataset == 'nyu': latents = latents / 5.07543 elif self.dataset == 'kitti': latents = latents / 4.6211 else: print('Please calculate the STD for the dataset!') if class_ids is not None: if self.caption_aggregation: class_embeddings = self.class_embeddings[[0]*len(class_ids.tolist())]#[class_ids.tolist()] else: class_embeddings = [] for img_path in img_paths: class_embeddings.extend([value['caption'][0] for key, value in self.class_embeddings.items() if key in img_path.replace('//', '/')]) class_embeddings = self.clip_model.encode(class_embeddings) else: class_embeddings = self.class_embeddings c_crossattn = self.text_adapter(latents, class_embeddings, self.gamma) t = torch.ones((x.shape[0],), device=x.device).long() #if self.dataset == 'kitti': # c_crossattn_last = self.text_adapter_(latents, class_embeddings, self.gamma_) # outs = self.unet(latents, t, c_crossattn=[c_crossattn, c_crossattn_last]) #else: outs = self.unet(latents, t, c_crossattn=[c_crossattn]) outs = self.aggregation(outs) feats = [outs[0], outs[1], torch.cat([outs[2], F.interpolate(outs[3], scale_factor=2)], dim=1)] x = torch.cat([self.layer1(feats[0]), self.layer2(feats[1]), feats[2]], dim=1) return self.out_layer(x) def get_latent(self, x): return self.encoder_vq.encode(x).mode() class EVPDepth(nn.Module): def __init__(self, args=None, caption_aggregation=False): super().__init__() self.max_depth = args.max_depth self.min_depth = args.min_depth_eval embed_dim = 192 channels_in = embed_dim*8 channels_out = embed_dim if args.dataset == 'nyudepthv2': self.encoder = EVPDepthEncoder(out_dim=channels_in, dataset='nyu', caption_aggregation=caption_aggregation) else: self.encoder = EVPDepthEncoder(out_dim=channels_in, dataset='kitti', caption_aggregation=caption_aggregation) self.decoder = Decoder(channels_in, channels_out, args) self.decoder.init_weights()
self.mViT = False
3
2023-12-15 14:13:59+00:00
12k
penghao-wu/vstar
VisualSearch/model/VSM.py
[ { "identifier": "LlavaLlamaForCausalLM", "path": "VisualSearch/model/llava/model/language_model/llava_llama.py", "snippet": "class LlavaLlamaForCausalLM(LlamaForCausalLM, LlavaMetaForCausalLM):\n config_class = LlavaConfig\n\n def __init__(self, config):\n super(LlamaForCausalLM, self).__in...
from typing import List from VisualSearch.model.llava.model.language_model.llava_llama import (LlavaLlamaForCausalLM, LlavaLlamaModel) from .segment_anything.modeling import PromptEncoder, MaskDecoder, TwoWayTransformer from .owlvit.owlvit import OwlViT import torch import torch.nn as nn import torch.nn.functional as F
8,069
num_masks: float, ): """ Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). Returns: Loss tensor """ loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") loss = loss.flatten(1, 2).mean(1) / (num_masks + 1e-8) return loss class VSMMetaModel: def __init__( self, config, **kwargs, ): super(VSMMetaModel, self).__init__(config) self.config = config if not hasattr(self.config, "train_mask_decoder"): self.config.train_mask_decoder = kwargs["train_mask_decoder"] self.config.out_dim = kwargs["out_dim"] else: is_eval = kwargs.get('is_eval', False) self.initialize_lisa_modules(self.config, is_eval) def initialize_lisa_modules(self, config, is_eval=False): # OWL-ViT self.owlvit = OwlViT(1, is_eval) self.owlvit.train() for param in self.owlvit.parameters(): param.requires_grad = True for param in self.owlvit.vision_model.parameters(): param.requires_grad = False self.owlvit.vision_model.eval() for param in self.owlvit.box_head.parameters(): param.requires_grad = False self.visual_projection = nn.Linear(self.owlvit.vision_model.config.hidden_size, 256, bias=False) for param in self.visual_projection.parameters(): param.requires_grad = True self.prompt_encoder=PromptEncoder( embed_dim=256, image_embedding_size=(48, 48), input_image_size=(768, 768), mask_in_chans=16, ) self.prompt_encoder.train() for param in self.prompt_encoder.parameters(): param.requires_grad = True self.mask_decoder=MaskDecoder( num_multimask_outputs=3, transformer=TwoWayTransformer( depth=2, embedding_dim=256, mlp_dim=2048, num_heads=8, ), transformer_dim=256, iou_head_depth=3, iou_head_hidden_dim=256, ) self.mask_decoder.train() for param in self.mask_decoder.parameters(): param.requires_grad = True # Projection layer in_dim = config.hidden_size out_dim = config.out_dim text_fc_det = [ nn.Linear(in_dim, in_dim), nn.ReLU(inplace=True), nn.Linear(in_dim, out_dim), nn.Dropout(0.0), ] self.text_hidden_fcs_det = nn.ModuleList([nn.Sequential(*text_fc_det)]) self.text_hidden_fcs_det.train() for param in self.text_hidden_fcs_det.parameters(): param.requires_grad = True text_fc_seg = [ nn.Linear(in_dim, in_dim), nn.ReLU(inplace=True), nn.Linear(in_dim, 256), nn.Dropout(0.0), ] self.text_hidden_fcs_seg = nn.ModuleList([nn.Sequential(*text_fc_seg)]) self.text_hidden_fcs_seg.train() for param in self.text_hidden_fcs_seg.parameters(): param.requires_grad = True class VSMModel(VSMMetaModel, LlavaLlamaModel): def __init__( self, config, **kwargs, ): super(VSMModel, self).__init__(config, **kwargs) self.config.use_cache = False self.config.vision_tower = self.config.mm_vision_tower self.config.mm_vision_select_feature = "patch" self.config.image_aspect_ratio = "square" self.config.image_grid_pinpoints = None self.config.tune_mm_mlp_adapter = False self.config.freeze_mm_mlp_adapter = True self.config.pretrain_mm_mlp_adapter = None self.config.mm_use_im_patch_token = False
def dice_loss( inputs: torch.Tensor, targets: torch.Tensor, num_masks: float, scale=1000, # 100000.0, eps=1e-6, ): """ Compute the DICE loss, similar to generalized IOU for masks Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). """ inputs = inputs.sigmoid() inputs = inputs.flatten(1, 2) targets = targets.flatten(1, 2) numerator = 2 * (inputs / scale * targets).sum(-1) denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1) loss = 1 - (numerator + eps) / (denominator + eps) loss = loss / (num_masks + 1e-8) return loss def sigmoid_ce_loss( inputs: torch.Tensor, targets: torch.Tensor, num_masks: float, ): """ Args: inputs: A float tensor of arbitrary shape. The predictions for each example. targets: A float tensor with the same shape as inputs. Stores the binary classification label for each element in inputs (0 for the negative class and 1 for the positive class). Returns: Loss tensor """ loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") loss = loss.flatten(1, 2).mean(1) / (num_masks + 1e-8) return loss class VSMMetaModel: def __init__( self, config, **kwargs, ): super(VSMMetaModel, self).__init__(config) self.config = config if not hasattr(self.config, "train_mask_decoder"): self.config.train_mask_decoder = kwargs["train_mask_decoder"] self.config.out_dim = kwargs["out_dim"] else: is_eval = kwargs.get('is_eval', False) self.initialize_lisa_modules(self.config, is_eval) def initialize_lisa_modules(self, config, is_eval=False): # OWL-ViT self.owlvit = OwlViT(1, is_eval) self.owlvit.train() for param in self.owlvit.parameters(): param.requires_grad = True for param in self.owlvit.vision_model.parameters(): param.requires_grad = False self.owlvit.vision_model.eval() for param in self.owlvit.box_head.parameters(): param.requires_grad = False self.visual_projection = nn.Linear(self.owlvit.vision_model.config.hidden_size, 256, bias=False) for param in self.visual_projection.parameters(): param.requires_grad = True self.prompt_encoder=PromptEncoder( embed_dim=256, image_embedding_size=(48, 48), input_image_size=(768, 768), mask_in_chans=16, ) self.prompt_encoder.train() for param in self.prompt_encoder.parameters(): param.requires_grad = True self.mask_decoder=MaskDecoder( num_multimask_outputs=3, transformer=TwoWayTransformer( depth=2, embedding_dim=256, mlp_dim=2048, num_heads=8, ), transformer_dim=256, iou_head_depth=3, iou_head_hidden_dim=256, ) self.mask_decoder.train() for param in self.mask_decoder.parameters(): param.requires_grad = True # Projection layer in_dim = config.hidden_size out_dim = config.out_dim text_fc_det = [ nn.Linear(in_dim, in_dim), nn.ReLU(inplace=True), nn.Linear(in_dim, out_dim), nn.Dropout(0.0), ] self.text_hidden_fcs_det = nn.ModuleList([nn.Sequential(*text_fc_det)]) self.text_hidden_fcs_det.train() for param in self.text_hidden_fcs_det.parameters(): param.requires_grad = True text_fc_seg = [ nn.Linear(in_dim, in_dim), nn.ReLU(inplace=True), nn.Linear(in_dim, 256), nn.Dropout(0.0), ] self.text_hidden_fcs_seg = nn.ModuleList([nn.Sequential(*text_fc_seg)]) self.text_hidden_fcs_seg.train() for param in self.text_hidden_fcs_seg.parameters(): param.requires_grad = True class VSMModel(VSMMetaModel, LlavaLlamaModel): def __init__( self, config, **kwargs, ): super(VSMModel, self).__init__(config, **kwargs) self.config.use_cache = False self.config.vision_tower = self.config.mm_vision_tower self.config.mm_vision_select_feature = "patch" self.config.image_aspect_ratio = "square" self.config.image_grid_pinpoints = None self.config.tune_mm_mlp_adapter = False self.config.freeze_mm_mlp_adapter = True self.config.pretrain_mm_mlp_adapter = None self.config.mm_use_im_patch_token = False
class VSMForCausalLM(LlavaLlamaForCausalLM):
0
2023-12-15 14:58:24+00:00
12k
worm128/AI-YinMei
text-generation-webui/extensions/Training_PRO/script.py
[ { "identifier": "FPSchedulerTrainer", "path": "text-generation-webui/extensions/Training_PRO/custom_scheduler.py", "snippet": "class FPSchedulerTrainer(transformers.Trainer):\n def __init__(self,neftune_noise_alpha:float = 0.0, model = None, *args, **kwargs):\n self.neftune_noise_alpha = neftu...
import os import json import math import random import shutil import sys import threading import time import traceback import gradio as gr import pandas as pd import torch import transformers import inspect from datetime import datetime from pathlib import Path from functools import partial from .custom_scheduler import FPSchedulerTrainer, FPNEFtuneTrainer from .matplotgraph import create_graph from .train_utils import get_available_loras_local, precise_cut, sliding_block_cut, download_file_from_url from datasets import Dataset, load_dataset from peft import ( LoraConfig, get_peft_model, prepare_model_for_kbit_training, set_peft_model_state_dict ) from peft.utils.other import \ TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING as model_to_lora_modules from transformers.models.auto.modeling_auto import ( MODEL_FOR_CAUSAL_LM_MAPPING_NAMES ) from modules import shared, utils from modules.ui import create_refresh_button from modules.evaluate import ( calculate_perplexity, generate_markdown_table, save_past_evaluations ) from modules.logging_colors import logger from modules.models import reload_model from modules.utils import natural_keys from typing import Callable, Optional, Tuple, ContextManager from alpaca_lora_4bit.monkeypatch.peft_tuners_lora_monkey_patch import ( replace_peft_model_with_int4_lora_model ) from alpaca_lora_4bit.autograd_4bit import Autograd4bitQuantLinear from alpaca_lora_4bit.models import Linear4bitLt
9,883
text_chunks = precise_cut(raw_text, precize_slicing_overlap, min_chars, False, cutoff_len, hard_cut_string,non_serialized_params['debug_slicer']) total_blocks = len(text_chunks) result = f"Text: ({raw_text_file}.txt) has {total_blocks} blocks (Block Size {cutoff_len} tokens)" del text_chunks else: if dataset in ['None', '']: yield "Select dataset or text file." return if format in ['None', '']: yield "Select format choice for dataset." return with open(clean_path('training/formats', f'{format}.json'), 'r', encoding='utf-8-sig') as formatFile: format_data: dict[str, str] = json.load(formatFile) def generate_prompt(data_point: dict[str, str]): for options, data in format_data.items(): if set(options.split(',')) == set(x[0] for x in data_point.items() if (type(x[1]) is str and len(x[1].strip()) > 0)): for key, val in data_point.items(): if type(val) is str: data = data.replace(f'%{key}%', val) return data raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(format_data.keys())}"') def tokenize_dummy(prompt): input_ids = shared.tokenizer.encode(prompt, truncation=True, max_length=cutoff_len) labels = [1] * len(input_ids) input_ids = torch.tensor(input_ids) return { "input_ids": input_ids, "labels": labels, "attention_mask": input_ids.ne(shared.tokenizer.pad_token_id), } def generate_and_tokenize_prompt(data_point): prompt = generate_prompt(data_point) return tokenize_dummy(prompt) logger.info("Loading JSON datasets...") data = load_dataset("json", data_files=clean_path('training/datasets', f'{dataset}.json')) data_keys = [] if data: if 'train' in data: # Check if the 'train' split exists in the dataset data_keys = list(data['train'][0].keys()) print("Data Keys:", data_keys) else: print("The dataset is empty.") train_data = data['train'].map(generate_and_tokenize_prompt, new_fingerprint='%030x' % random.randrange(16**30)) total_blocks = train_data.num_rows result = f"Dataset: ({dataset}.json) has {total_blocks} blocks @ length = {cutoff_len} tokens\n(Keys: {data_keys} - Format: {format}.json): " #for options, data in format_data.items(): # format_keys = options.split(',') # result += f"{format_keys}, " #result = result.rstrip() #result = result.rstrip(',') if total_blocks>0: number_ofSteps = int(math.ceil(total_blocks / micro_batch_size) * epochs) num_stepsPer_epoch = int(math.ceil(number_ofSteps/epochs)) min_warm = math.ceil(100 / grad_accumulation) warmup_steps_suggest = min(int(min_warm*grad_accumulation), int(math.ceil(number_ofSteps * 0.1))) warmup_steps_suggest = min(warmup_steps_suggest,num_stepsPer_epoch) save_each_n_min = int(math.ceil(number_ofSteps/10)) save_each_n_max = int(math.ceil(number_ofSteps/5)) gradient_accumulation_max = int(total_blocks)//micro_batch_size result += f"\n[Batch Size: {micro_batch_size}, Epochs: {epochs}, Gradient Accumulation: {grad_accumulation}]\n" result += f"Total number of steps: {number_ofSteps}\n" result += f"Steps per each Epoch: {num_stepsPer_epoch}\n" result += f"Suggestions:\n" result += f"Checkpoints: Save every {save_each_n_min} - {save_each_n_max} steps (Current: {int(save_steps)})\n" result += f"Warmup steps: {warmup_steps_suggest} (Current: {int(warmup_steps)})" if gradient_accumulation_max < grad_accumulation: result += f"\n\nWARNING: Gradient Accumulation {grad_accumulation} is too high: It should be below {gradient_accumulation_max}" yield result return check_dataset_btn.click(check_dataset, dataset_calc_params ,check_dataset_txt) # Evaluation events. For some reason, the interrupt event # doesn't work with the .then() syntax, so I write them one # by one in this ugly but functional way. ev = start_evaluation.click(calculate_perplexity, [models, evaluate_text_file, stride_length, max_length], evaluation_log, show_progress=False) start_evaluation.click(generate_markdown_table, None, evaluation_table, show_progress=False) start_current_evaluation.click(lambda: ['current model'], None, tmp) ev_cur = start_current_evaluation.click(calculate_perplexity, [tmp, evaluate_text_file, stride_length, max_length], evaluation_log, show_progress=False) start_current_evaluation.click(generate_markdown_table, None, evaluation_table, show_progress=False) stop_evaluation.click(None, None, None, cancels=[ev, ev_cur], queue=False) refresh_table.click(generate_markdown_table, None, evaluation_table, show_progress=True) save_comments.click( save_past_evaluations, evaluation_table, None).then( lambda: "Comments saved.", None, evaluation_log, show_progress=False) def reload_lora(): return gr.Dropdown.update(choices=get_available_loras_local(non_serialized_params['Lora_sortedByTime'])) # nonserialized items sort_byTime.change(lambda x: non_serialized_params.update({"Lora_sortedByTime": x}), sort_byTime, None).then(reload_lora,None,copy_from) #debug_slicer.change(lambda x: non_serialized_params.update({"debug_slicer": x}), debug_slicer, None) def update_dataset(): return gr.update(choices=get_datasets('training/datasets', 'json')), gr.update(choices=get_datasets('training/datasets', 'txt'))
os.environ["WANDB_MODE"] = "offline" # os.environ["WANDB_DISABLED"] = "true" ## just temporary to avoid warning if hasattr(torch.utils.checkpoint, 'noop_context_fn'): def my_checkpoint( function, *args, use_reentrant: Optional[bool] = None, context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = torch.utils.checkpoint.noop_context_fn, determinism_check: str = torch.utils.checkpoint._DEFAULT_DETERMINISM_MODE, debug: bool = False, **kwargs ): if use_reentrant is None: #print ("reentran = NONE") use_reentrant = True # Hack to mix *args with **kwargs in a python 2.7-compliant way preserve = kwargs.pop("preserve_rng_state", True) if kwargs and use_reentrant: raise ValueError( "Unexpected keyword arguments: " + ",".join(arg for arg in kwargs) ) if use_reentrant: if context_fn is not torch.utils.checkpoint.noop_context_fn or debug is not False: raise ValueError( "Passing `context_fn` or `debug` is only supported when " "use_reentrant=False." ) return torch.utils.checkpoint.CheckpointFunction.apply(function, preserve, *args) else: print ("reentran = FALSE") gen = torch.utils.checkpoint._checkpoint_without_reentrant_generator( function, preserve, context_fn, determinism_check, debug, *args, **kwargs ) # Runs pre-forward logic next(gen) ret = function(*args, **kwargs) # Runs post-forward logic try: next(gen) except StopIteration: return ret params = { "display_name": "Training PRO", "is_tab": True } non_serialized_params = { "debug_slicer": False, "Lora_sortedByTime": False, "stop_at_loss": 0, "save_steps_under_loss": 0.0, "save_checkpoint_now": False, "training_loop": False, "current_stability": 0, "save_epochs": 0, "checkpoint_offset": 0, "epoch_offset":0, } MODEL_CLASSES = {v[1]: v[0] for v in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.items()} PARAMETERS = ["lora_name", "always_override", "save_steps", "micro_batch_size", "batch_size", "epochs", "learning_rate", "lr_scheduler_type", "lora_rank", "lora_alpha", "lora_dropout", "cutoff_len", "dataset", "eval_dataset", "format", "eval_steps", "raw_text_file", "higher_rank_limit", "warmup_steps", "optimizer", "hard_cut_string", "train_only_after", "stop_at_loss", "add_eos_token", "min_chars", "report_to", "precize_slicing_overlap", "add_eos_token_type", "save_steps_under_loss", "add_bos_token", "training_projection","sliding_window","warmup_ratio","grad_accumulation","neft_noise_alpha"] WANT_INTERRUPT = False train_log = {} train_template = {} train_log_graph = [] train_choices = ["all","q-k-v-o","q-k-v","k-v-down","q-v"] statistics = { 'loss': [], 'lr': [], } RED = "\033[91m" YELLOW = "\033[93m" GREEN = "\033[92m" RESET = "\033[0m" def ui(): with gr.Tab('Train LoRA', elem_id='lora-train-tab'): tmp = gr.State('') with gr.Row(): with gr.Column(): # YY.MM.DD gr.Markdown("`Ver: 23.10.20` This is enhanced version of QLora Training. [Maintained by FP](https://github.com/FartyPants/Training_PRO/tree/main)") with gr.Row(): with gr.Column(scale=5): with gr.Row(): copy_from = gr.Dropdown(label='Copy parameters from', value='None', choices=get_available_loras_local(non_serialized_params['Lora_sortedByTime']), elem_classes=['slim-dropdown']) create_refresh_button(copy_from, lambda: None, lambda: {'choices': get_available_loras_local(non_serialized_params['Lora_sortedByTime'])}, 'refresh-button') with gr.Column(): sort_byTime = gr.Checkbox(label='Sort list by Date', value=False, info='Sorts Loras by date created.', elem_classes=['no-background']) with gr.Row(): with gr.Column(scale=5): lora_name = gr.Textbox(label='Name', info='The name of your new LoRA file') with gr.Column(): always_override = gr.Checkbox(label='Override Existing Files', value=False, info='If the name is the same, checking will replace the existing file, and unchecking will load and continue from it (the rank must be the same).', elem_classes=['no-background']) with gr.Row(): with gr.Column(): lora_rank = gr.Slider(label='LoRA Rank', value=32, minimum=0, maximum=1024, step=4, info='Also called dimension count. Higher values = larger file, more content control. Smaller values = smaller file, less control. Use 4 or 8 for style, 128 or 256 to teach, 1024+ for fine-detail on big data. More VRAM is needed for higher ranks.') lora_alpha = gr.Slider(label='LoRA Alpha', value=64, minimum=0, maximum=2048, step=4, info='This divided by the rank becomes the scaling of the LoRA. Higher means stronger. A good standard value is twice your Rank.') batch_size = gr.Slider(visible= False, label='Batch Size', value=0, minimum=0, maximum=1024, step=4, info='Now Replaced with Gradient accumulation. Keeping it for sake of old saved data') micro_batch_size = gr.Slider(label='True Batch Size', value=4, minimum=1, maximum=128, step=1, info='Specifies how many text blocks per step will be trained. The higher value, the better the concept of training will be, but it requires more GPU memory and it reduces speed.') grad_accumulation = gr.Slider(label='Gradient Accumulation Steps', value=1, minimum=1, maximum=256, step=1, info="Virtually multiplies the Batch Size by averaging the learning over more than one step. VRAM friendly. Evens out loss fluctuations but can also degrade training fidelity.") with gr.Column(): stop_at_loss = gr.Slider(label='Stop at loss (Can be changed during training)', minimum=0.0, maximum=3.0, step=0.1, value=0.00, info='The process will automatically stop once the desired loss value is reached.') gr.Markdown(" ") epochs = gr.Number(label='Epochs', value=3, info='Number of times every entry in the dataset should be fed into training. So 1 means feed each item in once, 5 means feed it in five times, etc.') learning_rate = gr.Textbox(label='Learning Rate', value='3e-4', info='In scientific notation. 3e-4 is a good starting base point. 1e-2 is extremely high, 1e-6 is extremely low.') lr_scheduler_type = gr.Dropdown(label='LR Scheduler', value='linear', choices=['linear', 'constant', 'constant_with_warmup', 'cosine', 'cosine_with_restarts', 'polynomial', 'inverse_sqrt', 'FP_low_epoch_annealing', 'FP_half_time_annealing','FP_raise_fall_creative'], info='Learning rate scheduler - defines how the learning rate changes over time. Custom schedulers: FP_low_epoch_annealing, FP_half_time_annealing, FP_raise_fall_creative (see README)', elem_classes=['slim-dropdown']) with gr.Accordion(label='Checkpoints', open=True): with gr.Row(): with gr.Column(): save_steps = gr.Number(label='Save every n steps', value=0, info='A checkpoint will be saved every n steps and at each Epoch boundary. (0 = OFF)') with gr.Column(): save_steps_under_loss = gr.Slider(label='Save at 10% Loss change', value=1.8, minimum=0.0, maximum=3.0, step=0.1, info="Saves checkpoints at (or bellow) this loss and then each time loss falls by at least 10% This works independently from 'Save every n steps'") with gr.Row(): save_chackpoint_now = gr.Button('Queue Checkpoint Now') with gr.Accordion(label='Advanced Options', open=True): with gr.Row(): with gr.Column(): warmup_steps = gr.Number(label='Warmup Steps', value=100, info='Number of max steps used for a linear warmup. Reduces early over-fitting by the first training blocks. Value has precedent over Warmup Ratio. Aligns to the closest multiple of graddient accumulation') warmup_ratio = gr.Slider(label='Warmup Ratio', minimum=0.0, maximum=0.2, step=0.025, value=0.0, info='Ratio of total training steps that will be used for a linear warmup. It applies only if Warmup Step is 0.') neft_noise_alpha = gr.Slider(label='NEFtune noise scale', minimum=0.0, maximum=15, step=1, value=0.0, info='Add noise to the training to improve generalization. [0 - OFF, Starting value to experiment: 5]') training_projection = gr.Radio(value = train_choices[4], label='LLaMA Target Projections', info='Change the targets (LORA is typically q-v)', choices=train_choices) lora_dropout = gr.Slider(label='LoRA Dropout', minimum=0.0, maximum=1.0, step=0.025, value=0.05, info='Percentage probability for dropout of LoRA layers. This can help reduce overfitting. Most users should leave at default.') optimizer = gr.Dropdown(label='Optimizer', value='adamw_torch', choices=['adamw_hf', 'adamw_torch', 'adamw_torch_fused', 'adamw_torch_xla', 'adamw_apex_fused', 'adafactor', 'adamw_bnb_8bit', 'adamw_anyprecision', 'sgd', 'adagrad'], info='Different optimizer implementation options, for advanced users. Effects of different options are not well documented yet.', elem_classes=['slim-dropdown']) with gr.Column(): train_only_after = gr.Textbox(label='Train Only After', value='', info='Only consider text *after* this string in any given chunk for training. For Alpaca datasets, use "### Response:" to only train the response and ignore the input.') add_bos_token = gr.Checkbox(label='Add BOS token', value=True, info="Adds BOS token for each dataset item") add_eos_token = gr.Checkbox(label='Add EOS token', value=False, info="Adds EOS token for each dataset item") add_eos_token_type = gr.Dropdown(label='EOS placement (Text file)', choices=['Every Block', 'Hard Cut Blocks Only'], value='Every Block', info='', allow_custom_value = False) higher_rank_limit = gr.Checkbox(label='Enable higher ranks', value=False, info='If checked, changes Rank/Alpha slider above to go much higher. This will not work without a datacenter-class GPU.') report_to = gr.Radio(label="Save detailed logs with", value="None", choices=["None", "wandb", "tensorboard"], interactive=True) # for future #with gr.Accordion(label='Dynamic Scheduler', open = False): # ds_min_epochs = gr.Number(label='Minimum Epochs', value='1', info='Minimum epochs that will be always performed before ramp down can be triggered') # ds_max_epochs = gr.Number(label='Maximum Epochs (fallback)', value='50', info='Maximum Epochs before the training will bail out completely (should be a large number)') # ds_loss_trigger = gr.Slider(label='Trigger Loss', minimum=0.0, maximum=2.8, step=0.1, value=1.6, info='Loss at which the ramp down schedule will be triggered') # ds_loss_rolling_window = gr.Number(label='Loss rolling average', value='4', info='Calculate loss by averaging last x numbers to avoid jumps and noise') # ds_epochs_to_ramp = gr.Slider(label='Ramp down ratio', minimum=0.0, maximum=2.0, step=0.1, value=1.00, info='How long the ramp down will last relative to ellapsed steps (before trigger)') # gr.Markdown('These are settings for FP_dynamic_loss_trigger scheduler. The scheduler will do warm up, then hold constant untill a loss falls under Trigger Loss, then it will commence linear ramp down schedule and stop. The length of ramp down is set by Ramp down ratio where (ramp down steps) = ratio * (elapsed steps). (The time to completition shown will be very high untill ramp down is triggered.)') with gr.Column(): with gr.Tab(label='Formatted Dataset'): with gr.Row(): with gr.Column(): with gr.Row(): dataset = gr.Dropdown(choices=get_datasets('training/datasets', 'json'), value='None', label='Dataset', info='The dataset file to use for training.', elem_classes=['slim-dropdown']) create_refresh_button(dataset, lambda: None, lambda: {'choices': get_datasets('training/datasets', 'json')}, 'refresh-button') with gr.Row(): eval_dataset = gr.Dropdown(choices=get_datasets('training/datasets', 'json'), value='None', label='Evaluation Dataset', info='The (optional) dataset file used to evaluate the model after training.', elem_classes=['slim-dropdown']) create_refresh_button(eval_dataset, lambda: None, lambda: {'choices': get_datasets('training/datasets', 'json')}, 'refresh-button') with gr.Column(): with gr.Row(): format = gr.Dropdown(choices=get_datasets('training/formats', 'json'), value='None', label='Data Format', info='The format file used to decide how to format the dataset input.', elem_classes=['slim-dropdown']) create_refresh_button(format, lambda: None, lambda: {'choices': get_datasets('training/formats', 'json')}, 'refresh-button') with gr.Row(): eval_steps = gr.Number(label='Evaluate every n steps', value=100, info='If an evaluation dataset is given, test it every time this many steps pass.') with gr.Tab(label="Text file"): with gr.Row(): raw_text_file = gr.Dropdown(choices=get_datasets('training/datasets', 'txt'), value='None', label='Text file', info='The text file to use for training.', elem_classes=['slim-dropdown']) create_refresh_button(raw_text_file, lambda: None, lambda: {'choices': get_datasets('training/datasets', 'txt')}, 'refresh-button') with gr.Row(): with gr.Column(): precize_slicing_overlap = gr.Checkbox(label='Add Overlapping blocks', value = True) sliding_window = gr.Checkbox(label='DEMENTOR Long-form Learning by FP (Highly Experimental, use low epochs)', value = False, info='Deep Memorization Enforcement Through Overlapping and Repetition. (I named it, so shush). Special process for learning long-form text using low amount of epochs.') #debug_slicer = gr.Checkbox(label='Dump sentencelist.json to logs', value = non_serialized_params['debug_slicer'], info='Debug Slicer') with gr.Column(): hard_cut_string = gr.Textbox(label='Hard Cut String', value='\\n\\n\\n', info='String that indicates a cut between logical blocks of text (ex. Ideas or Chapters). Helps prevent unwanted overlap between unrelated ideas.') min_chars = gr.Number(label='Ignore small blocks', value=0, info='Ignore Text blocks that have less or equal characters than this number.') with gr.Tab(label="URL"): with gr.Row(): with gr.Column(): download_file_url = gr.Textbox(label='Download JSON or txt file to datasets (or formats) folder', value='',info='The URL of a file to download. If on github, make sure you get url of the raw file (https://raw.githubusercontent.com/...). If huggin face, make sure the url has /resolve/ in it not /blob/') with gr.Row(): download_check_overwrite = gr.Checkbox(label='Overwrite', value=False, info='Overwrite if file exist') download_folder = gr.Radio(label="Destination", value='training/datasets', choices=['training/datasets', 'training/formats'], interactive=True) download_button = gr.Button('Download') download_status = gr.Textbox(label='Download Status', value='', interactive=False) with gr.Row(): with gr.Column(): with gr.Row(): cutoff_len = gr.Slider(label='Chunk Length (Cutoff Length)', minimum=32, maximum=2048, value=256, step=32, info='The maximum length of a chunk (in tokens). Applies to both JSON dataset and text files. Higher values require much more VRAM.') with gr.Row(): with gr.Column(): check_dataset_btn = gr.Button('Verify Dataset/Text File and suggest data entries') check_dataset_txt = gr.Textbox(label='Dataset info', value='') with gr.Row(): start_button = gr.Button("Start LoRA Training", variant='primary') stop_button = gr.Button("Interrupt") with gr.Accordion(label="Graph", open=True): with gr.Row(): # show_actions_button = False - we use old gradio plot_graph = gr.LinePlot(x="epoch", y="value", title="Loss Metrics", overlay_point=True, tooltip=["epoch", "value"], x_lim=[0, 1], y_lim=[0, 3.5], width=500, height=250) output = gr.Markdown(value="Ready") with gr.Tab('Perplexity evaluation', elem_id='evaluate-tab'): with gr.Row(): with gr.Column(): models = gr.Dropdown(utils.get_available_models(), label='Models', multiselect=True) evaluate_text_file = gr.Dropdown(choices=['wikitext', 'ptb', 'ptb_new'] + get_datasets('training/datasets', 'txt')[1:], value='wikitext', label='Input dataset', info='The text file on which the model will be evaluated. The first options are automatically downloaded: wikitext, ptb, and ptb_new. The next options are your local text files under training/datasets.') with gr.Row(): with gr.Column(): stride_length = gr.Slider(label='Stride', minimum=1, maximum=2048, value=512, step=1, info='Used to make the evaluation faster at the cost of accuracy. 1 = slowest but most accurate. 512 is a common value.') with gr.Column(): max_length = gr.Slider(label='max_length', minimum=0, maximum=8096, value=0, step=1, info='The context for each evaluation. If set to 0, the maximum context length for the model will be used.') with gr.Row(): start_current_evaluation = gr.Button("Evaluate loaded model") start_evaluation = gr.Button("Evaluate selected models") stop_evaluation = gr.Button("Interrupt") with gr.Column(): evaluation_log = gr.Markdown(value='') evaluation_table = gr.Dataframe(value=generate_markdown_table(), interactive=True) with gr.Row(): save_comments = gr.Button('Save comments', elem_classes="small-button") refresh_table = gr.Button('Refresh the table', elem_classes="small-button") # Training events all_params = [lora_name, always_override, save_steps, micro_batch_size, batch_size, epochs, learning_rate, lr_scheduler_type, lora_rank, lora_alpha, lora_dropout, cutoff_len, dataset, eval_dataset, format, eval_steps, raw_text_file, higher_rank_limit, warmup_steps, optimizer, hard_cut_string, train_only_after, stop_at_loss, add_eos_token, min_chars, report_to, precize_slicing_overlap, add_eos_token_type, save_steps_under_loss, add_bos_token, training_projection,sliding_window,warmup_ratio,grad_accumulation, neft_noise_alpha] def fix_old_version(batch_size_val,micro_batch_size_val, grad_accumulation_val): if batch_size_val>0: gradient_acc = batch_size_val // micro_batch_size_val print(f"Using Old version of Batch Size ({batch_size_val}) to set Gradient Accumulation: {gradient_acc}") return gradient_acc return grad_accumulation_val copy_from.change(partial(do_copy_params, all_params= all_params), copy_from, all_params).then(fix_old_version,[batch_size,micro_batch_size, grad_accumulation],grad_accumulation) start_button.click(do_train, all_params, [output,plot_graph]) stop_button.click(do_interrupt, None, None, queue=False) higher_rank_limit.change(change_rank_limit, [higher_rank_limit], [lora_rank, lora_alpha]) def trigger_stop_at_loss(stop_at_loss_value): non_serialized_params.update({"stop_at_loss": stop_at_loss_value}) if non_serialized_params['training_loop']: print(f"Queue: [Stop at loss Change] to {stop_at_loss_value}") stop_at_loss.change(trigger_stop_at_loss, stop_at_loss, None) def trigger_save_checkpoint(): non_serialized_params.update({"save_checkpoint_now": True}) if non_serialized_params['training_loop']: print("Queue: [Save checkpoint] Checkpoint will be saved after the current step is finished.") else: print("Use during the training to save the checkpoint at any time.") def update_button(): return gr.Button.update('[Checkpoint in Queue]', variant='stop', interactive=True) def update_button2(): time.sleep(1.0) return gr.Button.update('Queue Checkpoint Now', variant='secondary',interactive = True) save_chackpoint_now.click(trigger_save_checkpoint, None, None).then(update_button, None,save_chackpoint_now).then(update_button2, None,save_chackpoint_now) dataset_calc_params = [save_steps,micro_batch_size, epochs, cutoff_len, dataset, format, raw_text_file, warmup_steps, hard_cut_string, min_chars, precize_slicing_overlap,sliding_window,warmup_ratio,grad_accumulation] def check_dataset(save_steps:int, micro_batch_size: int, epochs: int, cutoff_len: int, dataset:str, format:str, raw_text_file:str, warmup_steps:int, hard_cut_string:str, min_chars:int, precize_slicing_overlap:bool,sliding_window:bool,warmup_ratio:float,grad_accumulation:int): result = "Specify JSON dastaset or Text file" total_blocks = 0 if shared.tokenizer is None: yield "Tokenizer is not available. Please Load some Model first." return if raw_text_file not in ['None', '']: logger.info("Loading Text file...") fullpath = clean_path('training/datasets', f'{raw_text_file}') fullpath = Path(fullpath) if fullpath.is_dir(): logger.info('Training path directory {}'.format(raw_text_file)) raw_text = "" file_paths = sorted(fullpath.glob('*.txt'), key=lambda path: natural_keys(path.name)) for file_path in file_paths: if file_path.is_file(): with file_path.open('r', encoding='utf-8') as file: raw_text += file.read().replace('\r', '') logger.info(f"Loaded training file: {file_path.name}") else: try: with open(clean_path('training/datasets', f'{raw_text_file}.txt'), 'r', encoding='utf-8') as file: raw_text = file.read().replace('\r', '') except: yield f"{raw_text_file}.txt doesn't seem to exsist anymore... check your training/datasets folder" return if min_chars<0: min_chars = 0 # == New more precise slicing on sentence boundary == if sliding_window: text_chunks = sliding_block_cut(raw_text, min_chars, False, cutoff_len, hard_cut_string,non_serialized_params['debug_slicer']) else: text_chunks = precise_cut(raw_text, precize_slicing_overlap, min_chars, False, cutoff_len, hard_cut_string,non_serialized_params['debug_slicer']) total_blocks = len(text_chunks) result = f"Text: ({raw_text_file}.txt) has {total_blocks} blocks (Block Size {cutoff_len} tokens)" del text_chunks else: if dataset in ['None', '']: yield "Select dataset or text file." return if format in ['None', '']: yield "Select format choice for dataset." return with open(clean_path('training/formats', f'{format}.json'), 'r', encoding='utf-8-sig') as formatFile: format_data: dict[str, str] = json.load(formatFile) def generate_prompt(data_point: dict[str, str]): for options, data in format_data.items(): if set(options.split(',')) == set(x[0] for x in data_point.items() if (type(x[1]) is str and len(x[1].strip()) > 0)): for key, val in data_point.items(): if type(val) is str: data = data.replace(f'%{key}%', val) return data raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(format_data.keys())}"') def tokenize_dummy(prompt): input_ids = shared.tokenizer.encode(prompt, truncation=True, max_length=cutoff_len) labels = [1] * len(input_ids) input_ids = torch.tensor(input_ids) return { "input_ids": input_ids, "labels": labels, "attention_mask": input_ids.ne(shared.tokenizer.pad_token_id), } def generate_and_tokenize_prompt(data_point): prompt = generate_prompt(data_point) return tokenize_dummy(prompt) logger.info("Loading JSON datasets...") data = load_dataset("json", data_files=clean_path('training/datasets', f'{dataset}.json')) data_keys = [] if data: if 'train' in data: # Check if the 'train' split exists in the dataset data_keys = list(data['train'][0].keys()) print("Data Keys:", data_keys) else: print("The dataset is empty.") train_data = data['train'].map(generate_and_tokenize_prompt, new_fingerprint='%030x' % random.randrange(16**30)) total_blocks = train_data.num_rows result = f"Dataset: ({dataset}.json) has {total_blocks} blocks @ length = {cutoff_len} tokens\n(Keys: {data_keys} - Format: {format}.json): " #for options, data in format_data.items(): # format_keys = options.split(',') # result += f"{format_keys}, " #result = result.rstrip() #result = result.rstrip(',') if total_blocks>0: number_ofSteps = int(math.ceil(total_blocks / micro_batch_size) * epochs) num_stepsPer_epoch = int(math.ceil(number_ofSteps/epochs)) min_warm = math.ceil(100 / grad_accumulation) warmup_steps_suggest = min(int(min_warm*grad_accumulation), int(math.ceil(number_ofSteps * 0.1))) warmup_steps_suggest = min(warmup_steps_suggest,num_stepsPer_epoch) save_each_n_min = int(math.ceil(number_ofSteps/10)) save_each_n_max = int(math.ceil(number_ofSteps/5)) gradient_accumulation_max = int(total_blocks)//micro_batch_size result += f"\n[Batch Size: {micro_batch_size}, Epochs: {epochs}, Gradient Accumulation: {grad_accumulation}]\n" result += f"Total number of steps: {number_ofSteps}\n" result += f"Steps per each Epoch: {num_stepsPer_epoch}\n" result += f"Suggestions:\n" result += f"Checkpoints: Save every {save_each_n_min} - {save_each_n_max} steps (Current: {int(save_steps)})\n" result += f"Warmup steps: {warmup_steps_suggest} (Current: {int(warmup_steps)})" if gradient_accumulation_max < grad_accumulation: result += f"\n\nWARNING: Gradient Accumulation {grad_accumulation} is too high: It should be below {gradient_accumulation_max}" yield result return check_dataset_btn.click(check_dataset, dataset_calc_params ,check_dataset_txt) # Evaluation events. For some reason, the interrupt event # doesn't work with the .then() syntax, so I write them one # by one in this ugly but functional way. ev = start_evaluation.click(calculate_perplexity, [models, evaluate_text_file, stride_length, max_length], evaluation_log, show_progress=False) start_evaluation.click(generate_markdown_table, None, evaluation_table, show_progress=False) start_current_evaluation.click(lambda: ['current model'], None, tmp) ev_cur = start_current_evaluation.click(calculate_perplexity, [tmp, evaluate_text_file, stride_length, max_length], evaluation_log, show_progress=False) start_current_evaluation.click(generate_markdown_table, None, evaluation_table, show_progress=False) stop_evaluation.click(None, None, None, cancels=[ev, ev_cur], queue=False) refresh_table.click(generate_markdown_table, None, evaluation_table, show_progress=True) save_comments.click( save_past_evaluations, evaluation_table, None).then( lambda: "Comments saved.", None, evaluation_log, show_progress=False) def reload_lora(): return gr.Dropdown.update(choices=get_available_loras_local(non_serialized_params['Lora_sortedByTime'])) # nonserialized items sort_byTime.change(lambda x: non_serialized_params.update({"Lora_sortedByTime": x}), sort_byTime, None).then(reload_lora,None,copy_from) #debug_slicer.change(lambda x: non_serialized_params.update({"debug_slicer": x}), debug_slicer, None) def update_dataset(): return gr.update(choices=get_datasets('training/datasets', 'json')), gr.update(choices=get_datasets('training/datasets', 'txt'))
download_button.click(download_file_from_url, [download_file_url,download_check_overwrite,download_folder] , download_status).then(update_dataset,None,[dataset , raw_text_file])
6
2023-12-20 14:13:38+00:00
12k
foocker/Bert-VITS2-Faster
text/chinese.py
[ { "identifier": "punctuation", "path": "text/symbols.py", "snippet": "" }, { "identifier": "ToneSandhi", "path": "text/tone_sandhi.py", "snippet": "class ToneSandhi:\n def __init__(self):\n self.must_neural_tone_words = {\n \"麻烦\",\n \"麻利\",\n \...
import os import re import cn2an import sys import jieba.posseg as psg from pypinyin import lazy_pinyin, Style from text.symbols import punctuation from text.tone_sandhi import ToneSandhi from text import chinese_bert from text.chinese_bert import get_bert_feature
7,610
sys.path.insert(0,"/data/stable-diffusion-tritonserver/Bert-VITS2") current_file_path = os.path.dirname(__file__) pinyin_to_symbol_map = { line.split("\t")[0]: line.strip().split("\t")[1] for line in open(os.path.join(current_file_path, "opencpop-strict.txt")).readlines() } rep_map = { ":": ",", ";": ",", ",": ",", "。": ".", "!": "!", "?": "?", "\n": ".", "·": ",", "、": ",", "...": "…", "$": ".", "“": "'", "”": "'", "‘": "'", "’": "'", "(": "'", ")": "'", "(": "'", ")": "'", "《": "'", "》": "'", "【": "'", "】": "'", "[": "'", "]": "'", "—": "-", "~": "-", "~": "-", "「": "'", "」": "'", }
sys.path.insert(0,"/data/stable-diffusion-tritonserver/Bert-VITS2") current_file_path = os.path.dirname(__file__) pinyin_to_symbol_map = { line.split("\t")[0]: line.strip().split("\t")[1] for line in open(os.path.join(current_file_path, "opencpop-strict.txt")).readlines() } rep_map = { ":": ",", ";": ",", ",": ",", "。": ".", "!": "!", "?": "?", "\n": ".", "·": ",", "、": ",", "...": "…", "$": ".", "“": "'", "”": "'", "‘": "'", "’": "'", "(": "'", ")": "'", "(": "'", ")": "'", "《": "'", "》": "'", "【": "'", "】": "'", "[": "'", "]": "'", "—": "-", "~": "-", "~": "-", "「": "'", "」": "'", }
tone_modifier = ToneSandhi()
1
2023-12-18 09:53:41+00:00
12k
sinoyou/nelf-pro
nerfstudio/engine/trainer.py
[ { "identifier": "base_config", "path": "nerfstudio/configs/base_config.py", "snippet": "CONSOLE = Console(width=120)\nclass PrintableConfig: # pylint: disable=too-few-public-methods\nclass InstantiateConfig(PrintableConfig): # pylint: disable=too-few-public-methods\nclass MachineConfig(PrintableConfig...
import dataclasses import functools import os import time import json import torch import plotly.graph_objects as go from typing import Dict, List, Tuple from numpy import isin from pathlib import Path from rich.console import Console from torch.cuda.amp.grad_scaler import GradScaler from typing_extensions import Literal from nerfstudio.configs import base_config as cfg from nerfstudio.engine.callbacks import ( TrainingCallback, TrainingCallbackAttributes, TrainingCallbackLocation, ) from nerfstudio.engine.optimizers import Optimizers, setup_optimizers from nerfstudio.pipelines.base_pipeline import VanillaPipeline from nerfstudio.utils import profiler, writer from nerfstudio.utils.decorators import ( check_eval_enabled, check_main_thread, check_viewer_enabled, ) from nerfstudio.utils.misc import step_check from nerfstudio.utils.writer import EventName, TimeWriter from nerfstudio.viewer.server import viewer_utils from nerfstudio.utils.load_utils import check_load_step
10,195
try: self.viewer_state.update_scene(self, step, self.pipeline.model, num_rays_per_batch) except RuntimeError: time.sleep(0.03) # sleep to allow buffer to reset assert self.viewer_state.vis is not None self.viewer_state.vis["renderingState/log_errors"].write( "Error: GPU out of memory. Reduce resolution to prevent viewer from crashing." ) @check_viewer_enabled def _update_viewer_rays_per_sec(self, train_t: TimeWriter, vis_t: TimeWriter, step: int): """Performs update on rays/sec calclation for training Args: train_t: timer object carrying time to execute total training iteration vis_t: timer object carrying time to execute visualization step step: current step """ train_num_rays_per_batch = self.config.pipeline.datamanager.train_num_rays_per_batch writer.put_time( name=EventName.TRAIN_RAYS_PER_SEC, duration=train_num_rays_per_batch / (train_t.duration - vis_t.duration), step=step, avg_over_steps=True, ) def _load_checkpoint(self) -> None: """Helper function to load pipeline and optimizer from prespecified checkpoint""" load_dir = self.config.trainer.load_dir # try to find checkpoint dir if load_dir is None: load_dir_try = self.config.get_checkpoint_dir() if load_dir_try.exists(): load_dir = load_dir_try if load_dir is not None: load_step = self.config.trainer.load_step if load_step is None: print("Loading latest checkpoint from load_dir") # NOTE: this is specific to the checkpoint name format # load_step = sorted(int(x[x.find("-") + 1 : x.find(".")]) for x in os.listdir(load_dir))[-1] load_step = sorted(int(x.replace('-', '.').split('.')[-2]) for x in os.listdir(load_dir))[-1] load_path = Path(load_dir) / Path(f"model.{load_step:09d}.ckpt") if not load_path.exists(): load_path = Path(load_dir) / Path(f'step-{load_step:09d}.ckpt') # old format assert load_path.exists(), f"Checkpoint {load_path} does not exist" loaded_state = torch.load(load_path, map_location="cpu") self._start_step = loaded_state["step"] + 1 # load the checkpoints for pipeline, optimizers, and gradient scalar self.pipeline.load_pipeline(loaded_state["pipeline"], load_step, load_dir) self.optimizers.load_optimizers(loaded_state["optimizers"]) if "schedulers" in loaded_state and self.config.trainer.load_scheduler: self.optimizers.load_schedulers(loaded_state["schedulers"]) self.grad_scaler.load_state_dict(loaded_state["scalers"]) CONSOLE.print(f"done loading checkpoint from {load_path}, starting from step {self._start_step}") else: CONSOLE.print("No checkpoints to load, training from scratch") @check_main_thread def save_checkpoint(self, step: int) -> None: """Save the model and optimizers Args: step: number of steps in training for given checkpoint """ # possibly make the checkpoint directory if not self.checkpoint_dir.exists(): self.checkpoint_dir.mkdir(parents=True, exist_ok=True) # save the checkpoint ckpt_path = self.checkpoint_dir / f"model.{step:09d}.ckpt" torch.save( { "step": step, "pipeline": self.pipeline.module.state_dict() # type: ignore if hasattr(self.pipeline, "module") else self.pipeline.state_dict(), "optimizers": {k: v.state_dict() for (k, v) in self.optimizers.optimizers.items()}, "schedulers": {k: v.state_dict() for (k, v) in self.optimizers.schedulers.items()}, "scalers": self.grad_scaler.state_dict(), }, ckpt_path, ) self.pipeline.call_customized_save(step=step, checkpoint_dir=self.checkpoint_dir) # possibly delete old checkpoints if self.config.trainer.save_only_latest_checkpoint: # delete everything else in the checkpoint folder for f in self.checkpoint_dir.glob("*"): if int(str(f).split('.')[-2]) != step: f.unlink() @profiler.time_function def train_iteration(self, step: int) -> Tuple[torch.Tensor, Dict[str, torch.Tensor], Dict[str, torch.Tensor]]: """Run one iteration with a batch of inputs. Returns dictionary of model losses. Args: step: Current training step. """ self.optimizers.zero_grad_all() cpu_or_cuda_str = self.device.split(":")[0] with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision): _, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step) loss = functools.reduce(torch.add, loss_dict.values()) self.grad_scaler.scale(loss).backward() # type: ignore # try: # torch.nn.utils.clip_grad_norm_(self.pipeline.model.parameters(), 10.0, error_if_nonfinite=True) # # torch.nn.utils.clip_grad_value_(self.pipeline.model.parameters(), 10.0) # except Exception as e: # CONSOLE.print(f"Error: {e}") # CONSOLE.print("Error: gradient clipping detected nonfinite number, skipping updating. ") # self.optimizers.scheduler_step_all(step) # self.optimizers.zero_grad_all() # return loss, loss_dict, metrics_dict self.optimizers.optimizer_scaler_step_all(self.grad_scaler) self.grad_scaler.update() self.optimizers.scheduler_step_all(step) # Merging loss and metrics dict into a single output. return loss, loss_dict, metrics_dict
# zinyou note: # trainer in principle should not be modified. # modification should be only within pipeline or lower level: model and data manager. # Copyright 2022 The Nerfstudio 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. """ Code to train model. """ from __future__ import annotations CONSOLE = Console(width=120) class Trainer: """Trainer class Args: config: The configuration object. local_rank: Local rank of the process. world_size: World size of the process. Attributes: config: The configuration object. local_rank: Local rank of the process. world_size: World size of the process. device: The device to run the training on. pipeline: The pipeline object. optimizers: The optimizers object. callbacks: The callbacks object. """ pipeline: VanillaPipeline optimizers: Optimizers callbacks: List[TrainingCallback] def __init__(self, config: cfg.Config, local_rank: int = 0, world_size: int = 1): self.config = config self.local_rank = local_rank self.world_size = world_size self.device = "cpu" if world_size == 0 else f"cuda:{local_rank}" self.mixed_precision = self.config.trainer.mixed_precision if self.device == "cpu": self.mixed_precision = False CONSOLE.print("Mixed precision is disabled for CPU training.") self._start_step = 0 # optimizers self.grad_scaler = GradScaler(enabled=self.mixed_precision) self.base_dir = config.get_base_dir() # directory to save checkpoints self.checkpoint_dir = config.get_checkpoint_dir() CONSOLE.log(f"Saving checkpoints to: {self.checkpoint_dir}") # set up viewer if enabled viewer_log_path = self.base_dir / config.viewer.relative_log_filename self.viewer_state, banner_messages = None, None if self.config.is_viewer_enabled() and local_rank == 0: self.viewer_state, banner_messages = viewer_utils.setup_viewer(config.viewer, log_filename=viewer_log_path) self._check_viewer_warnings() # set up writers/profilers if enabled writer_log_path = self.base_dir / config.logging.relative_log_dir writer.setup_event_writer(config, log_dir=writer_log_path) writer.setup_local_writer( config.logging, max_iter=config.trainer.max_num_iterations, banner_messages=banner_messages ) writer.put_config(name="config", config_dict=dataclasses.asdict(config), step=0) profiler.setup_profiler(config.logging) def setup(self, test_mode: Literal["test", "val", "inference"] = "val"): """Setup the Trainer by calling other setup functions. Args: test_mode: 'val': loads train/val datasets into memory 'test': loads train/test datset into memory 'inference': does not load any dataset into memory """ self.pipeline = self.config.pipeline.setup( device=self.device, test_mode=test_mode, world_size=self.world_size, local_rank=self.local_rank, load_step = check_load_step(self.config), ) self.optimizers = setup_optimizers(self.config, self.pipeline.get_param_groups()) self._load_checkpoint() self.training_attributes = TrainingCallbackAttributes( optimizers=self.optimizers, # type: ignore grad_scaler=self.grad_scaler, # type: ignore pipeline=self.pipeline, # type: ignore config=self.config.trainer, # type: ignore ) self.callbacks = self.pipeline.get_training_callbacks(self.training_attributes) def train(self) -> None: """Train the model.""" assert self.pipeline.datamanager.train_dataset is not None, "Missing DatsetInputs" self._init_viewer_state() # plotly scene if self.config.trainer.visualize_scene: scene_plotly_data = self.pipeline.get_scene_plotly_figure() if scene_plotly_data: fig = go.Figure(data=scene_plotly_data) writer.put_plotly(name="scene", figure=fig) CONSOLE.log("Scene plotly is uploaded.") self.training_time = 0.0 with TimeWriter(writer, EventName.TOTAL_TRAIN_TIME): num_iterations = self.config.trainer.max_num_iterations step = self._start_step self._update_viewer_state(step) for step in range(self._start_step, num_iterations): with TimeWriter(writer, EventName.ITER_TRAIN_TIME, step=step) as train_t: self.pipeline.train() # training callbacks before the training iteration for callback in self.callbacks: callback.run_callback_at_location( step, location=TrainingCallbackLocation.BEFORE_TRAIN_ITERATION ) start_time = time.time() # time the forward pass loss, loss_dict, metrics_dict = self.train_iteration(step) self.training_time += time.time() - start_time # training callbacks after the training iteration for callback in self.callbacks: callback.run_callback_at_location(step, location=TrainingCallbackLocation.AFTER_TRAIN_ITERATION) # Skip the first two steps to avoid skewed timings that break the viewer rendering speed estimate. if step > 1: writer.put_time( name=EventName.TRAIN_RAYS_PER_SEC, duration=self.config.pipeline.datamanager.train_num_rays_per_batch / train_t.duration, step=step, avg_over_steps=True, ) self._update_viewer_state(step) # a batch of train rays if step_check(step, self.config.logging.steps_per_log, run_at_zero=True): writer.put_scalar(name="Train Loss", scalar=loss, step=step) writer.put_dict(name="Train Loss Dict", scalar_dict=loss_dict, step=step) writer.put_dict(name="Train Metrics Dict", scalar_dict=metrics_dict, step=step) if step_check(step, self.config.trainer.steps_per_save): self.save_checkpoint(step) self.eval_iteration(step) writer.write_out_storage() # save checkpoint at the end of training self.save_checkpoint(step) self.save_running_performance() CONSOLE.rule() CONSOLE.print("[bold green]:tada: :tada: :tada: Training Finished :tada: :tada: :tada:", justify="center") if not self.config.viewer.quit_on_train_completion: CONSOLE.print("Use ctrl+c to quit", justify="center") self._always_render(step) @check_main_thread def _always_render(self, step): if self.config.is_viewer_enabled(): while True: self.viewer_state.vis["renderingState/isTraining"].write(False) self._update_viewer_state(step) @check_main_thread def _check_viewer_warnings(self) -> None: """Helper to print out any warnings regarding the way the viewer/loggers are enabled""" if self.config.is_viewer_enabled(): string = ( "[NOTE] Not running eval iterations since only viewer is enabled." " Use [yellow]--vis wandb[/yellow] or [yellow]--vis tensorboard[/yellow] to run with eval instead." ) CONSOLE.print(f"{string}") @check_main_thread def save_running_performance(self): output_path = self.checkpoint_dir / f"../running_performance.json" performance_info = { "n_parameters": self.pipeline.model.n_parameters() / 1024 / 1024, "training_time": self.training_time, } output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(json.dumps(performance_info, indent=2), "utf8") CONSOLE.log(f'model parameters: {performance_info["n_parameters"]}, training time: {performance_info["training_time"]}') @check_viewer_enabled def _init_viewer_state(self) -> None: """Initializes viewer scene with given train dataset""" assert self.viewer_state and self.pipeline.datamanager.train_dataset self.viewer_state.init_scene( dataset=self.pipeline.datamanager.train_dataset, start_train=self.config.viewer.start_train, ) if not self.config.viewer.start_train: self._always_render(self._start_step) @check_viewer_enabled def _update_viewer_state(self, step: int): """Updates the viewer state by rendering out scene with current pipeline Returns the time taken to render scene. Args: step: current train step """ assert self.viewer_state is not None with TimeWriter(writer, EventName.ITER_VIS_TIME, step=step) as _: num_rays_per_batch = self.config.pipeline.datamanager.train_num_rays_per_batch try: self.viewer_state.update_scene(self, step, self.pipeline.model, num_rays_per_batch) except RuntimeError: time.sleep(0.03) # sleep to allow buffer to reset assert self.viewer_state.vis is not None self.viewer_state.vis["renderingState/log_errors"].write( "Error: GPU out of memory. Reduce resolution to prevent viewer from crashing." ) @check_viewer_enabled def _update_viewer_rays_per_sec(self, train_t: TimeWriter, vis_t: TimeWriter, step: int): """Performs update on rays/sec calclation for training Args: train_t: timer object carrying time to execute total training iteration vis_t: timer object carrying time to execute visualization step step: current step """ train_num_rays_per_batch = self.config.pipeline.datamanager.train_num_rays_per_batch writer.put_time( name=EventName.TRAIN_RAYS_PER_SEC, duration=train_num_rays_per_batch / (train_t.duration - vis_t.duration), step=step, avg_over_steps=True, ) def _load_checkpoint(self) -> None: """Helper function to load pipeline and optimizer from prespecified checkpoint""" load_dir = self.config.trainer.load_dir # try to find checkpoint dir if load_dir is None: load_dir_try = self.config.get_checkpoint_dir() if load_dir_try.exists(): load_dir = load_dir_try if load_dir is not None: load_step = self.config.trainer.load_step if load_step is None: print("Loading latest checkpoint from load_dir") # NOTE: this is specific to the checkpoint name format # load_step = sorted(int(x[x.find("-") + 1 : x.find(".")]) for x in os.listdir(load_dir))[-1] load_step = sorted(int(x.replace('-', '.').split('.')[-2]) for x in os.listdir(load_dir))[-1] load_path = Path(load_dir) / Path(f"model.{load_step:09d}.ckpt") if not load_path.exists(): load_path = Path(load_dir) / Path(f'step-{load_step:09d}.ckpt') # old format assert load_path.exists(), f"Checkpoint {load_path} does not exist" loaded_state = torch.load(load_path, map_location="cpu") self._start_step = loaded_state["step"] + 1 # load the checkpoints for pipeline, optimizers, and gradient scalar self.pipeline.load_pipeline(loaded_state["pipeline"], load_step, load_dir) self.optimizers.load_optimizers(loaded_state["optimizers"]) if "schedulers" in loaded_state and self.config.trainer.load_scheduler: self.optimizers.load_schedulers(loaded_state["schedulers"]) self.grad_scaler.load_state_dict(loaded_state["scalers"]) CONSOLE.print(f"done loading checkpoint from {load_path}, starting from step {self._start_step}") else: CONSOLE.print("No checkpoints to load, training from scratch") @check_main_thread def save_checkpoint(self, step: int) -> None: """Save the model and optimizers Args: step: number of steps in training for given checkpoint """ # possibly make the checkpoint directory if not self.checkpoint_dir.exists(): self.checkpoint_dir.mkdir(parents=True, exist_ok=True) # save the checkpoint ckpt_path = self.checkpoint_dir / f"model.{step:09d}.ckpt" torch.save( { "step": step, "pipeline": self.pipeline.module.state_dict() # type: ignore if hasattr(self.pipeline, "module") else self.pipeline.state_dict(), "optimizers": {k: v.state_dict() for (k, v) in self.optimizers.optimizers.items()}, "schedulers": {k: v.state_dict() for (k, v) in self.optimizers.schedulers.items()}, "scalers": self.grad_scaler.state_dict(), }, ckpt_path, ) self.pipeline.call_customized_save(step=step, checkpoint_dir=self.checkpoint_dir) # possibly delete old checkpoints if self.config.trainer.save_only_latest_checkpoint: # delete everything else in the checkpoint folder for f in self.checkpoint_dir.glob("*"): if int(str(f).split('.')[-2]) != step: f.unlink() @profiler.time_function def train_iteration(self, step: int) -> Tuple[torch.Tensor, Dict[str, torch.Tensor], Dict[str, torch.Tensor]]: """Run one iteration with a batch of inputs. Returns dictionary of model losses. Args: step: Current training step. """ self.optimizers.zero_grad_all() cpu_or_cuda_str = self.device.split(":")[0] with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision): _, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step) loss = functools.reduce(torch.add, loss_dict.values()) self.grad_scaler.scale(loss).backward() # type: ignore # try: # torch.nn.utils.clip_grad_norm_(self.pipeline.model.parameters(), 10.0, error_if_nonfinite=True) # # torch.nn.utils.clip_grad_value_(self.pipeline.model.parameters(), 10.0) # except Exception as e: # CONSOLE.print(f"Error: {e}") # CONSOLE.print("Error: gradient clipping detected nonfinite number, skipping updating. ") # self.optimizers.scheduler_step_all(step) # self.optimizers.zero_grad_all() # return loss, loss_dict, metrics_dict self.optimizers.optimizer_scaler_step_all(self.grad_scaler) self.grad_scaler.update() self.optimizers.scheduler_step_all(step) # Merging loss and metrics dict into a single output. return loss, loss_dict, metrics_dict
@check_eval_enabled
9
2023-12-15 20:07:22+00:00
12k
Infleqtion/qLDPC
qldpc/codes.py
[ { "identifier": "abstract", "path": "qldpc/abstract.py", "snippet": "DEFAULT_FIELD_ORDER = 2\nclass GroupMember(comb.Permutation):\nclass Group:\nclass Element:\nclass Protograph:\nclass TrivialGroup(Group):\nclass CyclicGroup(Group):\nclass DihedralGroup(Group):\nclass QuaternionGroup(Group):\n def ...
import abc import functools import itertools import cachetools import galois import ldpc.mod2 import networkx as nx import numpy as np import numpy.typing as npt import qldpc from collections.abc import Collection, Iterable, Sequence from typing import TYPE_CHECKING, Literal from qldpc import abstract from qldpc.objects import CayleyComplex, Node, Pauli, QuditOperator from typing_extensions import Self
7,861
matrix = np.zeros((num_bits - 1, num_bits), dtype=int) for row in range(num_bits - 1): matrix[row, row] = 1 matrix[row, row + 1] = minus_one return ClassicalCode(matrix, field) @classmethod def ring(cls, num_bits: int, field: int | None = None) -> ClassicalCode: """Construct a repetition code with periodic boundary conditions.""" minus_one = galois.GF(field or DEFAULT_FIELD_ORDER).characteristic - 1 matrix = np.zeros((num_bits, num_bits), dtype=int) for row in range(num_bits): matrix[row, row] = 1 matrix[row, (row + 1) % num_bits] = minus_one return ClassicalCode(matrix, field) @classmethod def hamming(cls, rank: int, field: int | None = None) -> ClassicalCode: """Construct a hamming code of a given rank.""" field = field or DEFAULT_FIELD_ORDER if field == 2: # parity check matrix: columns = all nonzero bitstrings bitstrings = list(itertools.product([0, 1], repeat=rank)) return ClassicalCode(np.array(bitstrings[1:]).T) # More generally, columns = maximal set of nonzero, linearly independent strings. # This is achieved by collecting together all strings whose first nonzero element is a 1. strings = [ (0,) * top_row + (1,) + rest for top_row in range(rank - 1, -1, -1) for rest in itertools.product(range(field), repeat=rank - top_row - 1) ] return ClassicalCode(np.array(strings).T, field=field) # TODO: add more codes, particularly from code families that are useful for good quantum codes # see https://mhostetter.github.io/galois/latest/api/#forward-error-correction # TODO: # - add method to convert a parity check matrix into standard form # - see https://arxiv.org/abs/1101.1519 # - one method to compute "blocks" of standard form, one to return the matrix itself # - add is_CSS method to figure out whether this is a CSS Code # - see https://quantumcomputing.stackexchange.com/questions/15432/ # - also compute and store sub-codes, if CSS # - also add QuditCode.to_CSS() -> CSSCode class QuditCode(AbstractCode): """Quantum stabilizer code for Galois qudits, with dimension q = p^m for prime p and integer m. The parity check matrix of a QuditCode has dimensions (num_checks, 2 * num_qudits), and can be written as a block matrix in the form H = [H_x|H_z]. Each block has num_qudits columns. The entries H_x[c, d] = r_x and H_z[c, d] = r_z iff check c addresses qudit d with the operator X(r_x) * Z(r_z), where r_x, r_z range over the base field, and X(r), Z(r) are generalized Pauli operators. Specifically: - X(r) = sum_{j=0}^{q-1} |j+r><j| is a shift operator, and - Z(r) = sum_{j=0}^{q-1} w^{j r} |j><j| is a phase operator, with w = exp(2 pi i / q). Warning: here j, r, s, etc. not integers, but elements of the Galois field GF(q), which has different rules for addition and multiplication when q is not a prime number. Helpful lecture by Gottesman: https://www.youtube.com/watch?v=JWg4zrNAF-g """ @property def num_checks(self) -> int: """Number of parity checks (stabilizers) in this code.""" return self.matrix.shape[0] @property def num_qudits(self) -> int: """Number of data qudits in this code.""" return self.matrix.shape[1] // 2 @property def num_qubits(self) -> int: """Number of data qubits in this code.""" self._assert_qubit_code() return self.num_qudits def _assert_qubit_code(self) -> None: if self._field_order != 2: raise ValueError("Attempted to call a qubit-only method with a non-qubit code.") @classmethod def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph: """Convert a parity check matrix into a Tanner graph.""" graph = nx.DiGraph() matrix = np.reshape(matrix, (len(matrix), 2, -1)) for row, col_xz, col in zip(*np.nonzero(matrix)): node_check = Node(index=int(row), is_data=False) node_qudit = Node(index=int(col), is_data=True) graph.add_edge(node_check, node_qudit) qudit_op = graph[node_check][node_qudit].get(QuditOperator, QuditOperator()) vals_xz = list(qudit_op.value) vals_xz[col_xz] += int(matrix[row, col_xz, col]) graph[node_check][node_qudit][QuditOperator] = QuditOperator(tuple(vals_xz)) if isinstance(matrix, galois.FieldArray): graph.order = type(matrix).order return graph @classmethod def graph_to_matrix(cls, graph: nx.DiGraph) -> galois.FieldArray: """Convert a Tanner graph into a parity check matrix.""" num_qudits = sum(1 for node in graph.nodes() if node.is_data) num_checks = len(graph.nodes()) - num_qudits matrix = np.zeros((num_checks, 2, num_qudits), dtype=int) for node_check, node_qudit, data in graph.edges(data=True): matrix[node_check.index, :, node_qudit.index] = data[QuditOperator].value field = graph.order if hasattr(graph, "order") else DEFAULT_FIELD_ORDER return galois.GF(field)(matrix.reshape(num_checks, 2 * num_qudits)) def get_stabilizers(self) -> list[str]: """Stabilizers (checks) of this code, represented by strings.""" matrix = self.matrix.reshape(self.num_checks, 2, self.num_qudits) stabilizers = [] for check in range(self.num_checks): ops = [] for qudit in range(self.num_qudits):
"""Error correction code constructions Copyright 2023 The qLDPC Authors and Infleqtion 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. """ from __future__ import annotations if TYPE_CHECKING: DEFAULT_FIELD_ORDER = abstract.DEFAULT_FIELD_ORDER ################################################################################ # template error correction code classes class AbstractCode(abc.ABC): """Template class for error-correcting codes.""" _field_order: int def __init__( self, matrix: Self | npt.NDArray[np.int_] | Sequence[Sequence[int]], field: int | None = None, ) -> None: """Construct a code from a parity check matrix over a finite field. The base field is taken to be F_2 by default. """ self._matrix: galois.FieldArray if isinstance(matrix, type(self)): self._field_order = matrix.field.order if not (field is None or field == self._field_order): raise ValueError( f"Field argument {field} is inconsistent with the given code, which is defined" f" over F_{self._field_order}" ) self._matrix = matrix.matrix elif isinstance(matrix, galois.FieldArray): self._field_order = type(matrix).order self._matrix = matrix else: self._field_order = field or DEFAULT_FIELD_ORDER self._matrix = self.field(np.array(matrix)) @property def field(self) -> type[galois.FieldArray]: """Base field over which this code is defined.""" return galois.GF(self._field_order) @property def matrix(self) -> galois.FieldArray: """Parity check matrix of this code.""" return self._matrix @functools.cached_property def graph(self) -> nx.DiGraph: """Tanner graph of this code.""" return self.matrix_to_graph(self.matrix) @classmethod @abc.abstractmethod def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph: """Convert a parity check matrix into a Tanner graph.""" @classmethod @abc.abstractmethod def graph_to_matrix(cls, graph: nx.DiGraph) -> galois.FieldArray: """Convert a Tanner graph into a parity check matrix.""" class ClassicalCode(AbstractCode): """Classical linear error-correcting code over a finite field F_q. A classical binary code C = {x} is a set of vectors x (with entries in F_q) called code words. We consider only linear codes, for which any linear combination of code words is also code word. Operationally, we define a classical code by a parity check matrix H with dimensions (num_checks, num_bits). Each row of H represents a linear constraint (a "check") that code words must satisfy. A vector x is a code word iff H @ x = 0. """ def __contains__(self, word: npt.NDArray[np.int_] | Sequence[int]) -> bool: return not np.any(self.matrix @ self.field(word)) @classmethod def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph: """Convert a parity check matrix H into a Tanner graph. The Tanner graph is a bipartite graph with (num_checks, num_bits) vertices, respectively identified with the checks and bits of the code. The check vertex c and the bit vertex b share an edge iff c addresses b; that is, edge (c, b) is in the graph iff H[c, b] != 0. """ graph = nx.DiGraph() for row, col in zip(*np.nonzero(matrix)): node_c = Node(index=int(row), is_data=False) node_d = Node(index=int(col), is_data=True) graph.add_edge(node_c, node_d, val=matrix[row][col]) if isinstance(matrix, galois.FieldArray): graph.order = type(matrix).order return graph @classmethod def graph_to_matrix(cls, graph: nx.DiGraph) -> galois.FieldArray: """Convert a Tanner graph into a parity check matrix.""" num_bits = sum(1 for node in graph.nodes() if node.is_data) num_checks = len(graph.nodes()) - num_bits field = graph.order if hasattr(graph, "order") else DEFAULT_FIELD_ORDER matrix = galois.GF(field).Zeros((num_checks, num_bits)) for node_c, node_b, data in graph.edges(data=True): matrix[node_c.index, node_b.index] = data.get("val", 1) return matrix @functools.cached_property def generator(self) -> galois.FieldArray: """Generator of this code: a matrix whose rows for a basis for code words.""" return self.matrix.null_space() def words(self) -> galois.FieldArray: """Code words of this code.""" vectors = itertools.product(self.field.elements, repeat=self.generator.shape[0]) return self.field(list(vectors)) @ self.generator def get_random_word(self) -> galois.FieldArray: """Random code word: a sum all generators with random field coefficients.""" return self.field.Random(self.generator.shape[0]) @ self.generator def dual(self) -> ClassicalCode: """Dual to this code. The dual code ~C is the set of bitstrings orthogonal to C: ~C = { x : x @ y = 0 for all y in C }. The parity check matrix of ~C is equal to the generator of C. """ return ClassicalCode(self.generator, self._field_order) def __invert__(self) -> ClassicalCode: return self.dual() @classmethod def tensor_product(cls, code_a: ClassicalCode, code_b: ClassicalCode) -> ClassicalCode: """Tensor product C_a ⊗ C_b of two codes C_a and C_b. Let G_a and G_b respectively denote the generators C_a and C_b. Definition: C_a ⊗ C_b is the code whose generators are G_a ⊗ G_b. Observation: G_a ⊗ G_b is the check matrix of ~(C_a ⊗ C_b). We therefore construct ~(C_a ⊗ C_b) and return its dual ~~(C_a ⊗ C_b) = C_a ⊗ C_b. """ if not code_a._field_order == code_b._field_order: raise ValueError("Cannot take tensor product of codes over different fields") gen_a: npt.NDArray[np.int_] = code_a.generator gen_b: npt.NDArray[np.int_] = code_b.generator return ~ClassicalCode(np.kron(gen_a, gen_b)) @property def num_checks(self) -> int: """Number of check bits in this code.""" return self._matrix.shape[0] @property def num_bits(self) -> int: """Number of data bits in this code.""" return self._matrix.shape[1] @functools.cached_property def rank(self) -> int: """Rank of this code's parity check matrix. Equivalently, the number of linearly independent parity checks in this code. """ if self._field_order == 2: return ldpc.mod2.rank(self._matrix) return np.linalg.matrix_rank(self._matrix) @property def dimension(self) -> int: """The number of logical bits encoded by this code.""" return self.num_bits - self.rank @functools.cache def get_distance(self) -> int: """The distance of this code, or equivalently the minimal weight of a nonzero code word.""" words = self.words().view(np.ndarray) return np.min(np.count_nonzero(words[1:], axis=1)) def get_code_params(self) -> tuple[int, int, int]: """Compute the parameters of this code: [n,k,d]. Here: - n is the number of data bits - k is the number of encoded ("logical") bits - d is the code distance """ return self.num_bits, self.dimension, self.get_distance() @classmethod def random(cls, bits: int, checks: int, field: int | None = None) -> ClassicalCode: """Construct a random classical code with the given number of bits and nontrivial checks.""" if field is None: field = DEFAULT_FIELD_ORDER code_field = galois.GF(field) rows, cols = checks, bits matrix = code_field.Random((rows, cols)) for row in range(matrix.shape[0]): if not matrix[row, :].any(): matrix[row, np.random.randint(cols)] = code_field.Random(low=1) # pragma: no cover for col in range(matrix.shape[1]): if not matrix[:, col].any(): matrix[np.random.randint(rows), col] = code_field.Random(low=1) # pragma: no cover return ClassicalCode(matrix, field) @classmethod def repetition(cls, num_bits: int, field: int | None = None) -> ClassicalCode: """Construct a repetition code on the given number of bits.""" minus_one = galois.GF(field or DEFAULT_FIELD_ORDER).characteristic - 1 matrix = np.zeros((num_bits - 1, num_bits), dtype=int) for row in range(num_bits - 1): matrix[row, row] = 1 matrix[row, row + 1] = minus_one return ClassicalCode(matrix, field) @classmethod def ring(cls, num_bits: int, field: int | None = None) -> ClassicalCode: """Construct a repetition code with periodic boundary conditions.""" minus_one = galois.GF(field or DEFAULT_FIELD_ORDER).characteristic - 1 matrix = np.zeros((num_bits, num_bits), dtype=int) for row in range(num_bits): matrix[row, row] = 1 matrix[row, (row + 1) % num_bits] = minus_one return ClassicalCode(matrix, field) @classmethod def hamming(cls, rank: int, field: int | None = None) -> ClassicalCode: """Construct a hamming code of a given rank.""" field = field or DEFAULT_FIELD_ORDER if field == 2: # parity check matrix: columns = all nonzero bitstrings bitstrings = list(itertools.product([0, 1], repeat=rank)) return ClassicalCode(np.array(bitstrings[1:]).T) # More generally, columns = maximal set of nonzero, linearly independent strings. # This is achieved by collecting together all strings whose first nonzero element is a 1. strings = [ (0,) * top_row + (1,) + rest for top_row in range(rank - 1, -1, -1) for rest in itertools.product(range(field), repeat=rank - top_row - 1) ] return ClassicalCode(np.array(strings).T, field=field) # TODO: add more codes, particularly from code families that are useful for good quantum codes # see https://mhostetter.github.io/galois/latest/api/#forward-error-correction # TODO: # - add method to convert a parity check matrix into standard form # - see https://arxiv.org/abs/1101.1519 # - one method to compute "blocks" of standard form, one to return the matrix itself # - add is_CSS method to figure out whether this is a CSS Code # - see https://quantumcomputing.stackexchange.com/questions/15432/ # - also compute and store sub-codes, if CSS # - also add QuditCode.to_CSS() -> CSSCode class QuditCode(AbstractCode): """Quantum stabilizer code for Galois qudits, with dimension q = p^m for prime p and integer m. The parity check matrix of a QuditCode has dimensions (num_checks, 2 * num_qudits), and can be written as a block matrix in the form H = [H_x|H_z]. Each block has num_qudits columns. The entries H_x[c, d] = r_x and H_z[c, d] = r_z iff check c addresses qudit d with the operator X(r_x) * Z(r_z), where r_x, r_z range over the base field, and X(r), Z(r) are generalized Pauli operators. Specifically: - X(r) = sum_{j=0}^{q-1} |j+r><j| is a shift operator, and - Z(r) = sum_{j=0}^{q-1} w^{j r} |j><j| is a phase operator, with w = exp(2 pi i / q). Warning: here j, r, s, etc. not integers, but elements of the Galois field GF(q), which has different rules for addition and multiplication when q is not a prime number. Helpful lecture by Gottesman: https://www.youtube.com/watch?v=JWg4zrNAF-g """ @property def num_checks(self) -> int: """Number of parity checks (stabilizers) in this code.""" return self.matrix.shape[0] @property def num_qudits(self) -> int: """Number of data qudits in this code.""" return self.matrix.shape[1] // 2 @property def num_qubits(self) -> int: """Number of data qubits in this code.""" self._assert_qubit_code() return self.num_qudits def _assert_qubit_code(self) -> None: if self._field_order != 2: raise ValueError("Attempted to call a qubit-only method with a non-qubit code.") @classmethod def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph: """Convert a parity check matrix into a Tanner graph.""" graph = nx.DiGraph() matrix = np.reshape(matrix, (len(matrix), 2, -1)) for row, col_xz, col in zip(*np.nonzero(matrix)): node_check = Node(index=int(row), is_data=False) node_qudit = Node(index=int(col), is_data=True) graph.add_edge(node_check, node_qudit) qudit_op = graph[node_check][node_qudit].get(QuditOperator, QuditOperator()) vals_xz = list(qudit_op.value) vals_xz[col_xz] += int(matrix[row, col_xz, col]) graph[node_check][node_qudit][QuditOperator] = QuditOperator(tuple(vals_xz)) if isinstance(matrix, galois.FieldArray): graph.order = type(matrix).order return graph @classmethod def graph_to_matrix(cls, graph: nx.DiGraph) -> galois.FieldArray: """Convert a Tanner graph into a parity check matrix.""" num_qudits = sum(1 for node in graph.nodes() if node.is_data) num_checks = len(graph.nodes()) - num_qudits matrix = np.zeros((num_checks, 2, num_qudits), dtype=int) for node_check, node_qudit, data in graph.edges(data=True): matrix[node_check.index, :, node_qudit.index] = data[QuditOperator].value field = graph.order if hasattr(graph, "order") else DEFAULT_FIELD_ORDER return galois.GF(field)(matrix.reshape(num_checks, 2 * num_qudits)) def get_stabilizers(self) -> list[str]: """Stabilizers (checks) of this code, represented by strings.""" matrix = self.matrix.reshape(self.num_checks, 2, self.num_qudits) stabilizers = [] for check in range(self.num_checks): ops = [] for qudit in range(self.num_qudits):
val_x = matrix[check, Pauli.X.index, qudit]
3
2023-12-19 22:29:42+00:00
12k
amazon-science/c2f-seg
src/video_model.py
[ { "identifier": "VQModel", "path": "taming_src/taming_models.py", "snippet": "class VQModel(nn.Module):\n def __init__(self, config):\n super(VQModel, self).__init__()\n self.config = config\n self.iteration = 0\n self.name = config.model_type\n self.m_path = os.pat...
import os import math import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributed as dist from torchvision import transforms from taming_src.taming_models import VQModel from src.video_component import MaskedTransformer, Resnet_Encoder, Refine_Module from src.loss import VGG19, PerceptualLoss from utils.pytorch_optimization import AdamW, get_linear_schedule_with_warmup from utils.utils import torch_show_all_params, torch_init_model from utils.utils import Config from utils.evaluation import video_iou from utils.loss import CrossEntropyLoss from tqdm import tqdm
8,251
class C2F_Seg(nn.Module): def __init__(self, config, g_path, mode, logger=None, save_eval_dict={}): super(C2F_Seg, self).__init__() self.config = config self.iteration = 0 self.sample_iter = 0 self.name = config.model_type # load g model for mask self.g_config = Config(os.path.join(g_path, 'vqgan_{}.yml'.format(config.dataset))) self.g_path = os.path.join(g_path, self.g_config.model_type) self.root_path = config.path self.transformer_path = os.path.join(config.path, self.name) # self.refine_path = os.path.join(config.path, "Refine") self.trans_size = config.trans_size self.mode = mode self.save_eval_dict = save_eval_dict self.eps = 1e-6 self.train_sample_iters = config.train_sample_iters self.g_model = VQModel(self.g_config).to(config.device) self.img_encoder = Resnet_Encoder().to(config.device) self.refine_module = Refine_Module().to(config.device) self.transformer = MaskedTransformer(config).to(config.device) self.g_model.eval() self.refine_criterion = nn.BCELoss() self.criterion = CrossEntropyLoss(num_classes=config.vocab_size+1, device=config.device) if config.train_with_dec: if not config.gumbel_softmax: self.temperature = nn.Parameter(torch.tensor([config.tp], dtype=torch.float32), requires_grad=True).to(config.device) if config.use_vgg: vgg = VGG19(pretrained=True, vgg_norm=config.vgg_norm).to(config.device) vgg.eval() reduction = 'mean' if config.balanced_loss is False else 'none' self.perceptual_loss = PerceptualLoss(vgg, weights=config.vgg_weights, reduction=reduction).to(config.device) else: self.perceptual_loss = None if config.init_gpt_with_vqvae: self.transformer.z_emb.weight = self.g_model.quantize.embedding.weight if logger is not None: logger.info('Gen Parameters:{}'.format(torch_show_all_params(self.g_model))) logger.info('Transformer Parameters:{}'.format(torch_show_all_params(self.transformer))) else: print('Gen Parameters:{}'.format(torch_show_all_params(self.g_model))) print('Transformer Parameters:{}'.format(torch_show_all_params(self.transformer))) # loss no_decay = ['bias', 'ln1.bias', 'ln1.weight', 'ln2.bias', 'ln2.weight'] ignored_param = ['z_emb.weight', 'c_emb.weight'] param_optimizer = self.transformer.named_parameters() param_optimizer_encoder = self.img_encoder.named_parameters() param_optimizer_refine= self.refine_module.named_parameters() optimizer_parameters = [ {'params': [p for n, p in param_optimizer if not any([nd in n for nd in no_decay])], 'weight_decay': config.weight_decay}, {'params': [p for n, p in param_optimizer if any([nd in n for nd in no_decay])], 'weight_decay': 0.0}, {'params': [p for n, p in param_optimizer_encoder], 'weight_decay': config.weight_decay}, {'params': [p for n, p in param_optimizer_refine], 'weight_decay': config.weight_decay}, ] self.opt = AdamW(params=optimizer_parameters, lr=float(config.lr), betas=(config.beta1, config.beta2))
class C2F_Seg(nn.Module): def __init__(self, config, g_path, mode, logger=None, save_eval_dict={}): super(C2F_Seg, self).__init__() self.config = config self.iteration = 0 self.sample_iter = 0 self.name = config.model_type # load g model for mask self.g_config = Config(os.path.join(g_path, 'vqgan_{}.yml'.format(config.dataset))) self.g_path = os.path.join(g_path, self.g_config.model_type) self.root_path = config.path self.transformer_path = os.path.join(config.path, self.name) # self.refine_path = os.path.join(config.path, "Refine") self.trans_size = config.trans_size self.mode = mode self.save_eval_dict = save_eval_dict self.eps = 1e-6 self.train_sample_iters = config.train_sample_iters self.g_model = VQModel(self.g_config).to(config.device) self.img_encoder = Resnet_Encoder().to(config.device) self.refine_module = Refine_Module().to(config.device) self.transformer = MaskedTransformer(config).to(config.device) self.g_model.eval() self.refine_criterion = nn.BCELoss() self.criterion = CrossEntropyLoss(num_classes=config.vocab_size+1, device=config.device) if config.train_with_dec: if not config.gumbel_softmax: self.temperature = nn.Parameter(torch.tensor([config.tp], dtype=torch.float32), requires_grad=True).to(config.device) if config.use_vgg: vgg = VGG19(pretrained=True, vgg_norm=config.vgg_norm).to(config.device) vgg.eval() reduction = 'mean' if config.balanced_loss is False else 'none' self.perceptual_loss = PerceptualLoss(vgg, weights=config.vgg_weights, reduction=reduction).to(config.device) else: self.perceptual_loss = None if config.init_gpt_with_vqvae: self.transformer.z_emb.weight = self.g_model.quantize.embedding.weight if logger is not None: logger.info('Gen Parameters:{}'.format(torch_show_all_params(self.g_model))) logger.info('Transformer Parameters:{}'.format(torch_show_all_params(self.transformer))) else: print('Gen Parameters:{}'.format(torch_show_all_params(self.g_model))) print('Transformer Parameters:{}'.format(torch_show_all_params(self.transformer))) # loss no_decay = ['bias', 'ln1.bias', 'ln1.weight', 'ln2.bias', 'ln2.weight'] ignored_param = ['z_emb.weight', 'c_emb.weight'] param_optimizer = self.transformer.named_parameters() param_optimizer_encoder = self.img_encoder.named_parameters() param_optimizer_refine= self.refine_module.named_parameters() optimizer_parameters = [ {'params': [p for n, p in param_optimizer if not any([nd in n for nd in no_decay])], 'weight_decay': config.weight_decay}, {'params': [p for n, p in param_optimizer if any([nd in n for nd in no_decay])], 'weight_decay': 0.0}, {'params': [p for n, p in param_optimizer_encoder], 'weight_decay': config.weight_decay}, {'params': [p for n, p in param_optimizer_refine], 'weight_decay': config.weight_decay}, ] self.opt = AdamW(params=optimizer_parameters, lr=float(config.lr), betas=(config.beta1, config.beta2))
self.sche = get_linear_schedule_with_warmup(self.opt, num_warmup_steps=config.warmup_iters,
7
2023-12-21 04:25:47+00:00
12k
huahuahuage/Bert-VITS2-Speech
onnx_infer/text/chinese.py
[ { "identifier": "punctuation", "path": "onnx_infer/text/symbols.py", "snippet": "" }, { "identifier": "ToneSandhi", "path": "onnx_infer/text/chinese_tone_sandhi.py", "snippet": "class ToneSandhi:\r\n def __init__(self):\r\n self.must_neural_tone_words = {\r\n \"麻烦\",...
import os import re import cn2an import jieba.posseg as psg from typing import List, Dict from pypinyin import lazy_pinyin, Style from .symbols import punctuation from .chinese_tone_sandhi import ToneSandhi from log import log_instance
8,307
REP_MAP = { ":": ",", ";": ",", ",": ",", "。": ".", "!": "!", "?": "?", "\n": ".", "·": ",", "、": ",", "...": "…", "$": ".", "“": "'", "”": "'", '"': "'", "‘": "'", "’": "'", "(": "'", ")": "'", "(": "'", ")": "'", "《": "'", "》": "'", "【": "'", "】": "'", "[": "'", "]": "'", "—": "-", "~": "-", "~": "-", "「": "'", "」": "'", } class ChineseG2P: def __init__(self) -> None: self.tone_modifier = ToneSandhi() self.pinyin_to_symbol_map: Dict[str, str] = {} self.__read_opencpop_symbol_map() def __read_opencpop_symbol_map(self): """ 取读opencpop数据 """ f = open("onnx/Text/opencpop-strict.txt", "r") for line in f.readlines(): self.pinyin_to_symbol_map[line.split("\t")[0]] = line.strip().split("\t")[1] f.close() @staticmethod def __get_initials_finals(word): initials = [] finals = [] orig_initials = lazy_pinyin( word, neutral_tone_with_five=True, style=Style.INITIALS ) orig_finals = lazy_pinyin( word, neutral_tone_with_five=True, style=Style.FINALS_TONE3 ) for c, v in zip(orig_initials, orig_finals): initials.append(c) finals.append(v) return initials, finals def g2p(self, segments_list: List[str]): phones_list = [] tones_list = [] word2ph = [] for seg in segments_list: seg_cut = psg.lcut(seg) initials = [] finals = [] seg_cut = self.tone_modifier.pre_merge_for_modify(seg_cut) for word, pos in seg_cut: if pos == "eng": continue sub_initials, sub_finals = self.__get_initials_finals(word) sub_finals = self.tone_modifier.modified_tone(word, pos, sub_finals) initials.append(sub_initials) finals.append(sub_finals) # assert len(sub_initials) == len(sub_finals) == len(word) initials = sum(initials, []) finals = sum(finals, []) # for c, v in zip(initials, finals): raw_pinyin = c + v # NOTE: post process for pypinyin outputs # we discriminate i, ii and iii if c == v:
REP_MAP = { ":": ",", ";": ",", ",": ",", "。": ".", "!": "!", "?": "?", "\n": ".", "·": ",", "、": ",", "...": "…", "$": ".", "“": "'", "”": "'", '"': "'", "‘": "'", "’": "'", "(": "'", ")": "'", "(": "'", ")": "'", "《": "'", "》": "'", "【": "'", "】": "'", "[": "'", "]": "'", "—": "-", "~": "-", "~": "-", "「": "'", "」": "'", } class ChineseG2P: def __init__(self) -> None: self.tone_modifier = ToneSandhi() self.pinyin_to_symbol_map: Dict[str, str] = {} self.__read_opencpop_symbol_map() def __read_opencpop_symbol_map(self): """ 取读opencpop数据 """ f = open("onnx/Text/opencpop-strict.txt", "r") for line in f.readlines(): self.pinyin_to_symbol_map[line.split("\t")[0]] = line.strip().split("\t")[1] f.close() @staticmethod def __get_initials_finals(word): initials = [] finals = [] orig_initials = lazy_pinyin( word, neutral_tone_with_five=True, style=Style.INITIALS ) orig_finals = lazy_pinyin( word, neutral_tone_with_five=True, style=Style.FINALS_TONE3 ) for c, v in zip(orig_initials, orig_finals): initials.append(c) finals.append(v) return initials, finals def g2p(self, segments_list: List[str]): phones_list = [] tones_list = [] word2ph = [] for seg in segments_list: seg_cut = psg.lcut(seg) initials = [] finals = [] seg_cut = self.tone_modifier.pre_merge_for_modify(seg_cut) for word, pos in seg_cut: if pos == "eng": continue sub_initials, sub_finals = self.__get_initials_finals(word) sub_finals = self.tone_modifier.modified_tone(word, pos, sub_finals) initials.append(sub_initials) finals.append(sub_finals) # assert len(sub_initials) == len(sub_finals) == len(word) initials = sum(initials, []) finals = sum(finals, []) # for c, v in zip(initials, finals): raw_pinyin = c + v # NOTE: post process for pypinyin outputs # we discriminate i, ii and iii if c == v:
assert c in punctuation
0
2023-12-21 13:50:50+00:00
12k
lipku/metahuman-stream
nerf_triplane/network.py
[ { "identifier": "get_encoder", "path": "encoding.py", "snippet": "def get_encoder(encoding, input_dim=3, \n multires=6, \n degree=4,\n num_levels=16, level_dim=2, base_resolution=16, log2_hashmap_size=19, desired_resolution=2048, align_corners=False,\n ...
import torch import torch.nn as nn import torch.nn.functional as F from encoding import get_encoder from .renderer import NeRFRenderer
9,303
# Audio feature extractor class AudioAttNet(nn.Module): def __init__(self, dim_aud=64, seq_len=8): super(AudioAttNet, self).__init__() self.seq_len = seq_len self.dim_aud = dim_aud self.attentionConvNet = nn.Sequential( # b x subspace_dim x seq_len nn.Conv1d(self.dim_aud, 16, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(16, 8, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(8, 4, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(4, 2, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(2, 1, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True) ) self.attentionNet = nn.Sequential( nn.Linear(in_features=self.seq_len, out_features=self.seq_len, bias=True), nn.Softmax(dim=1) ) def forward(self, x): # x: [1, seq_len, dim_aud] y = x.permute(0, 2, 1) # [1, dim_aud, seq_len] y = self.attentionConvNet(y) y = self.attentionNet(y.view(1, self.seq_len)).view(1, self.seq_len, 1) return torch.sum(y * x, dim=1) # [1, dim_aud] # Audio feature extractor class AudioNet(nn.Module): def __init__(self, dim_in=29, dim_aud=64, win_size=16): super(AudioNet, self).__init__() self.win_size = win_size self.dim_aud = dim_aud self.encoder_conv = nn.Sequential( # n x 29 x 16 nn.Conv1d(dim_in, 32, kernel_size=3, stride=2, padding=1, bias=True), # n x 32 x 8 nn.LeakyReLU(0.02, True), nn.Conv1d(32, 32, kernel_size=3, stride=2, padding=1, bias=True), # n x 32 x 4 nn.LeakyReLU(0.02, True), nn.Conv1d(32, 64, kernel_size=3, stride=2, padding=1, bias=True), # n x 64 x 2 nn.LeakyReLU(0.02, True), nn.Conv1d(64, 64, kernel_size=3, stride=2, padding=1, bias=True), # n x 64 x 1 nn.LeakyReLU(0.02, True), ) self.encoder_fc1 = nn.Sequential( nn.Linear(64, 64), nn.LeakyReLU(0.02, True), nn.Linear(64, dim_aud), ) def forward(self, x): half_w = int(self.win_size/2) x = x[:, :, 8-half_w:8+half_w] x = self.encoder_conv(x).squeeze(-1) x = self.encoder_fc1(x) return x class MLP(nn.Module): def __init__(self, dim_in, dim_out, dim_hidden, num_layers): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dim_hidden = dim_hidden self.num_layers = num_layers net = [] for l in range(num_layers): net.append(nn.Linear(self.dim_in if l == 0 else self.dim_hidden, self.dim_out if l == num_layers - 1 else self.dim_hidden, bias=False)) self.net = nn.ModuleList(net) def forward(self, x): for l in range(self.num_layers): x = self.net[l](x) if l != self.num_layers - 1: x = F.relu(x, inplace=True) # x = F.dropout(x, p=0.1, training=self.training) return x
# Audio feature extractor class AudioAttNet(nn.Module): def __init__(self, dim_aud=64, seq_len=8): super(AudioAttNet, self).__init__() self.seq_len = seq_len self.dim_aud = dim_aud self.attentionConvNet = nn.Sequential( # b x subspace_dim x seq_len nn.Conv1d(self.dim_aud, 16, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(16, 8, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(8, 4, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(4, 2, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True), nn.Conv1d(2, 1, kernel_size=3, stride=1, padding=1, bias=True), nn.LeakyReLU(0.02, True) ) self.attentionNet = nn.Sequential( nn.Linear(in_features=self.seq_len, out_features=self.seq_len, bias=True), nn.Softmax(dim=1) ) def forward(self, x): # x: [1, seq_len, dim_aud] y = x.permute(0, 2, 1) # [1, dim_aud, seq_len] y = self.attentionConvNet(y) y = self.attentionNet(y.view(1, self.seq_len)).view(1, self.seq_len, 1) return torch.sum(y * x, dim=1) # [1, dim_aud] # Audio feature extractor class AudioNet(nn.Module): def __init__(self, dim_in=29, dim_aud=64, win_size=16): super(AudioNet, self).__init__() self.win_size = win_size self.dim_aud = dim_aud self.encoder_conv = nn.Sequential( # n x 29 x 16 nn.Conv1d(dim_in, 32, kernel_size=3, stride=2, padding=1, bias=True), # n x 32 x 8 nn.LeakyReLU(0.02, True), nn.Conv1d(32, 32, kernel_size=3, stride=2, padding=1, bias=True), # n x 32 x 4 nn.LeakyReLU(0.02, True), nn.Conv1d(32, 64, kernel_size=3, stride=2, padding=1, bias=True), # n x 64 x 2 nn.LeakyReLU(0.02, True), nn.Conv1d(64, 64, kernel_size=3, stride=2, padding=1, bias=True), # n x 64 x 1 nn.LeakyReLU(0.02, True), ) self.encoder_fc1 = nn.Sequential( nn.Linear(64, 64), nn.LeakyReLU(0.02, True), nn.Linear(64, dim_aud), ) def forward(self, x): half_w = int(self.win_size/2) x = x[:, :, 8-half_w:8+half_w] x = self.encoder_conv(x).squeeze(-1) x = self.encoder_fc1(x) return x class MLP(nn.Module): def __init__(self, dim_in, dim_out, dim_hidden, num_layers): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dim_hidden = dim_hidden self.num_layers = num_layers net = [] for l in range(num_layers): net.append(nn.Linear(self.dim_in if l == 0 else self.dim_hidden, self.dim_out if l == num_layers - 1 else self.dim_hidden, bias=False)) self.net = nn.ModuleList(net) def forward(self, x): for l in range(self.num_layers): x = self.net[l](x) if l != self.num_layers - 1: x = F.relu(x, inplace=True) # x = F.dropout(x, p=0.1, training=self.training) return x
class NeRFNetwork(NeRFRenderer):
1
2023-12-19 01:32:46+00:00
12k
MingtaoGuo/AnimateAnyone_unofficial
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, 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
9,741
""" 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)
""" 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)
6
2023-12-16 03:31:33+00:00
12k
modelscope/scepter
scepter/modules/model/backbone/image/vit_modify.py
[ { "identifier": "MULTI_HEAD_VIT_MODEL", "path": "scepter/modules/model/backbone/image/utils/vit.py", "snippet": "class MULTI_HEAD_VIT_MODEL(nn.Module):\n para_dict = {\n 'INPUT_RESOLUTION': {\n 'value': 224,\n 'description': 'The input resolution of vit model!'\n }...
import torch import torch.nn as nn from scepter.modules.model.backbone.image.utils.vit import ( MULTI_HEAD_VIT_MODEL, VIT, VIT_MODEL, MULTI_HEAD_VIT_MODEL_Split) from scepter.modules.model.base_model import BaseModel from scepter.modules.model.registry import BACKBONES from scepter.modules.utils.config import dict_to_yaml from scepter.modules.utils.file_system import FS
9,573
'description': 'The frozen layers number!' }, 'FT_LAYERS': { 'value': 6, 'description': 'The finetune layers number!' } } para_dict.update(VIT_MODEL.para_dict) def __init__(self, cfg, logger=None): super().__init__(cfg, logger=logger) self.pretrain_path = cfg.PRETRAIN_PATH self.pretrained = cfg.PRETRAINED self.visual = VIT_MODEL(cfg) self.frozen_layers = cfg.FROZEN_LAYERS self.ft_layers = cfg.FT_LAYERS if self.pretrained: with FS.get_from(self.pretrain_path, wait_finish=True) as local_file: logger.info(f'Loading checkpoint from {self.pretrain_path}') visual_pre = torch.load(local_file, map_location='cpu') state_dict_update = self.reformat_state_dict(visual_pre) self.visual.load_state_dict(state_dict_update, strict=True) def reformat_state_dict(self, state_dict): state_dict_update = {} for k, v in state_dict.items(): if 'transformer.resblocks.' in k: if int(k.split('.')[2]) < self.frozen_layers: state_dict_update[k.replace( 'transformer.resblocks', 'frozen_transformer.resblocks')] = v else: new_k = k.replace('transformer.resblocks', 'ft_transformer.resblocks') k_tups = new_k.split('.') k_tups[2] = str(int(k_tups[2]) - self.frozen_layers) new_k = '.'.join(k_tups) state_dict_update[new_k] = v else: state_dict_update[k] = v return state_dict_update def forward(self, x): out = self.visual.forward(x) return out @staticmethod def get_config_template(): ''' { "ENV" : { "description" : "", "A" : { "value": 1.0, "description": "" } } } :return: ''' return dict_to_yaml('BACKBONES', __class__.__name__, SomeFTVisualTransformer.para_dict, set_name=True) @BACKBONES.register_class() class MultiHeadSomeFTVisualTransformer(BaseModel): ''' INPUT_RESOLUTION: 224 PATCH_SIZE: 32 WIDTH: 768 OUTPUT_DIM: 512 LAYERS: 12 HEADS: 12 ''' para_dict = {} para_dict.update(MULTI_HEAD_VIT_MODEL.para_dict) def __init__(self, cfg, logger=None): super().__init__(cfg, logger=logger) self.visual = MULTI_HEAD_VIT_MODEL(cfg) self.multi_head = cfg.MULTI_HEAD self.frozen_layers = cfg.FROZEN_LAYERS self.ft_layers = cfg.FT_LAYERS def forward(self, x): out = self.visual.forward(x) return out @staticmethod def get_config_template(): ''' { "ENV" : { "description" : "", "A" : { "value": 1.0, "description": "" } } } :return: ''' return dict_to_yaml('BACKBONES', __class__.__name__, MultiHeadSomeFTVisualTransformer.para_dict, set_name=True) @BACKBONES.register_class() class SomeFTVisualTransformerTwoPart(BaseModel): ''' INPUT_RESOLUTION: 224 PATCH_SIZE: 32 WIDTH: 768 OUTPUT_DIM: 512 LAYERS: 12 HEADS: 12 ''' para_dict = {}
# -*- coding: utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. def convert_weights(model: nn.Module): """Convert applicable model parameters to fp16""" def _convert_weights_to_fp16(layer): if isinstance(layer, (nn.Conv1d, nn.Conv2d, nn.Linear)): layer.weight.data = layer.weight.data.half() if layer.bias is not None: layer.bias.data = layer.bias.data.half() if isinstance(layer, nn.MultiheadAttention): for attr in [ *[f'{s}_proj_weight' for s in ['in', 'q', 'k', 'v']], 'in_proj_bias', 'bias_k', 'bias_v' ]: tensor = getattr(layer, attr) if tensor is not None: tensor.data = tensor.data.half() for name in ['text_projection', 'proj']: if hasattr(layer, name): attr = getattr(layer, name) if attr is not None: attr.data = attr.data.half() model.apply(_convert_weights_to_fp16) @BACKBONES.register_class() class VisualTransformer(BaseModel): ''' B/16: Input 224 Patch-size 16 Layers 12 Heads 12 WIDTH 768 B/32: Input 224 Patch-size 32 Layers 12 Heads 12 WIDTH 768 L/16: Input 224/336 Patch-size 16 Layers 24 Heads 16 WIDTH 1024 L/14: Input 224/336 Patch-size 14 Layers 24 Heads 16 WIDTH 1024 L/32: Input 224 Patch-size 32 Layers 24 Heads 16 WIDTH 1024 H/14: Input ... INPUT_RESOLUTION: 224 PATCH_SIZE: 32 WIDTH: 768 OUTPUT_DIM: 512 LAYERS: 12 HEADS: 12 ''' para_dict = { 'PRETRAIN_PATH': { 'value': '', 'description': 'The file path of pretrained model!' }, 'PRETRAINED': { 'value': True, 'description': 'Use the pretrained model or not!' } } para_dict.update(VIT.para_dict) def __init__(self, cfg, logger=None): super().__init__(cfg, logger=logger) self.pretrain_path = cfg.PRETRAIN_PATH self.pretrained = cfg.PRETRAINED self.visual = VIT(cfg) use_proj = cfg.get('USE_PROJ', True) if self.pretrained: with FS.get_from(self.pretrain_path, wait_finish=True) as local_file: logger.info(f'Loading checkpoint from {self.pretrain_path}') visual_pre = torch.load(local_file, map_location='cpu') if not use_proj: visual_pre.pop('proj') if visual_pre['conv1.weight'].dtype == torch.float16: convert_weights(self.visual) self.visual.load_state_dict(visual_pre, strict=True) def forward(self, x): out = self.visual.forward(x) return out @staticmethod def get_config_template(): ''' { "ENV" : { "description" : "", "A" : { "value": 1.0, "description": "" } } } :return: ''' return dict_to_yaml('BACKBONES', __class__.__name__, VisualTransformer.para_dict, set_name=True) @BACKBONES.register_class() class SomeFTVisualTransformer(BaseModel): ''' INPUT_RESOLUTION: 224 PATCH_SIZE: 32 WIDTH: 768 OUTPUT_DIM: 512 LAYERS: 12 HEADS: 12 ''' para_dict = { 'PRETRAIN_PATH': { 'value': '', 'description': 'The file path of pretrained model!' }, 'PRETRAINED': { 'value': True, 'description': 'Use the pretrained model or not!' }, 'FROZEN_LAYERS': { 'value': 6, 'description': 'The frozen layers number!' }, 'FT_LAYERS': { 'value': 6, 'description': 'The finetune layers number!' } } para_dict.update(VIT_MODEL.para_dict) def __init__(self, cfg, logger=None): super().__init__(cfg, logger=logger) self.pretrain_path = cfg.PRETRAIN_PATH self.pretrained = cfg.PRETRAINED self.visual = VIT_MODEL(cfg) self.frozen_layers = cfg.FROZEN_LAYERS self.ft_layers = cfg.FT_LAYERS if self.pretrained: with FS.get_from(self.pretrain_path, wait_finish=True) as local_file: logger.info(f'Loading checkpoint from {self.pretrain_path}') visual_pre = torch.load(local_file, map_location='cpu') state_dict_update = self.reformat_state_dict(visual_pre) self.visual.load_state_dict(state_dict_update, strict=True) def reformat_state_dict(self, state_dict): state_dict_update = {} for k, v in state_dict.items(): if 'transformer.resblocks.' in k: if int(k.split('.')[2]) < self.frozen_layers: state_dict_update[k.replace( 'transformer.resblocks', 'frozen_transformer.resblocks')] = v else: new_k = k.replace('transformer.resblocks', 'ft_transformer.resblocks') k_tups = new_k.split('.') k_tups[2] = str(int(k_tups[2]) - self.frozen_layers) new_k = '.'.join(k_tups) state_dict_update[new_k] = v else: state_dict_update[k] = v return state_dict_update def forward(self, x): out = self.visual.forward(x) return out @staticmethod def get_config_template(): ''' { "ENV" : { "description" : "", "A" : { "value": 1.0, "description": "" } } } :return: ''' return dict_to_yaml('BACKBONES', __class__.__name__, SomeFTVisualTransformer.para_dict, set_name=True) @BACKBONES.register_class() class MultiHeadSomeFTVisualTransformer(BaseModel): ''' INPUT_RESOLUTION: 224 PATCH_SIZE: 32 WIDTH: 768 OUTPUT_DIM: 512 LAYERS: 12 HEADS: 12 ''' para_dict = {} para_dict.update(MULTI_HEAD_VIT_MODEL.para_dict) def __init__(self, cfg, logger=None): super().__init__(cfg, logger=logger) self.visual = MULTI_HEAD_VIT_MODEL(cfg) self.multi_head = cfg.MULTI_HEAD self.frozen_layers = cfg.FROZEN_LAYERS self.ft_layers = cfg.FT_LAYERS def forward(self, x): out = self.visual.forward(x) return out @staticmethod def get_config_template(): ''' { "ENV" : { "description" : "", "A" : { "value": 1.0, "description": "" } } } :return: ''' return dict_to_yaml('BACKBONES', __class__.__name__, MultiHeadSomeFTVisualTransformer.para_dict, set_name=True) @BACKBONES.register_class() class SomeFTVisualTransformerTwoPart(BaseModel): ''' INPUT_RESOLUTION: 224 PATCH_SIZE: 32 WIDTH: 768 OUTPUT_DIM: 512 LAYERS: 12 HEADS: 12 ''' para_dict = {}
para_dict.update(MULTI_HEAD_VIT_MODEL_Split.para_dict)
3
2023-12-21 02:01:48+00:00
12k
pigeonai-org/ViDove
src/task.py
[ { "identifier": "SrtScript", "path": "src/srt_util/srt.py", "snippet": "class SrtScript(object):\n def __init__(self, src_lang, tgt_lang, segments, domain=\"General\") -> None:\n self.domain = domain\n self.src_lang = src_lang\n self.tgt_lang = tgt_lang\n self.segments = [...
import threading import time import openai import logging import subprocess import torch import stable_whisper import shutil from pytube import YouTube from os import getenv, getcwd from pathlib import Path from enum import Enum, auto from src.srt_util.srt import SrtScript from src.srt_util.srt2ass import srt2ass from time import time, strftime, gmtime, sleep from src.translators.translation import get_translation, prompt_selector from datetime import datetime
8,219
def __init__(self, task_id, task_local_dir, task_cfg): """ Constructor for initializing a task with its ID, local directory, and configuration settings. """ self.__status_lock = threading.Lock() self.__status = TaskStatus.CREATED self.gpu_status = 0 openai.api_key = getenv("OPENAI_API_KEY") self.task_id = task_id self.task_local_dir = task_local_dir self.ASR_setting = task_cfg["ASR"] self.translation_setting = task_cfg["translation"] self.translation_model = self.translation_setting["model"] self.output_type = task_cfg["output_type"] self.target_lang = task_cfg["target_lang"] self.source_lang = task_cfg["source_lang"] self.field = task_cfg["field"] self.pre_setting = task_cfg["pre_process"] self.post_setting = task_cfg["post_process"] self.audio_path = None self.SRT_Script = None self.result = None self.s_t = None self.t_e = None self.t_s = time() # logging setting logfmt = "%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s" logging.basicConfig(level=logging.INFO, format=logfmt, handlers=[ logging.FileHandler( "{}/{}_{}.log".format(task_local_dir, f"task_{task_id}", datetime.now().strftime("%m%d%Y_%H%M%S")), 'w', encoding='utf-8')]) print(f"Task ID: {self.task_id}") logging.info(f"Task ID: {self.task_id}") logging.info(f"{self.source_lang} -> {self.target_lang} task in {self.field}") logging.info(f"Translation Model: {self.translation_model}") logging.info(f"subtitle_type: {self.output_type['subtitle']}") logging.info(f"video_ouput: {self.output_type['video']}") logging.info(f"bilingual_ouput: {self.output_type['bilingual']}") logging.info("Pre-process setting:") for key in self.pre_setting: logging.info(f"{key}: {self.pre_setting[key]}") logging.info("Post-process setting:") for key in self.post_setting: logging.info(f"{key}: {self.post_setting[key]}") @staticmethod def fromYoutubeLink(youtube_url, task_id, task_dir, task_cfg): """ Creates a YoutubeTask instance from a YouTube URL. """ return YoutubeTask(task_id, task_dir, task_cfg, youtube_url) @staticmethod def fromAudioFile(audio_path, task_id, task_dir, task_cfg): """ Creates an AudioTask instance from an audio file path. """ return AudioTask(task_id, task_dir, task_cfg, audio_path) @staticmethod def fromVideoFile(video_path, task_id, task_dir, task_cfg): """ Creates a VideoTask instance from a video file path. """ return VideoTask(task_id, task_dir, task_cfg, video_path) @staticmethod def fromSRTFile(srt_path, task_id, task_dir, task_cfg): """ Creates a SRTTask instance from a srt file path. """ return SRTTask(task_id, task_dir, task_cfg, srt_path) # Module 1 ASR: audio --> SRT_script def get_srt_class(self): """ Handles the ASR module to convert audio to SRT script format. """ # Instead of using the script_en variable directly, we'll use script_input # TODO: setup ASR module like translator self.status = TaskStatus.INITIALIZING_ASR if self.SRT_Script != None: logging.info("SRT input mode, skip ASR Module") return method = self.ASR_setting["whisper_config"]["method"] whisper_model = self.ASR_setting["whisper_config"]["whisper_model"] src_srt_path = self.task_local_dir.joinpath(f"task_{self.task_id}_{self.source_lang}.srt") if not Path.exists(src_srt_path): # extract script from audio logging.info("extract script from audio") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logging.info(f"Module 1: ASR inference method: {method}") init_prompt = "Hello, welcome to my lecture." if self.source_lang == "EN" else "" if method == "api": with open(self.audio_path, 'rb') as audio_file: transcript = openai.Audio.transcribe(model="whisper-1", file=audio_file, response_format="srt", language=self.source_lang.lower(), prompt=init_prompt) elif method == "stable": model = stable_whisper.load_model(whisper_model, device) transcript = model.transcribe(str(self.audio_path), regroup=False, initial_prompt=init_prompt) ( transcript .split_by_punctuation(['.', '。', '?']) .merge_by_gap(.15, max_words=3) .merge_by_punctuation([' ']) .split_by_punctuation(['.', '。', '?']) ) transcript = transcript.to_dict() transcript = transcript['segments'] # after get the transcript, release the gpu resource torch.cuda.empty_cache() else: raise RuntimeError(f"unavaliable ASR inference method: {method}") if isinstance(transcript, str):
class TaskStatus(str, Enum): """ An enumeration class representing the different statuses a task can have in the translation pipeline. TODO: add translation progress indicator (%). """ CREATED = 'CREATED' INITIALIZING_ASR = 'INITIALIZING_ASR' PRE_PROCESSING = 'PRE_PROCESSING' TRANSLATING = 'TRANSLATING' POST_PROCESSING = 'POST_PROCESSING' OUTPUT_MODULE = 'OUTPUT_MODULE' class Task: """ A class representing a task in the translation pipeline. It includes methods for handling different stages of the task. If one want to add a new entry type (e.g. add support for different video formats), one should extend this class and override the `run` method. """ @property def status(self): with self.__status_lock: return self.__status @status.setter def status(self, new_status): """ Sets the new status of the task, ensuring thread safety with a lock. """ with self.__status_lock: self.__status = new_status def __init__(self, task_id, task_local_dir, task_cfg): """ Constructor for initializing a task with its ID, local directory, and configuration settings. """ self.__status_lock = threading.Lock() self.__status = TaskStatus.CREATED self.gpu_status = 0 openai.api_key = getenv("OPENAI_API_KEY") self.task_id = task_id self.task_local_dir = task_local_dir self.ASR_setting = task_cfg["ASR"] self.translation_setting = task_cfg["translation"] self.translation_model = self.translation_setting["model"] self.output_type = task_cfg["output_type"] self.target_lang = task_cfg["target_lang"] self.source_lang = task_cfg["source_lang"] self.field = task_cfg["field"] self.pre_setting = task_cfg["pre_process"] self.post_setting = task_cfg["post_process"] self.audio_path = None self.SRT_Script = None self.result = None self.s_t = None self.t_e = None self.t_s = time() # logging setting logfmt = "%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s" logging.basicConfig(level=logging.INFO, format=logfmt, handlers=[ logging.FileHandler( "{}/{}_{}.log".format(task_local_dir, f"task_{task_id}", datetime.now().strftime("%m%d%Y_%H%M%S")), 'w', encoding='utf-8')]) print(f"Task ID: {self.task_id}") logging.info(f"Task ID: {self.task_id}") logging.info(f"{self.source_lang} -> {self.target_lang} task in {self.field}") logging.info(f"Translation Model: {self.translation_model}") logging.info(f"subtitle_type: {self.output_type['subtitle']}") logging.info(f"video_ouput: {self.output_type['video']}") logging.info(f"bilingual_ouput: {self.output_type['bilingual']}") logging.info("Pre-process setting:") for key in self.pre_setting: logging.info(f"{key}: {self.pre_setting[key]}") logging.info("Post-process setting:") for key in self.post_setting: logging.info(f"{key}: {self.post_setting[key]}") @staticmethod def fromYoutubeLink(youtube_url, task_id, task_dir, task_cfg): """ Creates a YoutubeTask instance from a YouTube URL. """ return YoutubeTask(task_id, task_dir, task_cfg, youtube_url) @staticmethod def fromAudioFile(audio_path, task_id, task_dir, task_cfg): """ Creates an AudioTask instance from an audio file path. """ return AudioTask(task_id, task_dir, task_cfg, audio_path) @staticmethod def fromVideoFile(video_path, task_id, task_dir, task_cfg): """ Creates a VideoTask instance from a video file path. """ return VideoTask(task_id, task_dir, task_cfg, video_path) @staticmethod def fromSRTFile(srt_path, task_id, task_dir, task_cfg): """ Creates a SRTTask instance from a srt file path. """ return SRTTask(task_id, task_dir, task_cfg, srt_path) # Module 1 ASR: audio --> SRT_script def get_srt_class(self): """ Handles the ASR module to convert audio to SRT script format. """ # Instead of using the script_en variable directly, we'll use script_input # TODO: setup ASR module like translator self.status = TaskStatus.INITIALIZING_ASR if self.SRT_Script != None: logging.info("SRT input mode, skip ASR Module") return method = self.ASR_setting["whisper_config"]["method"] whisper_model = self.ASR_setting["whisper_config"]["whisper_model"] src_srt_path = self.task_local_dir.joinpath(f"task_{self.task_id}_{self.source_lang}.srt") if not Path.exists(src_srt_path): # extract script from audio logging.info("extract script from audio") device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logging.info(f"Module 1: ASR inference method: {method}") init_prompt = "Hello, welcome to my lecture." if self.source_lang == "EN" else "" if method == "api": with open(self.audio_path, 'rb') as audio_file: transcript = openai.Audio.transcribe(model="whisper-1", file=audio_file, response_format="srt", language=self.source_lang.lower(), prompt=init_prompt) elif method == "stable": model = stable_whisper.load_model(whisper_model, device) transcript = model.transcribe(str(self.audio_path), regroup=False, initial_prompt=init_prompt) ( transcript .split_by_punctuation(['.', '。', '?']) .merge_by_gap(.15, max_words=3) .merge_by_punctuation([' ']) .split_by_punctuation(['.', '。', '?']) ) transcript = transcript.to_dict() transcript = transcript['segments'] # after get the transcript, release the gpu resource torch.cuda.empty_cache() else: raise RuntimeError(f"unavaliable ASR inference method: {method}") if isinstance(transcript, str):
self.SRT_Script = SrtScript.parse_from_srt_file(self.source_lang, self.target_lang, domain = self.field, srt_str = transcript.rstrip())
0
2023-12-20 01:46:47+00:00
12k
YyzHarry/shortcut-ood-fairness
train.py
[ { "identifier": "datasets", "path": "dataset/datasets.py", "snippet": "DATASETS = [\n 'MIMIC',\n 'CheXpert',\n 'NIH',\n 'PadChest',\n 'VinDr',\n 'SIIM',\n 'ISIC',\n 'ODIR'\n]\nCXR_DATASETS = [\n 'MIMIC',\n 'CheXpert',\n 'NIH',\n 'PadChest',\n 'VinDr',\n 'SIIM'\n...
import argparse import collections import json import os import random import sys import time import numpy as np import pandas as pd import PIL import torch import torchvision import torch.utils.data import pickle import hparams_registry import wandb import hashlib from tensorboard_logger import Logger from pathlib import Path from torch.utils.data import DataLoader from dataset import datasets from learning import algorithms, early_stopping, swad_utils from utils import misc, eval_helper from dataset.fast_dataloader import InfiniteDataLoader from collections import OrderedDict
7,344
args = parser.parse_args() start_step = 0 misc.prepare_folders(args) output_dir = os.path.join(args.output_dir, args.store_name) if not args.debug: sys.stdout = misc.Tee(os.path.join(output_dir, 'out.txt')) sys.stderr = misc.Tee(os.path.join(output_dir, 'err.txt')) tb_logger = Logger(logdir=output_dir, flush_secs=2) print("Environment:") print("\tPython: {}".format(sys.version.split(" ")[0])) print("\tPyTorch: {}".format(torch.__version__)) print("\tTorchvision: {}".format(torchvision.__version__)) print("\tCUDA: {}".format(torch.version.cuda)) print("\tCUDNN: {}".format(torch.backends.cudnn.version())) print("\tNumPy: {}".format(np.__version__)) print("\tPIL: {}".format(PIL.__version__)) print('Args:') for k, v in sorted(vars(args).items()): print('\t{}: {}'.format(k, v)) if args.hparams_seed == 0: hparams = hparams_registry.default_hparams(args.algorithm, args.dataset) else: hparams = hparams_registry.random_hparams(args.algorithm, args.dataset, misc.seed_hash(args.hparams_seed)) if args.hparams: hparams.update(json.loads(args.hparams)) hparams.update({ 'image_arch': args.image_arch, 'data_augmentation': args.aug, 'task': args.task, 'attr': args.attr, 'group_def': args.group_def }) if args.log_online: wandb.init(project='subpop_fairness', config={**vars(args), **hparams}, name=f"train_{args.dataset}_{args.task}_{args.algorithm}_{args.attr}_" f"{hashlib.md5(str({**vars(args), **hparams}).encode('utf-8')).hexdigest()[:8]}_" f"{os.environ['SLURM_JOB_ID'] if 'SLURM_JOB_ID' in os.environ else ''}") print('HParams:') for k, v in sorted(hparams.items()): print('\t{}: {}'.format(k, v)) with open(os.path.join(output_dir, 'args.json'), 'w') as f: json.dump(vars(args), f, indent=4) random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False os.environ["TOKENIZERS_PARALLELISM"] = "false" torch.multiprocessing.set_sharing_strategy('file_system') device = "cuda" if torch.cuda.is_available() else "cpu" def make_combined_dataset(names, sset, group_def, override_attr=None): ind_datasets = [] for ds in names: ind_datasets.append(vars(datasets)[ds](args.data_dir, sset, hparams, group_def=group_def, override_attr=override_attr)) return datasets.ConcatImageDataset(ind_datasets) if len(args.dataset) == 1: if args.dataset[0] in vars(datasets): train_dataset = vars(datasets)[args.dataset[0]](args.data_dir, 'tr', hparams, group_def=args.group_def) val_dataset = vars(datasets)[args.dataset[0]](args.data_dir, 'va', hparams, group_def='group') test_dataset = vars(datasets)[args.dataset[0]](args.data_dir, 'te', hparams, group_def='group') else: raise NotImplementedError else: train_dataset = make_combined_dataset(args.dataset, 'tr', args.group_def) val_dataset = make_combined_dataset(args.dataset, 'va', 'group') test_dataset = make_combined_dataset(args.dataset, 'te', 'group') if args.algorithm == 'DFR': train_datasets = [] for ds in args.dataset: train_datasets.append(vars(datasets)[ds]( args.data_dir, 'va', hparams, group_def=args.group_def, subsample_type='group')) train_dataset = datasets.ConcatImageDataset(train_datasets) elif args.algorithm == 'StratifiedERM': assert args.stratified_erm_subset is not None train_dataset = datasets.SubsetImageDataset( train_dataset, idxs=np.argwhere(np.array(train_dataset.a) == args.stratified_erm_subset).squeeze()) val_dataset = datasets.SubsetImageDataset( val_dataset, idxs=np.argwhere(np.array(val_dataset.a) == args.stratified_erm_subset).squeeze()) test_dataset = datasets.SubsetImageDataset( test_dataset, idxs=np.argwhere(np.array(test_dataset.a) == args.stratified_erm_subset).squeeze()) num_workers = train_dataset.N_WORKERS input_shape = train_dataset.INPUT_SHAPE num_labels = train_dataset.num_labels num_attributes = train_dataset.num_attributes data_type = train_dataset.data_type n_steps = args.steps or train_dataset.N_STEPS checkpoint_freq = args.checkpoint_freq or train_dataset.CHECKPOINT_FREQ hparams.update({ "steps": n_steps }) print(f"Dataset:\n\t[train]\t{len(train_dataset)}" f"\n\t[val]\t{len(val_dataset)}") if hparams['group_balanced']: # if attribute not available, groups degenerate to classes train_weights = np.asarray(train_dataset.weights_g) train_weights /= np.sum(train_weights) elif hparams['attr_balanced']: train_weights = np.asarray(train_dataset.weights_a) train_weights /= np.sum(train_weights) else: train_weights = None
if __name__ == "__main__": parser = argparse.ArgumentParser(description='Shortcut Learning in Chest X-rays') # training parser.add_argument('--store_name', type=str, default='debug') parser.add_argument('--dataset', type=str, default=["MIMIC"], nargs='+') parser.add_argument('--task', type=str, default="No Finding", choices=datasets.TASKS + datasets.ATTRS) parser.add_argument('--attr', type=str, default="sex", choices=datasets.ATTRS) parser.add_argument('--group_def', type=str, default="group", choices=['group', 'label']) parser.add_argument('--algorithm', type=str, default="ERM", choices=algorithms.ALGORITHMS) # others parser.add_argument('--output_dir', type=str, default='output') parser.add_argument('--data_dir', type=str, default='data') parser.add_argument('--hparams', type=str, help='JSON-serialized hparams dict') parser.add_argument('--hparams_seed', type=int, default=0, help='Seed for random hparams (0 for "default hparams")') parser.add_argument('--seed', type=int, default=0, help='Seed for everything else') parser.add_argument('--steps', type=int, default=None) parser.add_argument('--log_online', help='Log online using wandb', action='store_true') parser.add_argument('--skip_ood_eval', help='skip evals on OOD datasets', action='store_true') parser.add_argument('--log_all', help='Log all val metrics at each step to tb and wandb', action='store_true') parser.add_argument('--stratified_erm_subset', type=int, default=None) # two-stage related parser.add_argument('--stage1_folder', type=str) # early stopping parser.add_argument('--use_es', action='store_true') parser.add_argument('--es_strategy', choices=['metric'], default='metric') parser.add_argument('--es_metric', type=str, default='min_group:accuracy') parser.add_argument('--es_patience', type=int, default=5, help='Stop after this many checkpoints w/ no improvement') # checkpoints parser.add_argument('--resume', '-r', type=str, default='') parser.add_argument('--checkpoint_freq', type=int, default=None, help='Checkpoint every N steps') parser.add_argument('--skip_model_save', action='store_true') parser.add_argument('--debug', action='store_true') # architectures and pre-training sources parser.add_argument('--image_arch', default='densenet_sup_in1k', choices=['densenet_sup_in1k', 'resnet_sup_in1k', 'resnet_sup_in21k', 'resnet_simclr_in1k', 'resnet_barlow_in1k', 'vit_sup_in1k', 'vit_sup_in21k', 'vit_sup_swag', 'vit_clip_oai', 'vit_clip_laion', 'vit_dino_in1k', 'resnet_dino_in1k']) # data augmentations parser.add_argument('--aug', default='basic2', choices=['none', 'basic', 'basic2', 'auto_aug', 'rand_aug', 'trivial_aug', 'augmix']) args = parser.parse_args() start_step = 0 misc.prepare_folders(args) output_dir = os.path.join(args.output_dir, args.store_name) if not args.debug: sys.stdout = misc.Tee(os.path.join(output_dir, 'out.txt')) sys.stderr = misc.Tee(os.path.join(output_dir, 'err.txt')) tb_logger = Logger(logdir=output_dir, flush_secs=2) print("Environment:") print("\tPython: {}".format(sys.version.split(" ")[0])) print("\tPyTorch: {}".format(torch.__version__)) print("\tTorchvision: {}".format(torchvision.__version__)) print("\tCUDA: {}".format(torch.version.cuda)) print("\tCUDNN: {}".format(torch.backends.cudnn.version())) print("\tNumPy: {}".format(np.__version__)) print("\tPIL: {}".format(PIL.__version__)) print('Args:') for k, v in sorted(vars(args).items()): print('\t{}: {}'.format(k, v)) if args.hparams_seed == 0: hparams = hparams_registry.default_hparams(args.algorithm, args.dataset) else: hparams = hparams_registry.random_hparams(args.algorithm, args.dataset, misc.seed_hash(args.hparams_seed)) if args.hparams: hparams.update(json.loads(args.hparams)) hparams.update({ 'image_arch': args.image_arch, 'data_augmentation': args.aug, 'task': args.task, 'attr': args.attr, 'group_def': args.group_def }) if args.log_online: wandb.init(project='subpop_fairness', config={**vars(args), **hparams}, name=f"train_{args.dataset}_{args.task}_{args.algorithm}_{args.attr}_" f"{hashlib.md5(str({**vars(args), **hparams}).encode('utf-8')).hexdigest()[:8]}_" f"{os.environ['SLURM_JOB_ID'] if 'SLURM_JOB_ID' in os.environ else ''}") print('HParams:') for k, v in sorted(hparams.items()): print('\t{}: {}'.format(k, v)) with open(os.path.join(output_dir, 'args.json'), 'w') as f: json.dump(vars(args), f, indent=4) random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False os.environ["TOKENIZERS_PARALLELISM"] = "false" torch.multiprocessing.set_sharing_strategy('file_system') device = "cuda" if torch.cuda.is_available() else "cpu" def make_combined_dataset(names, sset, group_def, override_attr=None): ind_datasets = [] for ds in names: ind_datasets.append(vars(datasets)[ds](args.data_dir, sset, hparams, group_def=group_def, override_attr=override_attr)) return datasets.ConcatImageDataset(ind_datasets) if len(args.dataset) == 1: if args.dataset[0] in vars(datasets): train_dataset = vars(datasets)[args.dataset[0]](args.data_dir, 'tr', hparams, group_def=args.group_def) val_dataset = vars(datasets)[args.dataset[0]](args.data_dir, 'va', hparams, group_def='group') test_dataset = vars(datasets)[args.dataset[0]](args.data_dir, 'te', hparams, group_def='group') else: raise NotImplementedError else: train_dataset = make_combined_dataset(args.dataset, 'tr', args.group_def) val_dataset = make_combined_dataset(args.dataset, 'va', 'group') test_dataset = make_combined_dataset(args.dataset, 'te', 'group') if args.algorithm == 'DFR': train_datasets = [] for ds in args.dataset: train_datasets.append(vars(datasets)[ds]( args.data_dir, 'va', hparams, group_def=args.group_def, subsample_type='group')) train_dataset = datasets.ConcatImageDataset(train_datasets) elif args.algorithm == 'StratifiedERM': assert args.stratified_erm_subset is not None train_dataset = datasets.SubsetImageDataset( train_dataset, idxs=np.argwhere(np.array(train_dataset.a) == args.stratified_erm_subset).squeeze()) val_dataset = datasets.SubsetImageDataset( val_dataset, idxs=np.argwhere(np.array(val_dataset.a) == args.stratified_erm_subset).squeeze()) test_dataset = datasets.SubsetImageDataset( test_dataset, idxs=np.argwhere(np.array(test_dataset.a) == args.stratified_erm_subset).squeeze()) num_workers = train_dataset.N_WORKERS input_shape = train_dataset.INPUT_SHAPE num_labels = train_dataset.num_labels num_attributes = train_dataset.num_attributes data_type = train_dataset.data_type n_steps = args.steps or train_dataset.N_STEPS checkpoint_freq = args.checkpoint_freq or train_dataset.CHECKPOINT_FREQ hparams.update({ "steps": n_steps }) print(f"Dataset:\n\t[train]\t{len(train_dataset)}" f"\n\t[val]\t{len(val_dataset)}") if hparams['group_balanced']: # if attribute not available, groups degenerate to classes train_weights = np.asarray(train_dataset.weights_g) train_weights /= np.sum(train_weights) elif hparams['attr_balanced']: train_weights = np.asarray(train_dataset.weights_a) train_weights /= np.sum(train_weights) else: train_weights = None
train_loader = InfiniteDataLoader(
6
2023-12-15 04:10:31+00:00
12k
RomGai/BrainVis
main.py
[ { "identifier": "args", "path": "args.py", "snippet": "" }, { "identifier": "Dataset", "path": "dataset.py", "snippet": "class Dataset(Data.Dataset):\n def __init__(self, device, mode, data, wave_len):\n self.device = device\n self.datas, self.label ,self.clip,self.clip_...
import warnings import torch.utils.data as Data import argparse import torch; torch.utils.backcompat.broadcast_warning.enabled = True import torch.optim import torch.backends.cudnn as cudnn; cudnn.benchmark = True import numpy as np from args import args, Test_data, Train_data_all, Train_data, Train_data_all_with_image_name, Train_data_with_image_name, Test_data_with_image_name from dataset import Dataset,Dataset_with_image_name from model.BrainVisModels import TimeEncoder,TimeFreqEncoder,FreqEncoder from process import Trainer from classification import fit_lr, get_rep_with_label,get_rep_with_label_with_image_name from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
9,007
warnings.filterwarnings('ignore') parser = argparse.ArgumentParser(description="Template") parser.add_argument('-mp','--model_params', default='', nargs='*', help='list of key=value pairs of model options') # Parse arguments opt = parser.parse_args() def main(): ## Save data to local path ## Reduce the data load time on server for other training steps # with open("data/EEG_divided/Train_data_all.pkl", "wb") as f: # pickle.dump(Train_data_all,f) # # with open("data/EEG_divided/Train_data.pkl", "wb") as j: # pickle.dump(Train_data,j) # # with open("data/EEG_divided/Test_data.pkl", "wb") as k: # pickle.dump(Test_data,k) torch.set_num_threads(12) torch.cuda.manual_seed(3407) train_dataset = Dataset(device=args.device, mode='pretrain', data=Train_data_all, wave_len=args.wave_length) train_loader = Data.DataLoader(train_dataset, batch_size=args.train_batch_size, shuffle=True) args.data_shape = train_dataset.shape() train_linear_dataset = Dataset(device=args.device, mode='supervise_train', data=Train_data, wave_len=args.wave_length) train_linear_loader = Data.DataLoader(train_linear_dataset, batch_size=args.train_batch_size, shuffle=True) test_dataset = Dataset(device=args.device, mode='test', data=Test_data, wave_len=args.wave_length) test_loader = Data.DataLoader(test_dataset, batch_size=args.test_batch_size) all_train_linear_dataset_with_image_name = Dataset_with_image_name(device=args.device, mode='supervise_train', data=Train_data_all_with_image_name, wave_len=args.wave_length) all_train_linear_loader_with_image_name = Data.DataLoader(all_train_linear_dataset_with_image_name, batch_size=args.train_batch_size) test_dataset_with_image_name = Dataset_with_image_name(device=args.device, mode='test', data=Test_data_with_image_name, wave_len=args.wave_length) test_loader_with_image_name = Data.DataLoader(test_dataset_with_image_name, batch_size=args.test_batch_size) print(args.data_shape) print('dataset initial ends') time_model = TimeEncoder(args) print('model initial ends') trainer = Trainer(args, time_model, train_loader, train_linear_loader, test_loader, verbose=True) train_mode=True #True for training, False for the export of test data for image generation if train_mode: trainer.pretrain() #trainer.cont_pretrain() #trainer.finetune() ## Start from this step, to finetune on single subject, please modify the 'datautils.py'. #trainer.finetune_timefreq() #trainer.finetune_CLIP() else: ## We suggest exporting data by single subject timeE = TimeEncoder(args).to("cuda") freq_model_options = {key: int(value) if value.isdigit() else (float(value) if value[0].isdigit() else value) for (key, value) in [x.split("=") for x in opt.model_params]} # Create discriminator model
warnings.filterwarnings('ignore') parser = argparse.ArgumentParser(description="Template") parser.add_argument('-mp','--model_params', default='', nargs='*', help='list of key=value pairs of model options') # Parse arguments opt = parser.parse_args() def main(): ## Save data to local path ## Reduce the data load time on server for other training steps # with open("data/EEG_divided/Train_data_all.pkl", "wb") as f: # pickle.dump(Train_data_all,f) # # with open("data/EEG_divided/Train_data.pkl", "wb") as j: # pickle.dump(Train_data,j) # # with open("data/EEG_divided/Test_data.pkl", "wb") as k: # pickle.dump(Test_data,k) torch.set_num_threads(12) torch.cuda.manual_seed(3407) train_dataset = Dataset(device=args.device, mode='pretrain', data=Train_data_all, wave_len=args.wave_length) train_loader = Data.DataLoader(train_dataset, batch_size=args.train_batch_size, shuffle=True) args.data_shape = train_dataset.shape() train_linear_dataset = Dataset(device=args.device, mode='supervise_train', data=Train_data, wave_len=args.wave_length) train_linear_loader = Data.DataLoader(train_linear_dataset, batch_size=args.train_batch_size, shuffle=True) test_dataset = Dataset(device=args.device, mode='test', data=Test_data, wave_len=args.wave_length) test_loader = Data.DataLoader(test_dataset, batch_size=args.test_batch_size) all_train_linear_dataset_with_image_name = Dataset_with_image_name(device=args.device, mode='supervise_train', data=Train_data_all_with_image_name, wave_len=args.wave_length) all_train_linear_loader_with_image_name = Data.DataLoader(all_train_linear_dataset_with_image_name, batch_size=args.train_batch_size) test_dataset_with_image_name = Dataset_with_image_name(device=args.device, mode='test', data=Test_data_with_image_name, wave_len=args.wave_length) test_loader_with_image_name = Data.DataLoader(test_dataset_with_image_name, batch_size=args.test_batch_size) print(args.data_shape) print('dataset initial ends') time_model = TimeEncoder(args) print('model initial ends') trainer = Trainer(args, time_model, train_loader, train_linear_loader, test_loader, verbose=True) train_mode=True #True for training, False for the export of test data for image generation if train_mode: trainer.pretrain() #trainer.cont_pretrain() #trainer.finetune() ## Start from this step, to finetune on single subject, please modify the 'datautils.py'. #trainer.finetune_timefreq() #trainer.finetune_CLIP() else: ## We suggest exporting data by single subject timeE = TimeEncoder(args).to("cuda") freq_model_options = {key: int(value) if value.isdigit() else (float(value) if value[0].isdigit() else value) for (key, value) in [x.split("=") for x in opt.model_params]} # Create discriminator model
freq_model = FreqEncoder(**freq_model_options)
5
2023-12-16 12:52:14+00:00
12k
tonnetonne814/PL-Bert-VITS2
train_ms.py
[ { "identifier": "DistributedBucketSampler", "path": "data_utils.py", "snippet": "class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):\n \"\"\"\n Maintain similar input lengths in a batch.\n Length groups are specified by boundaries.\n Ex) boundaries = [b1, b2, b3]...
import argparse import itertools import json import math import os import logging import torch import torch.distributed as dist import torch.multiprocessing as mp import tqdm import commons import models import utils from torch import nn, optim from torch.cuda.amp import GradScaler, autocast from torch.nn import functional as F from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from data_utils import (DistributedBucketSampler, TextAudioSpeakerCollate, TextAudioSpeakerLoader) from losses import discriminator_loss, feature_loss, generator_loss, kl_loss from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from models import (AVAILABLE_DURATION_DISCRIMINATOR_TYPES, AVAILABLE_FLOW_TYPES, DurationDiscriminatorV1, DurationDiscriminatorV2, MultiPeriodDiscriminator, SynthesizerTrn) from PL_BERT_ja.text.symbols import symbols
10,766
), ) def run(rank, n_gpus, hps): net_dur_disc = None global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) writer = SummaryWriter(log_dir=hps.model_dir) writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) dist.init_process_group( backend="nccl", init_method="env://", world_size=n_gpus, rank=rank ) torch.manual_seed(hps.train.seed) torch.cuda.set_device(rank) if ( "use_mel_posterior_encoder" in hps.model.keys() and hps.model.use_mel_posterior_encoder == True ): print("Using mel posterior encoder for VITS2") posterior_channels = 128 # vits2 hps.data.use_mel_posterior_encoder = True else: print("Using lin posterior encoder for VITS1") posterior_channels = hps.data.filter_length // 2 + 1 hps.data.use_mel_posterior_encoder = False train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 500, 700, 900, 1100, 1300, 1500, 3000], num_replicas=n_gpus, rank=rank, shuffle=True, ) collate_fn = TextAudioSpeakerCollate() train_loader = DataLoader( train_dataset, num_workers=8, shuffle=False, pin_memory=True, collate_fn=collate_fn, batch_sampler=train_sampler, ) if rank == 0: eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) eval_loader = DataLoader( eval_dataset, num_workers=8, shuffle=False, batch_size=hps.train.batch_size, pin_memory=True, drop_last=False, collate_fn=collate_fn, ) # some of these flags are not being used in the code and directly set in hps json file. # they are kept here for reference and prototyping. if ( "use_transformer_flows" in hps.model.keys() and hps.model.use_transformer_flows == True ): use_transformer_flows = True transformer_flow_type = hps.model.transformer_flow_type print(f"Using transformer flows {transformer_flow_type} for VITS2") assert ( transformer_flow_type in AVAILABLE_FLOW_TYPES ), f"transformer_flow_type must be one of {AVAILABLE_FLOW_TYPES}" else: print("Using normal flows for VITS1") use_transformer_flows = False if ( "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder == True ): if hps.data.n_speakers == 0: raise ValueError( "n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model" ) use_spk_conditioned_encoder = True else: print("Using normal encoder for VITS1") use_spk_conditioned_encoder = False if ( "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas == True ): print("Using noise scaled MAS for VITS2") use_noise_scaled_mas = True mas_noise_scale_initial = 0.01 noise_scale_delta = 2e-6 else: print("Using normal MAS for VITS1") use_noise_scaled_mas = False mas_noise_scale_initial = 0.0 noise_scale_delta = 0.0 if ( "use_duration_discriminator" in hps.model.keys() and hps.model.use_duration_discriminator == True ): # print("Using duration discriminator for VITS2") use_duration_discriminator = True # comment - choihkk # add duration discriminator type here # I think it would be a good idea to come up with a method to input this part accurately, like a hydra duration_discriminator_type = getattr( hps.model, "duration_discriminator_type", "dur_disc_1" ) print(f"Using duration_discriminator {duration_discriminator_type} for VITS2") assert (
numba_logger = logging.getLogger('numba') numba_logger.setLevel(logging.WARNING) # from tensorboardX import SummaryWriter torch.backends.cudnn.benchmark = True global_step = 0 def main(): """Assume Single Node Multi GPUs Training Only""" assert torch.cuda.is_available(), "CPU training is not allowed." n_gpus = torch.cuda.device_count() os.environ["MASTER_ADDR"] = "localhost" os.environ["MASTER_PORT"] = "6060" hps = utils.get_hparams() mp.spawn( run, nprocs=n_gpus, args=( n_gpus, hps, ), ) def run(rank, n_gpus, hps): net_dur_disc = None global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) writer = SummaryWriter(log_dir=hps.model_dir) writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) dist.init_process_group( backend="nccl", init_method="env://", world_size=n_gpus, rank=rank ) torch.manual_seed(hps.train.seed) torch.cuda.set_device(rank) if ( "use_mel_posterior_encoder" in hps.model.keys() and hps.model.use_mel_posterior_encoder == True ): print("Using mel posterior encoder for VITS2") posterior_channels = 128 # vits2 hps.data.use_mel_posterior_encoder = True else: print("Using lin posterior encoder for VITS1") posterior_channels = hps.data.filter_length // 2 + 1 hps.data.use_mel_posterior_encoder = False train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 500, 700, 900, 1100, 1300, 1500, 3000], num_replicas=n_gpus, rank=rank, shuffle=True, ) collate_fn = TextAudioSpeakerCollate() train_loader = DataLoader( train_dataset, num_workers=8, shuffle=False, pin_memory=True, collate_fn=collate_fn, batch_sampler=train_sampler, ) if rank == 0: eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) eval_loader = DataLoader( eval_dataset, num_workers=8, shuffle=False, batch_size=hps.train.batch_size, pin_memory=True, drop_last=False, collate_fn=collate_fn, ) # some of these flags are not being used in the code and directly set in hps json file. # they are kept here for reference and prototyping. if ( "use_transformer_flows" in hps.model.keys() and hps.model.use_transformer_flows == True ): use_transformer_flows = True transformer_flow_type = hps.model.transformer_flow_type print(f"Using transformer flows {transformer_flow_type} for VITS2") assert ( transformer_flow_type in AVAILABLE_FLOW_TYPES ), f"transformer_flow_type must be one of {AVAILABLE_FLOW_TYPES}" else: print("Using normal flows for VITS1") use_transformer_flows = False if ( "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder == True ): if hps.data.n_speakers == 0: raise ValueError( "n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model" ) use_spk_conditioned_encoder = True else: print("Using normal encoder for VITS1") use_spk_conditioned_encoder = False if ( "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas == True ): print("Using noise scaled MAS for VITS2") use_noise_scaled_mas = True mas_noise_scale_initial = 0.01 noise_scale_delta = 2e-6 else: print("Using normal MAS for VITS1") use_noise_scaled_mas = False mas_noise_scale_initial = 0.0 noise_scale_delta = 0.0 if ( "use_duration_discriminator" in hps.model.keys() and hps.model.use_duration_discriminator == True ): # print("Using duration discriminator for VITS2") use_duration_discriminator = True # comment - choihkk # add duration discriminator type here # I think it would be a good idea to come up with a method to input this part accurately, like a hydra duration_discriminator_type = getattr( hps.model, "duration_discriminator_type", "dur_disc_1" ) print(f"Using duration_discriminator {duration_discriminator_type} for VITS2") assert (
duration_discriminator_type in AVAILABLE_DURATION_DISCRIMINATOR_TYPES
9
2023-12-16 05:34:02+00:00
12k
camenduru/FreeInit-hf
animatediff/models/unet.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "animatediff/models/unet_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n num_layers...
from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from .unet_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from .resnet import InflatedConv3d, InflatedGroupNorm from diffusers.utils import WEIGHTS_NAME import os import json import pdb import torch import torch.nn as nn import torch.utils.checkpoint
7,711
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): _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: 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: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", use_inflated_groupnorm=False, # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # 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) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): _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: 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: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", use_inflated_groupnorm=False, # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # 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) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1
down_block = get_down_block(
5
2023-12-19 21:06:32+00:00
12k
zyrant/SPGroup3D
tools/data_converter/indoor_converter.py
[ { "identifier": "S3DISData", "path": "tools/data_converter/s3dis_data_utils.py", "snippet": "class S3DISData(object):\n \"\"\"S3DIS data.\n\n Generate s3dis infos for s3dis_converter.\n\n Args:\n root_path (str): Root path of the raw data.\n split (str, optional): Set split type o...
import os import mmcv import numpy as np from tools.data_converter.s3dis_data_utils import S3DISData, S3DISSegData from tools.data_converter.scannet_data_utils import ScanNetData, ScanNetSegData from tools.data_converter.scannet_md40_data_utils import ScanNetData_md40, ScanNetSegData_md40 from tools.data_converter.sunrgbd_data_utils import SUNRGBDData
8,142
# Copyright (c) OpenMMLab. All rights reserved. def create_indoor_info_file(data_path, pkl_prefix='sunrgbd', save_path=None, use_v1=False, workers=4): """Create indoor information file. Get information of the raw data and save it to the pkl file. Args: data_path (str): Path of the data. pkl_prefix (str, optional): Prefix of the pkl to be saved. Default: 'sunrgbd'. save_path (str, optional): Path of the pkl to be saved. Default: None. use_v1 (bool, optional): Whether to use v1. Default: False. workers (int, optional): Number of threads to be used. Default: 4. """ assert os.path.exists(data_path) assert pkl_prefix in ['sunrgbd', 'scannet', 's3dis', 'scannet_md40'], \ f'unsupported indoor dataset {pkl_prefix}' save_path = data_path if save_path is None else save_path assert os.path.exists(save_path) # generate infos for both detection and segmentation task if pkl_prefix in ['sunrgbd', 'scannet', 'scannet_md40']: train_filename = os.path.join(save_path, f'{pkl_prefix}_infos_train.pkl') val_filename = os.path.join(save_path, f'{pkl_prefix}_infos_val.pkl') if pkl_prefix == 'sunrgbd': # SUN RGB-D has a train-val split
# Copyright (c) OpenMMLab. All rights reserved. def create_indoor_info_file(data_path, pkl_prefix='sunrgbd', save_path=None, use_v1=False, workers=4): """Create indoor information file. Get information of the raw data and save it to the pkl file. Args: data_path (str): Path of the data. pkl_prefix (str, optional): Prefix of the pkl to be saved. Default: 'sunrgbd'. save_path (str, optional): Path of the pkl to be saved. Default: None. use_v1 (bool, optional): Whether to use v1. Default: False. workers (int, optional): Number of threads to be used. Default: 4. """ assert os.path.exists(data_path) assert pkl_prefix in ['sunrgbd', 'scannet', 's3dis', 'scannet_md40'], \ f'unsupported indoor dataset {pkl_prefix}' save_path = data_path if save_path is None else save_path assert os.path.exists(save_path) # generate infos for both detection and segmentation task if pkl_prefix in ['sunrgbd', 'scannet', 'scannet_md40']: train_filename = os.path.join(save_path, f'{pkl_prefix}_infos_train.pkl') val_filename = os.path.join(save_path, f'{pkl_prefix}_infos_val.pkl') if pkl_prefix == 'sunrgbd': # SUN RGB-D has a train-val split
train_dataset = SUNRGBDData(
4
2023-12-21 12:50:35+00:00
12k
jdejaegh/irm-kmi-ha
custom_components/irm_kmi/coordinator.py
[ { "identifier": "IrmKmiApiClient", "path": "custom_components/irm_kmi/api.py", "snippet": "class IrmKmiApiClient:\n \"\"\"API client for IRM KMI weather data\"\"\"\n COORD_DECIMALS = 6\n\n def __init__(self, session: aiohttp.ClientSession) -> None:\n self._session = session\n self...
import asyncio import logging import async_timeout import pytz from datetime import datetime, timedelta from typing import Any, List, Tuple from homeassistant.components.weather import Forecast from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, CONF_ZONE from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import (DataUpdateCoordinator, UpdateFailed) from .api import IrmKmiApiClient, IrmKmiApiError from .const import CONF_DARK_MODE, CONF_STYLE, DOMAIN from .const import IRM_KMI_TO_HA_CONDITION_MAP as CDT_MAP from .const import LANGS from .const import MAP_WARNING_ID_TO_SLUG as SLUG_MAP from .const import OPTION_STYLE_SATELLITE, OUT_OF_BENELUX, STYLE_TO_PARAM_MAP from .data import (AnimationFrameData, CurrentWeatherData, IrmKmiForecast, ProcessedCoordinatorData, RadarAnimationData, WarningData) from .rain_graph import RainGraph from .utils import disable_from_config, get_config_value
7,235
"""DataUpdateCoordinator for the IRM KMI integration.""" _LOGGER = logging.getLogger(__name__) class IrmKmiCoordinator(DataUpdateCoordinator): """Coordinator to update data from IRM KMI""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry): """Initialize the coordinator.""" super().__init__( hass, _LOGGER, # Name of the data. For logging purposes. name="IRM KMI weather", # Polling interval. Will only be polled if there are subscribers. update_interval=timedelta(minutes=7), ) self._api_client = IrmKmiApiClient(session=async_get_clientsession(hass)) self._zone = get_config_value(entry, CONF_ZONE) self._dark_mode = get_config_value(entry, CONF_DARK_MODE) self._style = get_config_value(entry, CONF_STYLE) self._config_entry = entry async def _async_update_data(self) -> ProcessedCoordinatorData: """Fetch data from API endpoint. This is the place to pre-process the data to lookup tables so entities can quickly look up their data. """ if (zone := self.hass.states.get(self._zone)) is None: raise UpdateFailed(f"Zone '{self._zone}' not found") try: # Note: asyncio.TimeoutError and aiohttp.ClientError are already # handled by the data update coordinator. async with async_timeout.timeout(10): api_data = await self._api_client.get_forecasts_coord( {'lat': zone.attributes[ATTR_LATITUDE], 'long': zone.attributes[ATTR_LONGITUDE]} ) _LOGGER.debug(f"Observation for {api_data.get('cityName', '')}: {api_data.get('obs', '{}')}") except IrmKmiApiError as err: raise UpdateFailed(f"Error communicating with API: {err}") if api_data.get('cityName', None) in OUT_OF_BENELUX: # TODO create a repair when this triggers _LOGGER.info(f"Config state: {self._config_entry.state}") _LOGGER.error(f"The zone {self._zone} is now out of Benelux and forecast is only available in Benelux." f"Associated device is now disabled. Move the zone back in Benelux and re-enable to fix " f"this") disable_from_config(self.hass, self._config_entry) issue_registry.async_create_issue( self.hass, DOMAIN, "zone_moved", is_fixable=True, severity=issue_registry.IssueSeverity.ERROR, translation_key='zone_moved', data={'config_entry_id': self._config_entry.entry_id, 'zone': self._zone}, translation_placeholders={'zone': self._zone} ) return ProcessedCoordinatorData() return await self.process_api_data(api_data) async def async_refresh(self) -> None: """Refresh data and log errors.""" await self._async_refresh(log_failures=True, raise_on_entry_error=True) async def _async_animation_data(self, api_data: dict) -> RadarAnimationData: """From the API data passed in, call the API to get all the images and create the radar animation data object. Frames from the API are merged with the background map and the location marker to create each frame.""" animation_data = api_data.get('animation', {}).get('sequence') localisation_layer_url = api_data.get('animation', {}).get('localisationLayer') country = api_data.get('country', '') if animation_data is None or localisation_layer_url is None or not isinstance(animation_data, list): return RadarAnimationData() try: images_from_api = await self.download_images_from_api(animation_data, country, localisation_layer_url) except IrmKmiApiError: _LOGGER.warning(f"Could not get images for weather radar") return RadarAnimationData() localisation = images_from_api[0] images_from_api = images_from_api[1:]
"""DataUpdateCoordinator for the IRM KMI integration.""" _LOGGER = logging.getLogger(__name__) class IrmKmiCoordinator(DataUpdateCoordinator): """Coordinator to update data from IRM KMI""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry): """Initialize the coordinator.""" super().__init__( hass, _LOGGER, # Name of the data. For logging purposes. name="IRM KMI weather", # Polling interval. Will only be polled if there are subscribers. update_interval=timedelta(minutes=7), ) self._api_client = IrmKmiApiClient(session=async_get_clientsession(hass)) self._zone = get_config_value(entry, CONF_ZONE) self._dark_mode = get_config_value(entry, CONF_DARK_MODE) self._style = get_config_value(entry, CONF_STYLE) self._config_entry = entry async def _async_update_data(self) -> ProcessedCoordinatorData: """Fetch data from API endpoint. This is the place to pre-process the data to lookup tables so entities can quickly look up their data. """ if (zone := self.hass.states.get(self._zone)) is None: raise UpdateFailed(f"Zone '{self._zone}' not found") try: # Note: asyncio.TimeoutError and aiohttp.ClientError are already # handled by the data update coordinator. async with async_timeout.timeout(10): api_data = await self._api_client.get_forecasts_coord( {'lat': zone.attributes[ATTR_LATITUDE], 'long': zone.attributes[ATTR_LONGITUDE]} ) _LOGGER.debug(f"Observation for {api_data.get('cityName', '')}: {api_data.get('obs', '{}')}") except IrmKmiApiError as err: raise UpdateFailed(f"Error communicating with API: {err}") if api_data.get('cityName', None) in OUT_OF_BENELUX: # TODO create a repair when this triggers _LOGGER.info(f"Config state: {self._config_entry.state}") _LOGGER.error(f"The zone {self._zone} is now out of Benelux and forecast is only available in Benelux." f"Associated device is now disabled. Move the zone back in Benelux and re-enable to fix " f"this") disable_from_config(self.hass, self._config_entry) issue_registry.async_create_issue( self.hass, DOMAIN, "zone_moved", is_fixable=True, severity=issue_registry.IssueSeverity.ERROR, translation_key='zone_moved', data={'config_entry_id': self._config_entry.entry_id, 'zone': self._zone}, translation_placeholders={'zone': self._zone} ) return ProcessedCoordinatorData() return await self.process_api_data(api_data) async def async_refresh(self) -> None: """Refresh data and log errors.""" await self._async_refresh(log_failures=True, raise_on_entry_error=True) async def _async_animation_data(self, api_data: dict) -> RadarAnimationData: """From the API data passed in, call the API to get all the images and create the radar animation data object. Frames from the API are merged with the background map and the location marker to create each frame.""" animation_data = api_data.get('animation', {}).get('sequence') localisation_layer_url = api_data.get('animation', {}).get('localisationLayer') country = api_data.get('country', '') if animation_data is None or localisation_layer_url is None or not isinstance(animation_data, list): return RadarAnimationData() try: images_from_api = await self.download_images_from_api(animation_data, country, localisation_layer_url) except IrmKmiApiError: _LOGGER.warning(f"Could not get images for weather radar") return RadarAnimationData() localisation = images_from_api[0] images_from_api = images_from_api[1:]
lang = self.hass.config.language if self.hass.config.language in LANGS else 'en'
6
2023-12-17 16:35:01+00:00
12k
v3ucn/Bert-vits2-V2.2
oldVersion/V111/text/chinese.py
[ { "identifier": "punctuation", "path": "oldVersion/V111/text/symbols.py", "snippet": "" }, { "identifier": "ToneSandhi", "path": "oldVersion/V111/text/tone_sandhi.py", "snippet": "class ToneSandhi:\n def __init__(self):\n self.must_neural_tone_words = {\n \"麻烦\",\n ...
import os import re import cn2an import jieba.posseg as psg from pypinyin import lazy_pinyin, Style from .symbols import punctuation from .tone_sandhi import ToneSandhi from text import chinese_bert from text.chinese_bert import get_bert_feature
7,595
current_file_path = os.path.dirname(__file__) pinyin_to_symbol_map = { line.split("\t")[0]: line.strip().split("\t")[1] for line in open(os.path.join(current_file_path, "opencpop-strict.txt")).readlines() } rep_map = { ":": ",", ";": ",", ",": ",", "。": ".", "!": "!", "?": "?", "\n": ".", "·": ",", "、": ",", "...": "…", "$": ".", "“": "'", "”": "'", "‘": "'", "’": "'", "(": "'", ")": "'", "(": "'", ")": "'", "《": "'", "》": "'", "【": "'", "】": "'", "[": "'", "]": "'", "—": "-", "~": "-", "~": "-", "「": "'", "」": "'", }
current_file_path = os.path.dirname(__file__) pinyin_to_symbol_map = { line.split("\t")[0]: line.strip().split("\t")[1] for line in open(os.path.join(current_file_path, "opencpop-strict.txt")).readlines() } rep_map = { ":": ",", ";": ",", ",": ",", "。": ".", "!": "!", "?": "?", "\n": ".", "·": ",", "、": ",", "...": "…", "$": ".", "“": "'", "”": "'", "‘": "'", "’": "'", "(": "'", ")": "'", "(": "'", ")": "'", "《": "'", "》": "'", "【": "'", "】": "'", "[": "'", "]": "'", "—": "-", "~": "-", "~": "-", "「": "'", "」": "'", }
tone_modifier = ToneSandhi()
1
2023-12-18 04:54:46+00:00
12k
d-krupke/CP-SAT-Log-Analyzer
app.py
[ { "identifier": "LogParser", "path": "cpsat_log_parser/parser.py", "snippet": "class LogParser:\n def __init__(self, log: typing.Union[str, typing.List[str]]) -> None:\n self.comments, log_without_comments = self._extract_comments(log)\n self.blocks = self.parse_blocks(log_without_comme...
import streamlit as st from cpsat_log_parser import LogParser from cpsat_log_parser.blocks import ( SearchProgressBlock, SearchStatsBlock, SolutionsBlock, TableBlock, SolverBlock, ResponseBlock, PresolveLogBlock, TaskTimingBlock, PresolvedModelBlock, ) from _app import print_header, input_log, show_overview
9,886
""" This file is the main entry point for the Streamlit app. Further parts of the app are in the `_app` folder. The logic for parsing the log is in the `cpsat_log_parser` folder. """ print_header() data = input_log() if data: st.header("Log Analysis") st.warning( "This is just a prototype and may crash or show wrong results. Please report any issues [here](https://github.com/d-krupke/CP-SAT-Log-Analyzer). I welcome any feedback and complex logs to test this on." ) parser = LogParser(data) show_overview(parser) st.markdown("*You can expand the following block to see the raw log.*") with st.expander("Raw Log"): st.text(data) st.markdown( "*The following part contains a parsed version of the log, easier for analysis. Depending on the CP-SAT version, not all parts may be parsed properly.*" ) for block in parser.blocks: try: if isinstance(block, SearchProgressBlock): st.subheader("Search", divider=True) with st.expander(block.get_title(), expanded=True): if block.get_help(): st.info(block.get_help()) st.text(str(block)) fig = block.as_plotly() if fig: st.plotly_chart(fig, use_container_width=True) st.info( "This plot shows you how the quality of the solution (objective), and the proved quality (bound) converge over time. It allows you to estimate if finding good solutions or proving optimality is the bottleneck." ) fig_3 = block.gap_as_plotly() if fig_3: st.plotly_chart(fig_3, use_container_width=True) st.info( "This plot shows you how the gap between the objective and the bound changes over time. If it quickly reaches a small value but then does not improve for a long time, you could set the `relative_gap_limit` parameter to allow to stop the search as soon as a specific solution quality is reached." ) fig_2 = block.model_changes_as_plotly() if fig_2: st.plotly_chart(fig_2, use_container_width=True) st.info( "This plot shows you how the size of the model changes over time." ) st.subheader("Statistics", divider=True) st.info( "This part contains detailed statistics about the search. Only a few elements are useful for the common user." ) elif isinstance(block, SolverBlock): st.subheader("Initialization", divider=True) st.info( "This block contains some basic information about the solver and the model. For example, you can check how large the model is which parameters were changed." ) with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) st.text(str(block)) elif isinstance(block, SearchStatsBlock): with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) df = block.to_pandas() st.dataframe( df, column_config={ "Restarts": st.column_config.NumberColumn( help="Restarting the search once we learned about the importance of variables can significantly reduce the size of the search tree." ), }, ) elif isinstance(block, TaskTimingBlock): with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) tab1, tab2 = st.tabs(["Table", "Raw"]) df_1 = block.to_pandas(deterministic=False) tab1.dataframe(df_1, use_container_width=True) df_2 = block.to_pandas(deterministic=True) tab1.dataframe(df_2, use_container_width=True) tab2.text(str(block)) elif isinstance(block, SolutionsBlock): with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) st.markdown(f"Number of solutions: {block.get_num_solutions()}") df = block.to_pandas() st.dataframe(df, use_container_width=True) elif isinstance(block, PresolvedModelBlock): with st.expander(block.get_title(), expanded=True): if block.get_help(): st.info(block.get_help()) st.text(str(block)) elif isinstance(block, ResponseBlock): st.subheader("Summary", divider=True) with st.expander(block.get_title(), expanded=True): if block.get_help(): st.info(block.get_help()) df = block.to_pandas() st.dataframe(df.transpose(), use_container_width=True)
""" This file is the main entry point for the Streamlit app. Further parts of the app are in the `_app` folder. The logic for parsing the log is in the `cpsat_log_parser` folder. """ print_header() data = input_log() if data: st.header("Log Analysis") st.warning( "This is just a prototype and may crash or show wrong results. Please report any issues [here](https://github.com/d-krupke/CP-SAT-Log-Analyzer). I welcome any feedback and complex logs to test this on." ) parser = LogParser(data) show_overview(parser) st.markdown("*You can expand the following block to see the raw log.*") with st.expander("Raw Log"): st.text(data) st.markdown( "*The following part contains a parsed version of the log, easier for analysis. Depending on the CP-SAT version, not all parts may be parsed properly.*" ) for block in parser.blocks: try: if isinstance(block, SearchProgressBlock): st.subheader("Search", divider=True) with st.expander(block.get_title(), expanded=True): if block.get_help(): st.info(block.get_help()) st.text(str(block)) fig = block.as_plotly() if fig: st.plotly_chart(fig, use_container_width=True) st.info( "This plot shows you how the quality of the solution (objective), and the proved quality (bound) converge over time. It allows you to estimate if finding good solutions or proving optimality is the bottleneck." ) fig_3 = block.gap_as_plotly() if fig_3: st.plotly_chart(fig_3, use_container_width=True) st.info( "This plot shows you how the gap between the objective and the bound changes over time. If it quickly reaches a small value but then does not improve for a long time, you could set the `relative_gap_limit` parameter to allow to stop the search as soon as a specific solution quality is reached." ) fig_2 = block.model_changes_as_plotly() if fig_2: st.plotly_chart(fig_2, use_container_width=True) st.info( "This plot shows you how the size of the model changes over time." ) st.subheader("Statistics", divider=True) st.info( "This part contains detailed statistics about the search. Only a few elements are useful for the common user." ) elif isinstance(block, SolverBlock): st.subheader("Initialization", divider=True) st.info( "This block contains some basic information about the solver and the model. For example, you can check how large the model is which parameters were changed." ) with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) st.text(str(block)) elif isinstance(block, SearchStatsBlock): with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) df = block.to_pandas() st.dataframe( df, column_config={ "Restarts": st.column_config.NumberColumn( help="Restarting the search once we learned about the importance of variables can significantly reduce the size of the search tree." ), }, ) elif isinstance(block, TaskTimingBlock): with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) tab1, tab2 = st.tabs(["Table", "Raw"]) df_1 = block.to_pandas(deterministic=False) tab1.dataframe(df_1, use_container_width=True) df_2 = block.to_pandas(deterministic=True) tab1.dataframe(df_2, use_container_width=True) tab2.text(str(block)) elif isinstance(block, SolutionsBlock): with st.expander(block.get_title()): if block.get_help(): st.info(block.get_help()) st.markdown(f"Number of solutions: {block.get_num_solutions()}") df = block.to_pandas() st.dataframe(df, use_container_width=True) elif isinstance(block, PresolvedModelBlock): with st.expander(block.get_title(), expanded=True): if block.get_help(): st.info(block.get_help()) st.text(str(block)) elif isinstance(block, ResponseBlock): st.subheader("Summary", divider=True) with st.expander(block.get_title(), expanded=True): if block.get_help(): st.info(block.get_help()) df = block.to_pandas() st.dataframe(df.transpose(), use_container_width=True)
elif isinstance(block, PresolveLogBlock):
7
2023-12-18 09:18:19+00:00
12k
MMC-K/multimodal_generation_downstream_tasks
testing_veldt5_accelerate_bg.py
[ { "identifier": "DatasetForVLAlign", "path": "data_utils.py", "snippet": "class DatasetForVLAlign(Dataset):\n def __init__(\n self,\n file_path: str,\n image_tokenizer: ViTFeatureExtractor,\n text_tokenizer: AutoTokenizer,\n ...
import argparse import json import logging import math import os import random import numpy as np import torch import transformers import datasets import evaluate from curses import raw from datetime import timedelta from itertools import chain from torch import nn from torch.utils.data import DataLoader from tqdm.auto import tqdm from torch.nn import CrossEntropyLoss from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed, InitProcessGroupKwargs, DistributedDataParallelKwargs from torch.optim import AdamW from transformers import ( AutoTokenizer, ViTFeatureExtractor, SchedulerType, get_scheduler, default_data_collator, ) from datasets import load_dataset from data_utils import DatasetForVLAlign from modeling_veldt5 import VELDT5Model from mecab import MeCab from PIL import Image
8,022
help="Total number of validation steps to perform.", ) # parser.add_argument( # "--max_train_steps_per_epoch", # type=int, # default=None, # help="The number of training steps to perform on a epoch. (for debugging)", # ) parser.add_argument( "--lr_scheduler_type", type=SchedulerType, default="linear", help="The scheduler type to use.", choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], ) parser.add_argument( "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." ) # parser.add_argument( # "--warmup_portion", type=float, default=0, help="Portion of total training steps for the warmup in the lr scheduler." # ) # parser.add_argument( # "--checkpointing_steps", # type=str, # default=None, # help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", # ) parser.add_argument( "--resume_from_checkpoint", type=str, default=None, help="If the training should continue from a checkpoint folder.", ) # logging # parser.add_argument( # "--logging_steps", type=int, default=0, help="Number of steps for logging (stdout)." # ) parser.add_argument( "--with_tracking", action="store_true", help="Whether to enable experiment trackers for logging.", ) parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.") parser.add_argument( "--report_to", type=str, default="all", help=( 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,' ' `"wandb"` and `"comet_ml"`. Use `"all"` (default) to report to all integrations.' "Only applicable when `--with_tracking` is passed." ), ) parser.add_argument( "--from_veld_model", type=str, default=None, help=( "Path to model that you want to test" ), ) parser.add_argument( "--save_caption_result", action="store_true", help="save caption results in <model_path>/figures/<img_num>.png and <model_path>/figures/captions.json", ) args = parser.parse_args() print("[BG] args.validation_path:", args.validation_path) # assert(False) return args def main(): args = parse_args() accelerator_log_kwargs = {} if args.with_tracking: accelerator_log_kwargs["log_with"] = args.report_to # accelerator_log_kwargs["logging_dir"] = args.output_dir kwargs_handlers = [ InitProcessGroupKwargs(timeout=timedelta(days=10)), DistributedDataParallelKwargs(find_unused_parameters=True) ] # accelerator_log_kwargs["project_dir"] = accelerator_log_kwargs["logging_dir"] # del accelerator_log_kwargs["logging_dir"] accelerator = Accelerator( # gradient_accumulation_steps=args.gradient_accumulation_steps, kwargs_handlers=kwargs_handlers , **accelerator_log_kwargs) # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) logger.info(accelerator.state, main_process_only=False) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) random.seed(args.seed) model = None # Load model and tokenizer logger.info("***** Running from a pretrained VELD model *****")
#!/usr/bin/env python # coding=utf-8 # Copyright The HuggingFace Team and The HuggingFace Inc. 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. # Copyright 2022 san kim # # 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. logger = get_logger(__name__) # epochs=1 # learning_rate=0.001 # scheduler_type=linear # accelerate launch training_veldt5_accelerate.py \ # --vision_model 'google/vit-base-patch16-384' \ # --language_model 'KETI-AIR/ke-t5-base' \ # --gradient_accumulation_steps 32 \ # --per_device_train_batch_size 16 \ # --per_device_eval_batch_size 16 \ # --warmup_portion 0.02 \ # --logging_steps 20 \ # --checkpointing_steps 10000 \ # --num_train_epochs $epochs \ # --lr_scheduler_type $scheduler_type \ # --with_tracking \ # --output_dir veld_e${epochs}_${scheduler_type} # accelerate launch training_veldt5_accelerate.py \ # --max_train_steps_per_epoch 100 \ # --max_validation_steps 20 \ # --logging_steps 5 \ # --with_tracking \ # --output_dir test def parse_args(): parser = argparse.ArgumentParser(description="Finetune a transformers model on a summarization task") # data parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task") parser.add_argument( "--dataset_name_lm", type=str, default="sent_dataset.py", help="The name of the dataset to use (via the datasets library).", ) parser.add_argument( "--dataset_config_name_lm", type=str, default="base", help="The configuration name of the dataset to use (via the datasets library).", ) parser.add_argument( "--hf_cache_dir", type=str, default="../huggingface_datasets", help="The path to cache directory for huggingface datasets.", ) parser.add_argument( "--validation_split_percentage", default=1, help="The percentage of the train set used as validation set in case there's no validation split", ) parser.add_argument( "--preprocessing_num_workers", type=int, default=256, help="The number of processes to use for the preprocessing.", ) parser.add_argument( "--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets" ) parser.add_argument( "--block_size", type=int, default=None, help=( "Optional input sequence length after tokenization. The training dataset will be truncated in block of" " this size for training. Default to the model max input length for single sentence inputs (take into" " account special tokens)." ), ) # parser.add_argument("--train_path", # default="../../downloaded_data/train-filtered.json", type=str) parser.add_argument("--validation_path", default="../../downloaded_data/validation-filtered.json", type=str) # parser.add_argument("--image_root_dir", # default="../../downloaded_data", type=str) parser.add_argument( "--dataset_name", type=str, default="image_text_pair_datasets.py", help="The name of the dataset to use (via the datasets library).", ) parser.add_argument( "--dataset_config_name", type=str, default="base", help="The configuration name of the dataset to use (via the datasets library).", ) parser.add_argument( "--hf_data_dir", type=str, default="../../downloaded_data", help="The path to data directory for huggingface datasets.", ) # model parser.add_argument("--vision_model", default="google/vit-base-patch16-384", type=str) parser.add_argument("--language_model", default="KETI-AIR/ke-t5-base", type=str) parser.add_argument( "--use_slow_tokenizer", action="store_true", help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).", ) # training parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") # parser.add_argument( # "--gradient_accumulation_steps", # type=int, # default=1, # help="Number of updates steps to accumulate before performing a backward/update pass.", # ) parser.add_argument( "--per_device_train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader.", ) parser.add_argument( "--per_device_eval_batch_size", type=int, default=8, help="Batch size (per device) for the evaluation dataloader.", ) parser.add_argument( "--learning_rate", type=float, default=8e-4, help="Initial learning rate (after the potential warmup period) to use.", ) parser.add_argument("--contrastive_weight", default=1.0, type=float, help="The weighting value for contrastive loss") parser.add_argument("--captioning_weight", default=2.0, type=float, help="The weighting value for captioning loss") parser.add_argument("--lm_weight", default=1.0, type=float, help="The weighting value for lm loss") parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.") parser.add_argument("--logit_temperature", default=1.0, type=float, help="temperature for logits") parser.add_argument("--label_smoothing", default=0.0, type=float, help="label smoothing for cross entropy") # parser.add_argument("--num_train_epochs", type=int, default=1, help="Total number of training epochs to perform.") # parser.add_argument( # "--max_train_steps", # type=int, # default=None, # help="Total number of training steps to perform. If provided, overrides num_train_epochs.", # ) parser.add_argument( "--max_validation_steps", type=int, default=None, help="Total number of validation steps to perform.", ) # parser.add_argument( # "--max_train_steps_per_epoch", # type=int, # default=None, # help="The number of training steps to perform on a epoch. (for debugging)", # ) parser.add_argument( "--lr_scheduler_type", type=SchedulerType, default="linear", help="The scheduler type to use.", choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], ) parser.add_argument( "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." ) # parser.add_argument( # "--warmup_portion", type=float, default=0, help="Portion of total training steps for the warmup in the lr scheduler." # ) # parser.add_argument( # "--checkpointing_steps", # type=str, # default=None, # help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", # ) parser.add_argument( "--resume_from_checkpoint", type=str, default=None, help="If the training should continue from a checkpoint folder.", ) # logging # parser.add_argument( # "--logging_steps", type=int, default=0, help="Number of steps for logging (stdout)." # ) parser.add_argument( "--with_tracking", action="store_true", help="Whether to enable experiment trackers for logging.", ) parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.") parser.add_argument( "--report_to", type=str, default="all", help=( 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,' ' `"wandb"` and `"comet_ml"`. Use `"all"` (default) to report to all integrations.' "Only applicable when `--with_tracking` is passed." ), ) parser.add_argument( "--from_veld_model", type=str, default=None, help=( "Path to model that you want to test" ), ) parser.add_argument( "--save_caption_result", action="store_true", help="save caption results in <model_path>/figures/<img_num>.png and <model_path>/figures/captions.json", ) args = parser.parse_args() print("[BG] args.validation_path:", args.validation_path) # assert(False) return args def main(): args = parse_args() accelerator_log_kwargs = {} if args.with_tracking: accelerator_log_kwargs["log_with"] = args.report_to # accelerator_log_kwargs["logging_dir"] = args.output_dir kwargs_handlers = [ InitProcessGroupKwargs(timeout=timedelta(days=10)), DistributedDataParallelKwargs(find_unused_parameters=True) ] # accelerator_log_kwargs["project_dir"] = accelerator_log_kwargs["logging_dir"] # del accelerator_log_kwargs["logging_dir"] accelerator = Accelerator( # gradient_accumulation_steps=args.gradient_accumulation_steps, kwargs_handlers=kwargs_handlers , **accelerator_log_kwargs) # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) logger.info(accelerator.state, main_process_only=False) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) random.seed(args.seed) model = None # Load model and tokenizer logger.info("***** Running from a pretrained VELD model *****")
model = VELDT5Model.from_pretrained(args.from_veld_model)
1
2023-12-19 01:37:23+00:00
12k
sidharthrajaram/StyleTTS2
src/styletts2/models.py
[ { "identifier": "ASRCNN", "path": "src/styletts2/Utils/ASR/models.py", "snippet": "class ASRCNN(nn.Module):\n def __init__(self,\n input_dim=80,\n hidden_dim=256,\n n_token=35,\n n_layers=6,\n token_embedding_dim=256,\n\n...
import os import os.path as osp import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import yaml from torch.nn.utils import weight_norm, remove_weight_norm, spectral_norm from .Utils.ASR.models import ASRCNN from .Utils.JDC.model import JDCNet from .Modules.diffusion.sampler import KDiffusion, LogNormalDistribution from .Modules.diffusion.modules import Transformer1d, StyleTransformer1d from .Modules.diffusion.diffusion import AudioDiffusionConditional from .Modules.discriminators import MultiPeriodDiscriminator, MultiResSpecDiscriminator, WavLMDiscriminator from munch import Munch from .Modules.istftnet import Decoder from .Modules.hifigan import Decoder
10,224
def forward(self, texts, style, text_lengths, alignment, m): d = self.text_encoder(texts, style, text_lengths, m) batch_size = d.shape[0] text_size = d.shape[1] # predict duration input_lengths = text_lengths.cpu().numpy() x = nn.utils.rnn.pack_padded_sequence( d, input_lengths, batch_first=True, enforce_sorted=False) m = m.to(text_lengths.device).unsqueeze(1) self.lstm.flatten_parameters() x, _ = self.lstm(x) x, _ = nn.utils.rnn.pad_packed_sequence( x, batch_first=True) x_pad = torch.zeros([x.shape[0], m.shape[-1], x.shape[-1]]) x_pad[:, :x.shape[1], :] = x x = x_pad.to(x.device) duration = self.duration_proj(nn.functional.dropout(x, 0.5, training=self.training)) en = (d.transpose(-1, -2) @ alignment) return duration.squeeze(-1), en def F0Ntrain(self, x, s): x, _ = self.shared(x.transpose(-1, -2)) F0 = x.transpose(-1, -2) for block in self.F0: F0 = block(F0, s) F0 = self.F0_proj(F0) N = x.transpose(-1, -2) for block in self.N: N = block(N, s) N = self.N_proj(N) return F0.squeeze(1), N.squeeze(1) def length_to_mask(self, lengths): mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) mask = torch.gt(mask+1, lengths.unsqueeze(1)) return mask class DurationEncoder(nn.Module): def __init__(self, sty_dim, d_model, nlayers, dropout=0.1): super().__init__() self.lstms = nn.ModuleList() for _ in range(nlayers): self.lstms.append(nn.LSTM(d_model + sty_dim, d_model // 2, num_layers=1, batch_first=True, bidirectional=True, dropout=dropout)) self.lstms.append(AdaLayerNorm(sty_dim, d_model)) self.dropout = dropout self.d_model = d_model self.sty_dim = sty_dim def forward(self, x, style, text_lengths, m): masks = m.to(text_lengths.device) x = x.permute(2, 0, 1) s = style.expand(x.shape[0], x.shape[1], -1) x = torch.cat([x, s], axis=-1) x.masked_fill_(masks.unsqueeze(-1).transpose(0, 1), 0.0) x = x.transpose(0, 1) input_lengths = text_lengths.cpu().numpy() x = x.transpose(-1, -2) for block in self.lstms: if isinstance(block, AdaLayerNorm): x = block(x.transpose(-1, -2), style).transpose(-1, -2) x = torch.cat([x, s.permute(1, -1, 0)], axis=1) x.masked_fill_(masks.unsqueeze(-1).transpose(-1, -2), 0.0) else: x = x.transpose(-1, -2) x = nn.utils.rnn.pack_padded_sequence( x, input_lengths, batch_first=True, enforce_sorted=False) block.flatten_parameters() x, _ = block(x) x, _ = nn.utils.rnn.pad_packed_sequence( x, batch_first=True) x = F.dropout(x, p=self.dropout, training=self.training) x = x.transpose(-1, -2) x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]]) x_pad[:, :, :x.shape[-1]] = x x = x_pad.to(x.device) return x.transpose(-1, -2) def inference(self, x, style): x = self.embedding(x.transpose(-1, -2)) * math.sqrt(self.d_model) style = style.expand(x.shape[0], x.shape[1], -1) x = torch.cat([x, style], axis=-1) src = self.pos_encoder(x) output = self.transformer_encoder(src).transpose(0, 1) return output def length_to_mask(self, lengths): mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) mask = torch.gt(mask+1, lengths.unsqueeze(1)) return mask def load_F0_models(path): # load F0 model
#coding:utf-8 class LearnedDownSample(nn.Module): def __init__(self, layer_type, dim_in): super().__init__() self.layer_type = layer_type if self.layer_type == 'none': self.conv = nn.Identity() elif self.layer_type == 'timepreserve': self.conv = spectral_norm(nn.Conv2d(dim_in, dim_in, kernel_size=(3, 1), stride=(2, 1), groups=dim_in, padding=(1, 0))) elif self.layer_type == 'half': self.conv = spectral_norm(nn.Conv2d(dim_in, dim_in, kernel_size=(3, 3), stride=(2, 2), groups=dim_in, padding=1)) else: raise RuntimeError('Got unexpected donwsampletype %s, expected is [none, timepreserve, half]' % self.layer_type) def forward(self, x): return self.conv(x) class LearnedUpSample(nn.Module): def __init__(self, layer_type, dim_in): super().__init__() self.layer_type = layer_type if self.layer_type == 'none': self.conv = nn.Identity() elif self.layer_type == 'timepreserve': self.conv = nn.ConvTranspose2d(dim_in, dim_in, kernel_size=(3, 1), stride=(2, 1), groups=dim_in, output_padding=(1, 0), padding=(1, 0)) elif self.layer_type == 'half': self.conv = nn.ConvTranspose2d(dim_in, dim_in, kernel_size=(3, 3), stride=(2, 2), groups=dim_in, output_padding=1, padding=1) else: raise RuntimeError('Got unexpected upsampletype %s, expected is [none, timepreserve, half]' % self.layer_type) def forward(self, x): return self.conv(x) class DownSample(nn.Module): def __init__(self, layer_type): super().__init__() self.layer_type = layer_type def forward(self, x): if self.layer_type == 'none': return x elif self.layer_type == 'timepreserve': return F.avg_pool2d(x, (2, 1)) elif self.layer_type == 'half': if x.shape[-1] % 2 != 0: x = torch.cat([x, x[..., -1].unsqueeze(-1)], dim=-1) return F.avg_pool2d(x, 2) else: raise RuntimeError('Got unexpected donwsampletype %s, expected is [none, timepreserve, half]' % self.layer_type) class UpSample(nn.Module): def __init__(self, layer_type): super().__init__() self.layer_type = layer_type def forward(self, x): if self.layer_type == 'none': return x elif self.layer_type == 'timepreserve': return F.interpolate(x, scale_factor=(2, 1), mode='nearest') elif self.layer_type == 'half': return F.interpolate(x, scale_factor=2, mode='nearest') else: raise RuntimeError('Got unexpected upsampletype %s, expected is [none, timepreserve, half]' % self.layer_type) class ResBlk(nn.Module): def __init__(self, dim_in, dim_out, actv=nn.LeakyReLU(0.2), normalize=False, downsample='none'): super().__init__() self.actv = actv self.normalize = normalize self.downsample = DownSample(downsample) self.downsample_res = LearnedDownSample(downsample, dim_in) self.learned_sc = dim_in != dim_out self._build_weights(dim_in, dim_out) def _build_weights(self, dim_in, dim_out): self.conv1 = spectral_norm(nn.Conv2d(dim_in, dim_in, 3, 1, 1)) self.conv2 = spectral_norm(nn.Conv2d(dim_in, dim_out, 3, 1, 1)) if self.normalize: self.norm1 = nn.InstanceNorm2d(dim_in, affine=True) self.norm2 = nn.InstanceNorm2d(dim_in, affine=True) if self.learned_sc: self.conv1x1 = spectral_norm(nn.Conv2d(dim_in, dim_out, 1, 1, 0, bias=False)) def _shortcut(self, x): if self.learned_sc: x = self.conv1x1(x) if self.downsample: x = self.downsample(x) return x def _residual(self, x): if self.normalize: x = self.norm1(x) x = self.actv(x) x = self.conv1(x) x = self.downsample_res(x) if self.normalize: x = self.norm2(x) x = self.actv(x) x = self.conv2(x) return x def forward(self, x): x = self._shortcut(x) + self._residual(x) return x / math.sqrt(2) # unit variance class StyleEncoder(nn.Module): def __init__(self, dim_in=48, style_dim=48, max_conv_dim=384): super().__init__() blocks = [] blocks += [spectral_norm(nn.Conv2d(1, dim_in, 3, 1, 1))] repeat_num = 4 for _ in range(repeat_num): dim_out = min(dim_in*2, max_conv_dim) blocks += [ResBlk(dim_in, dim_out, downsample='half')] dim_in = dim_out blocks += [nn.LeakyReLU(0.2)] blocks += [spectral_norm(nn.Conv2d(dim_out, dim_out, 5, 1, 0))] blocks += [nn.AdaptiveAvgPool2d(1)] blocks += [nn.LeakyReLU(0.2)] self.shared = nn.Sequential(*blocks) self.unshared = nn.Linear(dim_out, style_dim) def forward(self, x): h = self.shared(x) h = h.view(h.size(0), -1) s = self.unshared(h) return s class LinearNorm(torch.nn.Module): def __init__(self, in_dim, out_dim, bias=True, w_init_gain='linear'): super(LinearNorm, self).__init__() self.linear_layer = torch.nn.Linear(in_dim, out_dim, bias=bias) torch.nn.init.xavier_uniform_( self.linear_layer.weight, gain=torch.nn.init.calculate_gain(w_init_gain)) def forward(self, x): return self.linear_layer(x) class Discriminator2d(nn.Module): def __init__(self, dim_in=48, num_domains=1, max_conv_dim=384, repeat_num=4): super().__init__() blocks = [] blocks += [spectral_norm(nn.Conv2d(1, dim_in, 3, 1, 1))] for lid in range(repeat_num): dim_out = min(dim_in*2, max_conv_dim) blocks += [ResBlk(dim_in, dim_out, downsample='half')] dim_in = dim_out blocks += [nn.LeakyReLU(0.2)] blocks += [spectral_norm(nn.Conv2d(dim_out, dim_out, 5, 1, 0))] blocks += [nn.LeakyReLU(0.2)] blocks += [nn.AdaptiveAvgPool2d(1)] blocks += [spectral_norm(nn.Conv2d(dim_out, num_domains, 1, 1, 0))] self.main = nn.Sequential(*blocks) def get_feature(self, x): features = [] for l in self.main: x = l(x) features.append(x) out = features[-1] out = out.view(out.size(0), -1) # (batch, num_domains) return out, features def forward(self, x): out, features = self.get_feature(x) out = out.squeeze() # (batch) return out, features class ResBlk1d(nn.Module): def __init__(self, dim_in, dim_out, actv=nn.LeakyReLU(0.2), normalize=False, downsample='none', dropout_p=0.2): super().__init__() self.actv = actv self.normalize = normalize self.downsample_type = downsample self.learned_sc = dim_in != dim_out self._build_weights(dim_in, dim_out) self.dropout_p = dropout_p if self.downsample_type == 'none': self.pool = nn.Identity() else: self.pool = weight_norm(nn.Conv1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1)) def _build_weights(self, dim_in, dim_out): self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_in, 3, 1, 1)) self.conv2 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1)) if self.normalize: self.norm1 = nn.InstanceNorm1d(dim_in, affine=True) self.norm2 = nn.InstanceNorm1d(dim_in, affine=True) if self.learned_sc: self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False)) def downsample(self, x): if self.downsample_type == 'none': return x else: if x.shape[-1] % 2 != 0: x = torch.cat([x, x[..., -1].unsqueeze(-1)], dim=-1) return F.avg_pool1d(x, 2) def _shortcut(self, x): if self.learned_sc: x = self.conv1x1(x) x = self.downsample(x) return x def _residual(self, x): if self.normalize: x = self.norm1(x) x = self.actv(x) x = F.dropout(x, p=self.dropout_p, training=self.training) x = self.conv1(x) x = self.pool(x) if self.normalize: x = self.norm2(x) x = self.actv(x) x = F.dropout(x, p=self.dropout_p, training=self.training) x = self.conv2(x) return x def forward(self, x): x = self._shortcut(x) + self._residual(x) return x / math.sqrt(2) # unit variance class LayerNorm(nn.Module): def __init__(self, channels, eps=1e-5): super().__init__() self.channels = channels self.eps = eps self.gamma = nn.Parameter(torch.ones(channels)) self.beta = nn.Parameter(torch.zeros(channels)) def forward(self, x): x = x.transpose(1, -1) x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps) return x.transpose(1, -1) class TextEncoder(nn.Module): def __init__(self, channels, kernel_size, depth, n_symbols, actv=nn.LeakyReLU(0.2)): super().__init__() self.embedding = nn.Embedding(n_symbols, channels) padding = (kernel_size - 1) // 2 self.cnn = nn.ModuleList() for _ in range(depth): self.cnn.append(nn.Sequential( weight_norm(nn.Conv1d(channels, channels, kernel_size=kernel_size, padding=padding)), LayerNorm(channels), actv, nn.Dropout(0.2), )) # self.cnn = nn.Sequential(*self.cnn) self.lstm = nn.LSTM(channels, channels//2, 1, batch_first=True, bidirectional=True) def forward(self, x, input_lengths, m): x = self.embedding(x) # [B, T, emb] x = x.transpose(1, 2) # [B, emb, T] m = m.to(input_lengths.device).unsqueeze(1) x.masked_fill_(m, 0.0) for c in self.cnn: x = c(x) x.masked_fill_(m, 0.0) x = x.transpose(1, 2) # [B, T, chn] input_lengths = input_lengths.cpu().numpy() x = nn.utils.rnn.pack_padded_sequence( x, input_lengths, batch_first=True, enforce_sorted=False) self.lstm.flatten_parameters() x, _ = self.lstm(x) x, _ = nn.utils.rnn.pad_packed_sequence( x, batch_first=True) x = x.transpose(-1, -2) x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]]) x_pad[:, :, :x.shape[-1]] = x x = x_pad.to(x.device) x.masked_fill_(m, 0.0) return x def inference(self, x): x = self.embedding(x) x = x.transpose(1, 2) x = self.cnn(x) x = x.transpose(1, 2) self.lstm.flatten_parameters() x, _ = self.lstm(x) return x def length_to_mask(self, lengths): mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) mask = torch.gt(mask+1, lengths.unsqueeze(1)) return mask class AdaIN1d(nn.Module): def __init__(self, style_dim, num_features): super().__init__() self.norm = nn.InstanceNorm1d(num_features, affine=False) self.fc = nn.Linear(style_dim, num_features*2) def forward(self, x, s): h = self.fc(s) h = h.view(h.size(0), h.size(1), 1) gamma, beta = torch.chunk(h, chunks=2, dim=1) return (1 + gamma) * self.norm(x) + beta class UpSample1d(nn.Module): def __init__(self, layer_type): super().__init__() self.layer_type = layer_type def forward(self, x): if self.layer_type == 'none': return x else: return F.interpolate(x, scale_factor=2, mode='nearest') class AdainResBlk1d(nn.Module): def __init__(self, dim_in, dim_out, style_dim=64, actv=nn.LeakyReLU(0.2), upsample='none', dropout_p=0.0): super().__init__() self.actv = actv self.upsample_type = upsample self.upsample = UpSample1d(upsample) self.learned_sc = dim_in != dim_out self._build_weights(dim_in, dim_out, style_dim) self.dropout = nn.Dropout(dropout_p) if upsample == 'none': self.pool = nn.Identity() else: self.pool = weight_norm(nn.ConvTranspose1d(dim_in, dim_in, kernel_size=3, stride=2, groups=dim_in, padding=1, output_padding=1)) def _build_weights(self, dim_in, dim_out, style_dim): self.conv1 = weight_norm(nn.Conv1d(dim_in, dim_out, 3, 1, 1)) self.conv2 = weight_norm(nn.Conv1d(dim_out, dim_out, 3, 1, 1)) self.norm1 = AdaIN1d(style_dim, dim_in) self.norm2 = AdaIN1d(style_dim, dim_out) if self.learned_sc: self.conv1x1 = weight_norm(nn.Conv1d(dim_in, dim_out, 1, 1, 0, bias=False)) def _shortcut(self, x): x = self.upsample(x) if self.learned_sc: x = self.conv1x1(x) return x def _residual(self, x, s): x = self.norm1(x, s) x = self.actv(x) x = self.pool(x) x = self.conv1(self.dropout(x)) x = self.norm2(x, s) x = self.actv(x) x = self.conv2(self.dropout(x)) return x def forward(self, x, s): out = self._residual(x, s) out = (out + self._shortcut(x)) / math.sqrt(2) return out class AdaLayerNorm(nn.Module): def __init__(self, style_dim, channels, eps=1e-5): super().__init__() self.channels = channels self.eps = eps self.fc = nn.Linear(style_dim, channels*2) def forward(self, x, s): x = x.transpose(-1, -2) x = x.transpose(1, -1) h = self.fc(s) h = h.view(h.size(0), h.size(1), 1) gamma, beta = torch.chunk(h, chunks=2, dim=1) gamma, beta = gamma.transpose(1, -1), beta.transpose(1, -1) x = F.layer_norm(x, (self.channels,), eps=self.eps) x = (1 + gamma) * x + beta return x.transpose(1, -1).transpose(-1, -2) class ProsodyPredictor(nn.Module): def __init__(self, style_dim, d_hid, nlayers, max_dur=50, dropout=0.1): super().__init__() self.text_encoder = DurationEncoder(sty_dim=style_dim, d_model=d_hid, nlayers=nlayers, dropout=dropout) self.lstm = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True) self.duration_proj = LinearNorm(d_hid, max_dur) self.shared = nn.LSTM(d_hid + style_dim, d_hid // 2, 1, batch_first=True, bidirectional=True) self.F0 = nn.ModuleList() self.F0.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout)) self.F0.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout)) self.F0.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout)) self.N = nn.ModuleList() self.N.append(AdainResBlk1d(d_hid, d_hid, style_dim, dropout_p=dropout)) self.N.append(AdainResBlk1d(d_hid, d_hid // 2, style_dim, upsample=True, dropout_p=dropout)) self.N.append(AdainResBlk1d(d_hid // 2, d_hid // 2, style_dim, dropout_p=dropout)) self.F0_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0) self.N_proj = nn.Conv1d(d_hid // 2, 1, 1, 1, 0) def forward(self, texts, style, text_lengths, alignment, m): d = self.text_encoder(texts, style, text_lengths, m) batch_size = d.shape[0] text_size = d.shape[1] # predict duration input_lengths = text_lengths.cpu().numpy() x = nn.utils.rnn.pack_padded_sequence( d, input_lengths, batch_first=True, enforce_sorted=False) m = m.to(text_lengths.device).unsqueeze(1) self.lstm.flatten_parameters() x, _ = self.lstm(x) x, _ = nn.utils.rnn.pad_packed_sequence( x, batch_first=True) x_pad = torch.zeros([x.shape[0], m.shape[-1], x.shape[-1]]) x_pad[:, :x.shape[1], :] = x x = x_pad.to(x.device) duration = self.duration_proj(nn.functional.dropout(x, 0.5, training=self.training)) en = (d.transpose(-1, -2) @ alignment) return duration.squeeze(-1), en def F0Ntrain(self, x, s): x, _ = self.shared(x.transpose(-1, -2)) F0 = x.transpose(-1, -2) for block in self.F0: F0 = block(F0, s) F0 = self.F0_proj(F0) N = x.transpose(-1, -2) for block in self.N: N = block(N, s) N = self.N_proj(N) return F0.squeeze(1), N.squeeze(1) def length_to_mask(self, lengths): mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) mask = torch.gt(mask+1, lengths.unsqueeze(1)) return mask class DurationEncoder(nn.Module): def __init__(self, sty_dim, d_model, nlayers, dropout=0.1): super().__init__() self.lstms = nn.ModuleList() for _ in range(nlayers): self.lstms.append(nn.LSTM(d_model + sty_dim, d_model // 2, num_layers=1, batch_first=True, bidirectional=True, dropout=dropout)) self.lstms.append(AdaLayerNorm(sty_dim, d_model)) self.dropout = dropout self.d_model = d_model self.sty_dim = sty_dim def forward(self, x, style, text_lengths, m): masks = m.to(text_lengths.device) x = x.permute(2, 0, 1) s = style.expand(x.shape[0], x.shape[1], -1) x = torch.cat([x, s], axis=-1) x.masked_fill_(masks.unsqueeze(-1).transpose(0, 1), 0.0) x = x.transpose(0, 1) input_lengths = text_lengths.cpu().numpy() x = x.transpose(-1, -2) for block in self.lstms: if isinstance(block, AdaLayerNorm): x = block(x.transpose(-1, -2), style).transpose(-1, -2) x = torch.cat([x, s.permute(1, -1, 0)], axis=1) x.masked_fill_(masks.unsqueeze(-1).transpose(-1, -2), 0.0) else: x = x.transpose(-1, -2) x = nn.utils.rnn.pack_padded_sequence( x, input_lengths, batch_first=True, enforce_sorted=False) block.flatten_parameters() x, _ = block(x) x, _ = nn.utils.rnn.pad_packed_sequence( x, batch_first=True) x = F.dropout(x, p=self.dropout, training=self.training) x = x.transpose(-1, -2) x_pad = torch.zeros([x.shape[0], x.shape[1], m.shape[-1]]) x_pad[:, :, :x.shape[-1]] = x x = x_pad.to(x.device) return x.transpose(-1, -2) def inference(self, x, style): x = self.embedding(x.transpose(-1, -2)) * math.sqrt(self.d_model) style = style.expand(x.shape[0], x.shape[1], -1) x = torch.cat([x, style], axis=-1) src = self.pos_encoder(x) output = self.transformer_encoder(src).transpose(0, 1) return output def length_to_mask(self, lengths): mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths) mask = torch.gt(mask+1, lengths.unsqueeze(1)) return mask def load_F0_models(path): # load F0 model
F0_model = JDCNet(num_class=1, seq_len=192)
1
2023-12-15 10:04:21+00:00
12k
alibaba/u2mot
yolox/tracker/u2mot_tracker.py
[ { "identifier": "BaseTrack", "path": "yolox/tracker/basetrack.py", "snippet": "class BaseTrack(object):\n _count = 0\n\n track_id = 0\n is_activated = False\n state = TrackState.New\n\n history = OrderedDict()\n features = []\n curr_feature = None\n score = 0\n start_frame = 0...
import numpy as np from collections import deque from .basetrack import BaseTrack, TrackState from .kalman_filter import KalmanFilter from .gmc import GMC from . import matching
7,874
# @jit(nopython=True) def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`. """ if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() # ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret @property # @jit(nopython=True) def tlbr(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[2:] += ret[:2] return ret @property def xywh(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[:2] += ret[2:] / 2.0 return ret @staticmethod # @jit(nopython=True) def tlwh_to_xyah(tlwh): """Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret @staticmethod def tlwh_to_xywh(tlwh): """Convert bounding box to format `(center x, center y, width, height)`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 return ret def to_xyah(self): return self.tlwh_to_xyah(self.tlwh) def to_xywh(self): return self.tlwh_to_xywh(self.tlwh) @staticmethod # @jit(nopython=True) def tlbr_to_tlwh(tlbr): ret = np.asarray(tlbr).copy() ret[2:] -= ret[:2] return ret @staticmethod # @jit(nopython=True) def tlwh_to_tlbr(tlwh): ret = np.asarray(tlwh).copy() ret[2:] += ret[:2] return ret def __repr__(self): return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame) class DefaultArgs(object): def __init__(self, mot20=False): self.track_thresh = 0.6 self.low_thresh = 0.1 self.track_buffer = 30 self.match_thresh = 0.8 self.mot20 = mot20 self.mask_emb_with_iou = True self.fuse_emb_and_iou = 'min' self.cmc_method = 'none' self.cmc_seq_name = '' self.cmc_file_dir = '' class U2MOTTracker(object): def __init__(self, args, frame_rate=30): self.tracked_stracks = [] # type: list[STrack] self.lost_stracks = [] # type: list[STrack] self.removed_stracks = [] # type: list[STrack] BaseTrack.clear_count() self.frame_id = 0 # self.args = args self.mot20 = args.mot20 # self.det_thresh = args.track_thresh + 0.1 self.track_high_thresh = args.track_thresh self.track_low_thresh = args.low_thresh self.new_track_thresh = args.track_thresh + 0.1 self.match_thresh = args.match_thresh self.buffer_size = int(frame_rate / 30.0 * args.track_buffer) self.max_time_lost = self.buffer_size self.kalman_filter = KalmanFilter() # ReID module self.iou_only = False self.mask_emb_with_iou = args.mask_emb_with_iou # default True self.fuse_emb_and_iou = args.fuse_emb_and_iou # default min, choice: [min, mean] self.proximity_thresh = 0.5 self.appearance_thresh = 0.25
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- # Copyright (c) Alibaba, Inc. and its affiliates. class STrack(BaseTrack): shared_kalman = KalmanFilter() def __init__(self, tlwh, score, cls=0, feat=None, feat_history=50): # wait activate self._tlwh = np.asarray(tlwh, dtype=np.float) self.kalman_filter = None self.mean, self.covariance = None, None self.is_activated = False self.cls = -1 self.cls_hist = [] # (cls id, freq) self.update_cls(cls, score) self.score = score self.tracklet_len = 0 self.smooth_feat = None self.curr_feat = None self.features = deque([], maxlen=feat_history) if feat is not None: self.update_features(feat) self.alpha = 0.9 def update_features(self, feat): feat /= np.linalg.norm(feat) self.curr_feat = feat if self.smooth_feat is None: self.smooth_feat = feat else: self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat self.features.append(feat) self.smooth_feat /= np.linalg.norm(self.smooth_feat) def update_cls(self, cls, score): if len(self.cls_hist) > 0: max_freq = 0 found = False for c in self.cls_hist: if cls == c[0]: c[1] += score found = True if c[1] > max_freq: max_freq = c[1] self.cls = c[0] if not found: self.cls_hist.append([cls, score]) self.cls = cls else: self.cls_hist.append([cls, score]) self.cls = cls def predict(self): mean_state = self.mean.copy() if self.state != TrackState.Tracked: mean_state[6] = 0 mean_state[7] = 0 self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance) @staticmethod def multi_predict(stracks): if len(stracks) > 0: multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) for i, st in enumerate(stracks): if st.state != TrackState.Tracked: multi_mean[i][6] = 0 multi_mean[i][7] = 0 multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance) for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): stracks[i].mean = mean stracks[i].covariance = cov @staticmethod def multi_gmc(stracks, H=np.eye(2, 3)): if len(stracks) > 0: multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) R = H[:2, :2] R8x8 = np.kron(np.eye(4, dtype=float), R) t = H[:2, 2] for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): mean = R8x8.dot(mean) mean[:2] += t cov = R8x8.dot(cov).dot(R8x8.transpose()) stracks[i].mean = mean stracks[i].covariance = cov def activate(self, kalman_filter, frame_id): """Start a new tracklet""" self.kalman_filter = kalman_filter self.track_id = self.next_id() # self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xyah(self._tlwh)) self.mean, self.covariance = self.kalman_filter.initiate(self.tlwh_to_xywh(self._tlwh)) self.tracklet_len = 0 self.state = TrackState.Tracked if frame_id == 1: self.is_activated = True # self.is_activated = True self.frame_id = frame_id self.start_frame = frame_id def re_activate(self, new_track, frame_id, new_id=False): # self.mean, self.covariance = self.kalman_filter.update( # self.mean, self.covariance, self.tlwh_to_xyah(new_track.tlwh) # ) self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, self.tlwh_to_xywh(new_track.tlwh)) if new_track.curr_feat is not None: self.update_features(new_track.curr_feat) self.tracklet_len = 0 self.state = TrackState.Tracked self.is_activated = True self.frame_id = frame_id if new_id: self.track_id = self.next_id() self.score = new_track.score self.update_cls(new_track.cls, new_track.score) def update(self, new_track, frame_id): """ Update a matched track :type new_track: STrack :type frame_id: int :type update_feature: bool :return: """ self.frame_id = frame_id self.tracklet_len += 1 new_tlwh = new_track.tlwh # self.mean, self.covariance = self.kalman_filter.update( # self.mean, self.covariance, self.tlwh_to_xyah(new_tlwh)) self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, self.tlwh_to_xywh(new_tlwh)) if new_track.curr_feat is not None: self.update_features(new_track.curr_feat) self.state = TrackState.Tracked self.is_activated = True self.score = new_track.score self.update_cls(new_track.cls, new_track.score) @property # @jit(nopython=True) def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`. """ if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() # ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret @property # @jit(nopython=True) def tlbr(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[2:] += ret[:2] return ret @property def xywh(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[:2] += ret[2:] / 2.0 return ret @staticmethod # @jit(nopython=True) def tlwh_to_xyah(tlwh): """Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret @staticmethod def tlwh_to_xywh(tlwh): """Convert bounding box to format `(center x, center y, width, height)`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 return ret def to_xyah(self): return self.tlwh_to_xyah(self.tlwh) def to_xywh(self): return self.tlwh_to_xywh(self.tlwh) @staticmethod # @jit(nopython=True) def tlbr_to_tlwh(tlbr): ret = np.asarray(tlbr).copy() ret[2:] -= ret[:2] return ret @staticmethod # @jit(nopython=True) def tlwh_to_tlbr(tlwh): ret = np.asarray(tlwh).copy() ret[2:] += ret[:2] return ret def __repr__(self): return 'OT_{}_({}-{})'.format(self.track_id, self.start_frame, self.end_frame) class DefaultArgs(object): def __init__(self, mot20=False): self.track_thresh = 0.6 self.low_thresh = 0.1 self.track_buffer = 30 self.match_thresh = 0.8 self.mot20 = mot20 self.mask_emb_with_iou = True self.fuse_emb_and_iou = 'min' self.cmc_method = 'none' self.cmc_seq_name = '' self.cmc_file_dir = '' class U2MOTTracker(object): def __init__(self, args, frame_rate=30): self.tracked_stracks = [] # type: list[STrack] self.lost_stracks = [] # type: list[STrack] self.removed_stracks = [] # type: list[STrack] BaseTrack.clear_count() self.frame_id = 0 # self.args = args self.mot20 = args.mot20 # self.det_thresh = args.track_thresh + 0.1 self.track_high_thresh = args.track_thresh self.track_low_thresh = args.low_thresh self.new_track_thresh = args.track_thresh + 0.1 self.match_thresh = args.match_thresh self.buffer_size = int(frame_rate / 30.0 * args.track_buffer) self.max_time_lost = self.buffer_size self.kalman_filter = KalmanFilter() # ReID module self.iou_only = False self.mask_emb_with_iou = args.mask_emb_with_iou # default True self.fuse_emb_and_iou = args.fuse_emb_and_iou # default min, choice: [min, mean] self.proximity_thresh = 0.5 self.appearance_thresh = 0.25
self.gmc = GMC(method=args.cmc_method,
3
2023-12-18 10:04:40+00:00
12k
liuhuang31/HiFTNet-sr
train.py
[ { "identifier": "AttrDict", "path": "env.py", "snippet": "class AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self" }, { "identifier": "build_env", "path": "env.py", "snippet": "def build_env(co...
import warnings import itertools import os import time import argparse import json import torch import torch.nn.functional as F import torch.multiprocessing as mp from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DistributedSampler, DataLoader from torch.distributed import init_process_group from torch.nn.parallel import DistributedDataParallel from env import AttrDict, build_env from meldataset import MelDataset, mel_spectrogram, get_dataset_filelist from models import Generator, MultiPeriodDiscriminator, MultiResSpecDiscriminator, feature_loss, generator_loss,\ discriminator_loss, discriminator_TPRLS_loss, generator_TPRLS_loss from utils import plot_spectrogram, scan_checkpoint, load_checkpoint, save_checkpoint from stft import TorchSTFT from Utils.JDC.model import JDCNet
7,449
warnings.simplefilter(action='ignore', category=FutureWarning) torch.backends.cudnn.benchmark = True def train(rank, a, h): if h.num_gpus > 1: init_process_group(backend=h.dist_config['dist_backend'], init_method=h.dist_config['dist_url'], world_size=h.dist_config['world_size'] * h.num_gpus, rank=rank) torch.cuda.manual_seed(h.seed) device = torch.device('cuda:{:d}'.format(rank)) F0_model = JDCNet(num_class=1, seq_len=192) params = torch.load(h.F0_path)['model'] F0_model.load_state_dict(params) generator = Generator(h, F0_model).to(device) mpd = MultiPeriodDiscriminator().to(device) msd = MultiResSpecDiscriminator().to(device) stft = TorchSTFT(filter_length=h.gen_istft_n_fft, hop_length=h.gen_istft_hop_size, win_length=h.gen_istft_n_fft).to(device) if rank == 0: print(generator) os.makedirs(a.checkpoint_path, exist_ok=True) print("checkpoints directory : ", a.checkpoint_path) if os.path.isdir(a.checkpoint_path): cp_g = scan_checkpoint(a.checkpoint_path, 'g_') cp_do = scan_checkpoint(a.checkpoint_path, 'do_') steps = 0 if cp_g is None or cp_do is None: state_dict_do = None last_epoch = -1 else: state_dict_g = load_checkpoint(cp_g, device) state_dict_do = load_checkpoint(cp_do, device) generator.load_state_dict(state_dict_g['generator']) mpd.load_state_dict(state_dict_do['mpd']) msd.load_state_dict(state_dict_do['msd']) steps = state_dict_do['steps'] + 1 last_epoch = state_dict_do['epoch'] if h.num_gpus > 1: generator = DistributedDataParallel(generator, device_ids=[rank], find_unused_parameters=True).to(device) mpd = DistributedDataParallel(mpd, device_ids=[rank]).to(device) msd = DistributedDataParallel(msd, device_ids=[rank]).to(device) optim_g = torch.optim.AdamW(generator.parameters(), h.learning_rate, betas=[h.adam_b1, h.adam_b2]) optim_d = torch.optim.AdamW(itertools.chain(msd.parameters(), mpd.parameters()), h.learning_rate, betas=[h.adam_b1, h.adam_b2]) if state_dict_do is not None: optim_g.load_state_dict(state_dict_do['optim_g']) optim_d.load_state_dict(state_dict_do['optim_d']) scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=h.lr_decay, last_epoch=last_epoch) scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=h.lr_decay, last_epoch=last_epoch) training_filelist, validation_filelist = get_dataset_filelist(a)
warnings.simplefilter(action='ignore', category=FutureWarning) torch.backends.cudnn.benchmark = True def train(rank, a, h): if h.num_gpus > 1: init_process_group(backend=h.dist_config['dist_backend'], init_method=h.dist_config['dist_url'], world_size=h.dist_config['world_size'] * h.num_gpus, rank=rank) torch.cuda.manual_seed(h.seed) device = torch.device('cuda:{:d}'.format(rank)) F0_model = JDCNet(num_class=1, seq_len=192) params = torch.load(h.F0_path)['model'] F0_model.load_state_dict(params) generator = Generator(h, F0_model).to(device) mpd = MultiPeriodDiscriminator().to(device) msd = MultiResSpecDiscriminator().to(device) stft = TorchSTFT(filter_length=h.gen_istft_n_fft, hop_length=h.gen_istft_hop_size, win_length=h.gen_istft_n_fft).to(device) if rank == 0: print(generator) os.makedirs(a.checkpoint_path, exist_ok=True) print("checkpoints directory : ", a.checkpoint_path) if os.path.isdir(a.checkpoint_path): cp_g = scan_checkpoint(a.checkpoint_path, 'g_') cp_do = scan_checkpoint(a.checkpoint_path, 'do_') steps = 0 if cp_g is None or cp_do is None: state_dict_do = None last_epoch = -1 else: state_dict_g = load_checkpoint(cp_g, device) state_dict_do = load_checkpoint(cp_do, device) generator.load_state_dict(state_dict_g['generator']) mpd.load_state_dict(state_dict_do['mpd']) msd.load_state_dict(state_dict_do['msd']) steps = state_dict_do['steps'] + 1 last_epoch = state_dict_do['epoch'] if h.num_gpus > 1: generator = DistributedDataParallel(generator, device_ids=[rank], find_unused_parameters=True).to(device) mpd = DistributedDataParallel(mpd, device_ids=[rank]).to(device) msd = DistributedDataParallel(msd, device_ids=[rank]).to(device) optim_g = torch.optim.AdamW(generator.parameters(), h.learning_rate, betas=[h.adam_b1, h.adam_b2]) optim_d = torch.optim.AdamW(itertools.chain(msd.parameters(), mpd.parameters()), h.learning_rate, betas=[h.adam_b1, h.adam_b2]) if state_dict_do is not None: optim_g.load_state_dict(state_dict_do['optim_g']) optim_d.load_state_dict(state_dict_do['optim_d']) scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=h.lr_decay, last_epoch=last_epoch) scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=h.lr_decay, last_epoch=last_epoch) training_filelist, validation_filelist = get_dataset_filelist(a)
trainset = MelDataset(training_filelist, h.segment_size, h.n_fft, h.num_mels,
2
2023-12-16 03:53:55+00:00
12k
UnbSky/Hanabi-AI-Assitant
main_connect.py
[ { "identifier": "AIWindow", "path": "game_ui.py", "snippet": "class AIWindow(QMainWindow, Ui_AIUI):\n def __init__(self, url, cookie, model_data=None):\n super().__init__()\n self.setupUi(self)\n #self.setFixedSize(1300, 1200)\n self.setWindowTitle(\"HanabiAIAssitant\")\n\...
import sys import json import requests from PyQt5 import QtWidgets, QtCore from game_ui import AIWindow from play_util import load_model
8,830
def printf(*args): print(*args, flush=True) # Imports (3rd-party) # Imports (local application) # Authenticate, login to the WebSocket server, and run forever. def login_to_hanab(username, password): if username == "": printf('error: "HANABI_USERNAME" is blank in the ".env" file') sys.exit(1) if password == "": printf('error: "HANABI_PASSWORD" is blank in the ".env" file') sys.exit(1) # The official site uses HTTPS. protocol = "https" ws_protocol = "wss" host = "hanab.live" path = "/login" ws_path = "/ws" url = protocol + "://" + host + path ws_url = ws_protocol + "://" + host + ws_path printf('Authenticating to "' + url + '" with a username of "' + username + '".') resp = requests.post( url, { "username": username, "password": password, # This is normally supposed to be the version of the JavaScript # client, but the server will also accept "bot" as a valid version. "version": "bot", }, ) # Handle failed authentication and other errors. if resp.status_code != 200: printf("Authentication failed:") printf(resp.text) sys.exit(1) # Scrape the cookie from the response. cookie = "" for header in resp.headers.items(): if header[0] == "Set-Cookie": cookie = header[1] break if cookie == "": printf("Failed to parse the cookie from the authentication response headers:") printf(resp.headers) sys.exit(1) return ws_url, cookie def main(): with open(f'user_config.json', 'r') as json_file: user_args = json.load(json_file) username = user_args["username"] password = user_args["password"] model_name = user_args["model"] printf("Load Model") model, action_dict_toact, action_dict_toid, output_action_dict_toact, output_action_dict_toid, device = load_model(model_name) printf("Try Login") ws_url, cookie = login_to_hanab(username, password) printf("Launch UI") #QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) app = QtWidgets.QApplication(sys.argv)
def printf(*args): print(*args, flush=True) # Imports (3rd-party) # Imports (local application) # Authenticate, login to the WebSocket server, and run forever. def login_to_hanab(username, password): if username == "": printf('error: "HANABI_USERNAME" is blank in the ".env" file') sys.exit(1) if password == "": printf('error: "HANABI_PASSWORD" is blank in the ".env" file') sys.exit(1) # The official site uses HTTPS. protocol = "https" ws_protocol = "wss" host = "hanab.live" path = "/login" ws_path = "/ws" url = protocol + "://" + host + path ws_url = ws_protocol + "://" + host + ws_path printf('Authenticating to "' + url + '" with a username of "' + username + '".') resp = requests.post( url, { "username": username, "password": password, # This is normally supposed to be the version of the JavaScript # client, but the server will also accept "bot" as a valid version. "version": "bot", }, ) # Handle failed authentication and other errors. if resp.status_code != 200: printf("Authentication failed:") printf(resp.text) sys.exit(1) # Scrape the cookie from the response. cookie = "" for header in resp.headers.items(): if header[0] == "Set-Cookie": cookie = header[1] break if cookie == "": printf("Failed to parse the cookie from the authentication response headers:") printf(resp.headers) sys.exit(1) return ws_url, cookie def main(): with open(f'user_config.json', 'r') as json_file: user_args = json.load(json_file) username = user_args["username"] password = user_args["password"] model_name = user_args["model"] printf("Load Model") model, action_dict_toact, action_dict_toid, output_action_dict_toact, output_action_dict_toid, device = load_model(model_name) printf("Try Login") ws_url, cookie = login_to_hanab(username, password) printf("Launch UI") #QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) app = QtWidgets.QApplication(sys.argv)
MyUiStart = AIWindow(ws_url, cookie, [model, action_dict_toact, action_dict_toid, output_action_dict_toact, output_action_dict_toid, device])
0
2023-12-17 03:57:47+00:00
12k
m-abr/FCPCodebase
communication/Radio.py
[ { "identifier": "Other_Robot", "path": "world/commons/Other_Robot.py", "snippet": "class Other_Robot():\n def __init__(self, unum, is_teammate) -> None:\n self.unum = unum # convenient variable to indicate uniform number (same as other robot's index + 1)\n self.is_self = ...
from typing import List from world.commons.Other_Robot import Other_Robot from world.World import World import numpy as np
8,222
class Radio(): ''' map limits are hardcoded: teammates/opponents positions (x,y) in ([-16,16],[-11,11]) ball position (x,y) in ([-15,15],[-10,10]) known server limitations: claimed: all ascii from 0x20 to 0x7E except ' ', '(', ')' bugs: - ' or " clip the message - '\' at the end or near another '\' - ';' at beginning of message ''' # map limits are hardcoded: # lines, columns, half lines index, half cols index, (lines-1)/x_span, (cols-1)/y_span, combinations, combinations*2states, TP = 321,221,160,110,10, 10,70941,141882 # teammate position OP = 201,111,100,55, 6.25,5, 22311,44622 # opponent position BP = 301,201,150,100,10, 10,60501 # ball position SYMB = "!#$%&*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~;" SLEN = len(SYMB) SYMB_TO_IDX = {ord(s):i for i,s in enumerate(SYMB)} def __init__(self, world : World, commit_announcement) -> None: self.world = world self.commit_announcement = commit_announcement r = world.robot t = world.teammates o = world.opponents self.groups = ( # player team/unum, group has ball?, self in group? [(t[9],t[10],o[6],o[7],o[8],o[9],o[10]), True ], # 2 teammates, 5 opponents, ball [(t[0],t[1], t[2],t[3],t[4],t[5],t[6] ), False], # 7 teammates [(t[7],t[8], o[0],o[1],o[2],o[3],o[4],o[5]), False] # 2 teammates, 6 opponents ) for g in self.groups: # add 'self in group?' g.append(any(i.is_self for i in g[0])) def get_player_combination(self, pos, is_unknown, is_down, info): ''' Returns combination (0-based) and number of possible combinations ''' if is_unknown: return info[7]+1, info[7]+2 # return unknown combination x,y = pos[:2] if x < -17 or x > 17 or y < -12 or y > 12: return info[7], info[7]+2 # return out of bounds combination (if it exceeds 1m in any axis) # convert to int to avoid overflow later l = int(np.clip( round(info[4]*x+info[2]), 0, info[0]-1 )) # absorb out of bounds positions (up to 1m in each axis) c = int(np.clip( round(info[5]*y+info[3]), 0, info[1]-1 )) return (l*info[1]+c)+(info[6] if is_down else 0), info[7]+2 # return valid combination def get_ball_combination(self, x, y): ''' Returns combination (0-based) and number of possible combinations ''' # if ball is out of bounds, we force it in l = int(np.clip( round(Radio.BP[4]*x+Radio.BP[2]), 0, Radio.BP[0]-1 )) c = int(np.clip( round(Radio.BP[5]*y+Radio.BP[3]), 0, Radio.BP[1]-1 )) return l*Radio.BP[1]+c, Radio.BP[6] # return valid combination def get_ball_position(self,comb): l = comb // Radio.BP[1] c = comb % Radio.BP[1] return np.array([l/Radio.BP[4]-15, c/Radio.BP[5]-10, 0.042]) # assume ball is on ground def get_player_position(self,comb, info): if comb == info[7]: return -1 # player is out of bounds if comb == info[7]+1: return -2 # player is in unknown location is_down = comb >= info[6] if is_down: comb -= info[6] l = comb // info[1] c = comb % info[1] return l/info[4]-16, c/info[5]-11, is_down def check_broadcast_requirements(self): ''' Check if broadcast group is valid Returns ------- ready : bool True if all requirements are met Sequence: g0,g1,g2, ig0,ig1,ig2, iig0,iig1,iig2 (whole cycle: 0.36s) igx means 'incomplete group', where <=1 element can be MIA recently iigx means 'very incomplete group', where <=2 elements can be MIA recently Rationale: prevent incomplete messages from monopolizing the broadcast space However: - 1st round: when 0 group members are missing, that group will update 3 times every 0.36s - 2nd round: when 1 group member is recently missing, that group will update 2 times every 0.36s - 3rd round: when 2 group members are recently missing, that group will update 1 time every 0.36s - when >2 group members are recently missing, that group will not be updated Players that have never been seen or heard are not considered for the 'recently missing'. If there is only 1 group member since the beginning, the respective group can be updated, except in the 1st round. In this way, the 1st round cannot be monopolized by clueless agents, which is important during games with 22 players. ''' w = self.world r = w.robot ago40ms = w.time_local_ms - 40 ago370ms = w.time_local_ms - 370 # maximum delay (up to 2 MIAs) is 360ms because radio has a delay of 20ms (otherwise max delay would be 340ms)
class Radio(): ''' map limits are hardcoded: teammates/opponents positions (x,y) in ([-16,16],[-11,11]) ball position (x,y) in ([-15,15],[-10,10]) known server limitations: claimed: all ascii from 0x20 to 0x7E except ' ', '(', ')' bugs: - ' or " clip the message - '\' at the end or near another '\' - ';' at beginning of message ''' # map limits are hardcoded: # lines, columns, half lines index, half cols index, (lines-1)/x_span, (cols-1)/y_span, combinations, combinations*2states, TP = 321,221,160,110,10, 10,70941,141882 # teammate position OP = 201,111,100,55, 6.25,5, 22311,44622 # opponent position BP = 301,201,150,100,10, 10,60501 # ball position SYMB = "!#$%&*+,-./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~;" SLEN = len(SYMB) SYMB_TO_IDX = {ord(s):i for i,s in enumerate(SYMB)} def __init__(self, world : World, commit_announcement) -> None: self.world = world self.commit_announcement = commit_announcement r = world.robot t = world.teammates o = world.opponents self.groups = ( # player team/unum, group has ball?, self in group? [(t[9],t[10],o[6],o[7],o[8],o[9],o[10]), True ], # 2 teammates, 5 opponents, ball [(t[0],t[1], t[2],t[3],t[4],t[5],t[6] ), False], # 7 teammates [(t[7],t[8], o[0],o[1],o[2],o[3],o[4],o[5]), False] # 2 teammates, 6 opponents ) for g in self.groups: # add 'self in group?' g.append(any(i.is_self for i in g[0])) def get_player_combination(self, pos, is_unknown, is_down, info): ''' Returns combination (0-based) and number of possible combinations ''' if is_unknown: return info[7]+1, info[7]+2 # return unknown combination x,y = pos[:2] if x < -17 or x > 17 or y < -12 or y > 12: return info[7], info[7]+2 # return out of bounds combination (if it exceeds 1m in any axis) # convert to int to avoid overflow later l = int(np.clip( round(info[4]*x+info[2]), 0, info[0]-1 )) # absorb out of bounds positions (up to 1m in each axis) c = int(np.clip( round(info[5]*y+info[3]), 0, info[1]-1 )) return (l*info[1]+c)+(info[6] if is_down else 0), info[7]+2 # return valid combination def get_ball_combination(self, x, y): ''' Returns combination (0-based) and number of possible combinations ''' # if ball is out of bounds, we force it in l = int(np.clip( round(Radio.BP[4]*x+Radio.BP[2]), 0, Radio.BP[0]-1 )) c = int(np.clip( round(Radio.BP[5]*y+Radio.BP[3]), 0, Radio.BP[1]-1 )) return l*Radio.BP[1]+c, Radio.BP[6] # return valid combination def get_ball_position(self,comb): l = comb // Radio.BP[1] c = comb % Radio.BP[1] return np.array([l/Radio.BP[4]-15, c/Radio.BP[5]-10, 0.042]) # assume ball is on ground def get_player_position(self,comb, info): if comb == info[7]: return -1 # player is out of bounds if comb == info[7]+1: return -2 # player is in unknown location is_down = comb >= info[6] if is_down: comb -= info[6] l = comb // info[1] c = comb % info[1] return l/info[4]-16, c/info[5]-11, is_down def check_broadcast_requirements(self): ''' Check if broadcast group is valid Returns ------- ready : bool True if all requirements are met Sequence: g0,g1,g2, ig0,ig1,ig2, iig0,iig1,iig2 (whole cycle: 0.36s) igx means 'incomplete group', where <=1 element can be MIA recently iigx means 'very incomplete group', where <=2 elements can be MIA recently Rationale: prevent incomplete messages from monopolizing the broadcast space However: - 1st round: when 0 group members are missing, that group will update 3 times every 0.36s - 2nd round: when 1 group member is recently missing, that group will update 2 times every 0.36s - 3rd round: when 2 group members are recently missing, that group will update 1 time every 0.36s - when >2 group members are recently missing, that group will not be updated Players that have never been seen or heard are not considered for the 'recently missing'. If there is only 1 group member since the beginning, the respective group can be updated, except in the 1st round. In this way, the 1st round cannot be monopolized by clueless agents, which is important during games with 22 players. ''' w = self.world r = w.robot ago40ms = w.time_local_ms - 40 ago370ms = w.time_local_ms - 370 # maximum delay (up to 2 MIAs) is 360ms because radio has a delay of 20ms (otherwise max delay would be 340ms)
group : List[Other_Robot]
0
2023-12-16 23:40:23+00:00
12k
quocanh34/magic-animate-modified
magicanimate/models/unet_controlnet.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "magicanimate/models/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n num_la...
from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from magicanimate.models.unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from .resnet import InflatedConv3d from diffusers.utils import WEIGHTS_NAME import os import json import torch import torch.nn as nn import torch.utils.checkpoint
7,794
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: 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: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # 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) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i 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, in_channels=input_channel, out_channels=output_channel, temb_channels=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, attn_num_head_channels=attention_head_dim[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, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn":
# ************************************************************************* # This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo- # difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B- # ytedance Inc.. # ************************************************************************* # 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. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): _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: 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: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # 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) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i 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, in_channels=input_channel, out_channels=output_channel, temb_channels=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, attn_num_head_channels=attention_head_dim[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, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn":
self.mid_block = UNetMidBlock3DCrossAttn(
3
2023-12-15 01:22:37+00:00
12k
cvlab-yonsei/RankMixup
calibrate/evaluation/calibrate_evaluator.py
[ { "identifier": "DatasetEvaluator", "path": "calibrate/evaluation/evaluator.py", "snippet": "class DatasetEvaluator(metaclass=ABCMeta):\n \"\"\"\n Base class for a dataset evaluator\n \"\"\"\n @abstractmethod\n def reset(self):\n \"\"\"\n Preparation for a new round of evalu...
import logging import numpy as np import torch import torch.nn.functional as F import wandb from terminaltables import AsciiTable from torch import nn from .evaluator import DatasetEvaluator from .metrics import ECELoss, AdaptiveECELoss, ClasswiseECELoss, OELoss, UELoss from .reliability_diagram import ReliabilityDiagram from calibrate.utils.torch_helper import to_numpy
9,641
logger = logging.getLogger(__name__) class CalibrateEvaluator(DatasetEvaluator): def __init__(self, num_classes, num_bins=15, device="cuda:0") -> None: self.num_classes = num_classes self.num_bins = num_bins self.device = device self.reset() def reset(self) -> None: self.logits = None self.labels = None def num_samples(self): return ( self.labels.shape[0] if self.labels is not None else 0 ) def main_metric(self) -> None: return "ece" def update(self, logits: torch.Tensor, labels: torch.Tensor) -> None: """update Args: logits (torch.Tensor): n x num_classes label (torch.Tensor): n x 1 """ assert logits.shape[0] == labels.shape[0] if self.logits is None: self.logits = logits self.labels = labels else: self.logits = torch.cat((self.logits, logits), dim=0) self.labels = torch.cat((self.labels, labels), dim=0) def mean_score(self, print=False, all_metric=True): nll_criterion = nn.CrossEntropyLoss().to(self.device) ece_criterion = ECELoss(self.num_bins).to(self.device) aece_criterion = AdaptiveECELoss(self.num_bins).to(self.device) cece_criterion = ClasswiseECELoss(self.num_bins).to(self.device) oe_criterion = OELoss(self.num_bins).to(self.device) ue_criterion = UELoss(self.num_bins).to(self.device) nll = nll_criterion(self.logits, self.labels).item() ece = ece_criterion(self.logits, self.labels).item() aece = aece_criterion(self.logits, self.labels).item() cece = cece_criterion(self.logits, self.labels).item() oe = oe_criterion(self.logits, self.labels).item() ue = ue_criterion(self.logits, self.labels).item() # metric = {"nll": nll, "ece": ece, "aece": aece, "cece": cece} metric = {"nll": nll, "ece": ece, "aece": aece, "cece": cece, "oe": oe, "ue": ue} # columns = ["samples", "nll", "ece", "aece", "cece"] columns = ["samples", "nll", "ece", "aece", "cece", "oe", "ue"] table_data = [columns] # table_data.append( # [ # self.num_samples(), # "{:.5f}".format(nll), # "{:.5f}".format(ece), # "{:.5f}".format(aece), # "{:.5f}".format(cece), # ] # ) table_data.append( [ self.num_samples(), "{:.5f}".format(nll), "{:.5f}".format(ece), "{:.5f}".format(aece), "{:.5f}".format(cece), "{:.5f}".format(oe), "{:.5f}".format(ue), ] ) if print: table = AsciiTable(table_data) logger.info("\n" + table.table) if all_metric: return metric, table_data else: return metric[self.main_metric()] def wandb_score_table(self): _, table_data = self.mean_score(print=False) return wandb.Table( columns=table_data[0], data=table_data[1:] ) def plot_reliability_diagram(self, title=""):
logger = logging.getLogger(__name__) class CalibrateEvaluator(DatasetEvaluator): def __init__(self, num_classes, num_bins=15, device="cuda:0") -> None: self.num_classes = num_classes self.num_bins = num_bins self.device = device self.reset() def reset(self) -> None: self.logits = None self.labels = None def num_samples(self): return ( self.labels.shape[0] if self.labels is not None else 0 ) def main_metric(self) -> None: return "ece" def update(self, logits: torch.Tensor, labels: torch.Tensor) -> None: """update Args: logits (torch.Tensor): n x num_classes label (torch.Tensor): n x 1 """ assert logits.shape[0] == labels.shape[0] if self.logits is None: self.logits = logits self.labels = labels else: self.logits = torch.cat((self.logits, logits), dim=0) self.labels = torch.cat((self.labels, labels), dim=0) def mean_score(self, print=False, all_metric=True): nll_criterion = nn.CrossEntropyLoss().to(self.device) ece_criterion = ECELoss(self.num_bins).to(self.device) aece_criterion = AdaptiveECELoss(self.num_bins).to(self.device) cece_criterion = ClasswiseECELoss(self.num_bins).to(self.device) oe_criterion = OELoss(self.num_bins).to(self.device) ue_criterion = UELoss(self.num_bins).to(self.device) nll = nll_criterion(self.logits, self.labels).item() ece = ece_criterion(self.logits, self.labels).item() aece = aece_criterion(self.logits, self.labels).item() cece = cece_criterion(self.logits, self.labels).item() oe = oe_criterion(self.logits, self.labels).item() ue = ue_criterion(self.logits, self.labels).item() # metric = {"nll": nll, "ece": ece, "aece": aece, "cece": cece} metric = {"nll": nll, "ece": ece, "aece": aece, "cece": cece, "oe": oe, "ue": ue} # columns = ["samples", "nll", "ece", "aece", "cece"] columns = ["samples", "nll", "ece", "aece", "cece", "oe", "ue"] table_data = [columns] # table_data.append( # [ # self.num_samples(), # "{:.5f}".format(nll), # "{:.5f}".format(ece), # "{:.5f}".format(aece), # "{:.5f}".format(cece), # ] # ) table_data.append( [ self.num_samples(), "{:.5f}".format(nll), "{:.5f}".format(ece), "{:.5f}".format(aece), "{:.5f}".format(cece), "{:.5f}".format(oe), "{:.5f}".format(ue), ] ) if print: table = AsciiTable(table_data) logger.info("\n" + table.table) if all_metric: return metric, table_data else: return metric[self.main_metric()] def wandb_score_table(self): _, table_data = self.mean_score(print=False) return wandb.Table( columns=table_data[0], data=table_data[1:] ) def plot_reliability_diagram(self, title=""):
diagram = ReliabilityDiagram(bins=25, style="curve")
6
2023-12-17 13:53:18+00:00
12k
mjavadpur/Sadtalker_LongVideos
src/face3d/models/facerecon_model.py
[ { "identifier": "BaseModel", "path": "src/face3d/models/base_model.py", "snippet": "class BaseModel(ABC):\n \"\"\"This class is an abstract base class (ABC) for models.\n To create a subclass, you need to implement the following five functions:\n -- <__init__>: initiali...
import numpy as np import torch import trimesh from src.face3d.models.base_model import BaseModel from src.face3d.models import networks from src.face3d.models.bfm import ParametricFaceModel from src.face3d.models.losses import perceptual_loss, photo_loss, reg_loss, reflectance_loss, landmark_loss from src.face3d.util import util from src.face3d.util.nvdiffrast import MeshRenderer from scipy.io import savemat
10,773
"""This script defines the face reconstruction model for Deep3DFaceRecon_pytorch """ # from src.face3d.util.preprocess import estimate_norm_torch class FaceReconModel(BaseModel): @staticmethod def modify_commandline_options(parser, is_train=False): """ Configures options specific for CUT model """ # net structure and parameters parser.add_argument('--net_recon', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50'], help='network structure') parser.add_argument('--init_path', type=str, default='./checkpoints/init_model/resnet50-0676ba61.pth') parser.add_argument('--use_last_fc', type=util.str2bool, nargs='?', const=True, default=False, help='zero initialize the last fc') parser.add_argument('--bfm_folder', type=str, default='./checkpoints/BFM_Fitting/') parser.add_argument('--bfm_model', type=str, default='BFM_model_front.mat', help='bfm model') # renderer parameters parser.add_argument('--focal', type=float, default=1015.) parser.add_argument('--center', type=float, default=112.) parser.add_argument('--camera_d', type=float, default=10.) parser.add_argument('--z_near', type=float, default=5.) parser.add_argument('--z_far', type=float, default=15.) if is_train: # training parameters parser.add_argument('--net_recog', type=str, default='r50', choices=['r18', 'r43', 'r50'], help='face recog network structure') parser.add_argument('--net_recog_path', type=str, default='checkpoints/recog_model/ms1mv3_arcface_r50_fp16/backbone.pth') parser.add_argument('--use_crop_face', type=util.str2bool, nargs='?', const=True, default=False, help='use crop mask for photo loss') parser.add_argument('--use_predef_M', type=util.str2bool, nargs='?', const=True, default=False, help='use predefined M for predicted face') # augmentation parameters parser.add_argument('--shift_pixs', type=float, default=10., help='shift pixels') parser.add_argument('--scale_delta', type=float, default=0.1, help='delta scale factor') parser.add_argument('--rot_angle', type=float, default=10., help='rot angles, degree') # loss weights parser.add_argument('--w_feat', type=float, default=0.2, help='weight for feat loss') parser.add_argument('--w_color', type=float, default=1.92, help='weight for loss loss') parser.add_argument('--w_reg', type=float, default=3.0e-4, help='weight for reg loss') parser.add_argument('--w_id', type=float, default=1.0, help='weight for id_reg loss') parser.add_argument('--w_exp', type=float, default=0.8, help='weight for exp_reg loss') parser.add_argument('--w_tex', type=float, default=1.7e-2, help='weight for tex_reg loss') parser.add_argument('--w_gamma', type=float, default=10.0, help='weight for gamma loss') parser.add_argument('--w_lm', type=float, default=1.6e-3, help='weight for lm loss') parser.add_argument('--w_reflc', type=float, default=5.0, help='weight for reflc loss') opt, _ = parser.parse_known_args() parser.set_defaults( focal=1015., center=112., camera_d=10., use_last_fc=False, z_near=5., z_far=15. ) if is_train: parser.set_defaults( use_crop_face=True, use_predef_M=False ) return parser def __init__(self, opt): """Initialize this model class. Parameters: opt -- training/test options A few things can be done here. - (required) call the initialization function of BaseModel - define loss function, visualization images, model names, and optimizers """ BaseModel.__init__(self, opt) # call the initialization method of BaseModel self.visual_names = ['output_vis'] self.model_names = ['net_recon'] self.parallel_names = self.model_names + ['renderer'] self.facemodel = ParametricFaceModel( bfm_folder=opt.bfm_folder, camera_distance=opt.camera_d, focal=opt.focal, center=opt.center, is_train=self.isTrain, default_name=opt.bfm_model ) fov = 2 * np.arctan(opt.center / opt.focal) * 180 / np.pi self.renderer = MeshRenderer( rasterize_fov=fov, znear=opt.z_near, zfar=opt.z_far, rasterize_size=int(2 * opt.center) ) if self.isTrain: self.loss_names = ['all', 'feat', 'color', 'lm', 'reg', 'gamma', 'reflc'] self.net_recog = networks.define_net_recog( net_recog=opt.net_recog, pretrained_path=opt.net_recog_path ) # loss func name: (compute_%s_loss) % loss_name self.compute_feat_loss = perceptual_loss self.comupte_color_loss = photo_loss self.compute_lm_loss = landmark_loss self.compute_reg_loss = reg_loss
"""This script defines the face reconstruction model for Deep3DFaceRecon_pytorch """ # from src.face3d.util.preprocess import estimate_norm_torch class FaceReconModel(BaseModel): @staticmethod def modify_commandline_options(parser, is_train=False): """ Configures options specific for CUT model """ # net structure and parameters parser.add_argument('--net_recon', type=str, default='resnet50', choices=['resnet18', 'resnet34', 'resnet50'], help='network structure') parser.add_argument('--init_path', type=str, default='./checkpoints/init_model/resnet50-0676ba61.pth') parser.add_argument('--use_last_fc', type=util.str2bool, nargs='?', const=True, default=False, help='zero initialize the last fc') parser.add_argument('--bfm_folder', type=str, default='./checkpoints/BFM_Fitting/') parser.add_argument('--bfm_model', type=str, default='BFM_model_front.mat', help='bfm model') # renderer parameters parser.add_argument('--focal', type=float, default=1015.) parser.add_argument('--center', type=float, default=112.) parser.add_argument('--camera_d', type=float, default=10.) parser.add_argument('--z_near', type=float, default=5.) parser.add_argument('--z_far', type=float, default=15.) if is_train: # training parameters parser.add_argument('--net_recog', type=str, default='r50', choices=['r18', 'r43', 'r50'], help='face recog network structure') parser.add_argument('--net_recog_path', type=str, default='checkpoints/recog_model/ms1mv3_arcface_r50_fp16/backbone.pth') parser.add_argument('--use_crop_face', type=util.str2bool, nargs='?', const=True, default=False, help='use crop mask for photo loss') parser.add_argument('--use_predef_M', type=util.str2bool, nargs='?', const=True, default=False, help='use predefined M for predicted face') # augmentation parameters parser.add_argument('--shift_pixs', type=float, default=10., help='shift pixels') parser.add_argument('--scale_delta', type=float, default=0.1, help='delta scale factor') parser.add_argument('--rot_angle', type=float, default=10., help='rot angles, degree') # loss weights parser.add_argument('--w_feat', type=float, default=0.2, help='weight for feat loss') parser.add_argument('--w_color', type=float, default=1.92, help='weight for loss loss') parser.add_argument('--w_reg', type=float, default=3.0e-4, help='weight for reg loss') parser.add_argument('--w_id', type=float, default=1.0, help='weight for id_reg loss') parser.add_argument('--w_exp', type=float, default=0.8, help='weight for exp_reg loss') parser.add_argument('--w_tex', type=float, default=1.7e-2, help='weight for tex_reg loss') parser.add_argument('--w_gamma', type=float, default=10.0, help='weight for gamma loss') parser.add_argument('--w_lm', type=float, default=1.6e-3, help='weight for lm loss') parser.add_argument('--w_reflc', type=float, default=5.0, help='weight for reflc loss') opt, _ = parser.parse_known_args() parser.set_defaults( focal=1015., center=112., camera_d=10., use_last_fc=False, z_near=5., z_far=15. ) if is_train: parser.set_defaults( use_crop_face=True, use_predef_M=False ) return parser def __init__(self, opt): """Initialize this model class. Parameters: opt -- training/test options A few things can be done here. - (required) call the initialization function of BaseModel - define loss function, visualization images, model names, and optimizers """ BaseModel.__init__(self, opt) # call the initialization method of BaseModel self.visual_names = ['output_vis'] self.model_names = ['net_recon'] self.parallel_names = self.model_names + ['renderer'] self.facemodel = ParametricFaceModel( bfm_folder=opt.bfm_folder, camera_distance=opt.camera_d, focal=opt.focal, center=opt.center, is_train=self.isTrain, default_name=opt.bfm_model ) fov = 2 * np.arctan(opt.center / opt.focal) * 180 / np.pi self.renderer = MeshRenderer( rasterize_fov=fov, znear=opt.z_near, zfar=opt.z_far, rasterize_size=int(2 * opt.center) ) if self.isTrain: self.loss_names = ['all', 'feat', 'color', 'lm', 'reg', 'gamma', 'reflc'] self.net_recog = networks.define_net_recog( net_recog=opt.net_recog, pretrained_path=opt.net_recog_path ) # loss func name: (compute_%s_loss) % loss_name self.compute_feat_loss = perceptual_loss self.comupte_color_loss = photo_loss self.compute_lm_loss = landmark_loss self.compute_reg_loss = reg_loss
self.compute_reflc_loss = reflectance_loss
6
2023-12-19 11:01:35+00:00
12k
Angryrou/udao
udao/optimization/tests/moo/test_sequential_progressive_frontier.py
[ { "identifier": "set_deterministic_torch", "path": "udao/model/utils/utils.py", "snippet": "def set_deterministic_torch(seed: int = 0) -> None:\n \"\"\"\n Set seeds and configurations to enable deterministic behavior in PyTorch.\n\n Parameters\n ----------\n seed : int\n Random see...
from typing import cast from ....model.utils.utils import set_deterministic_torch from ....utils.interfaces import VarTypes from ...concepts.problem import MOProblem from ...moo.progressive_frontier import SequentialProgressiveFrontier from ...soo.mogd import MOGD from ...utils.moo_utils import Point import numpy as np import pytest import torch as th
10,570
@pytest.fixture def spf(mogd: MOGD) -> SequentialProgressiveFrontier: spf = SequentialProgressiveFrontier( params=SequentialProgressiveFrontier.Params(), solver=mogd, ) return spf class TestProgressiveFrontier: def test__get_corner_points(self, spf: SequentialProgressiveFrontier) -> None: utopia = Point(np.array([1, 0.3])) nadir = Point(np.array([5, 10])) corner_points = spf._get_corner_points(utopia, nadir) # 1-------3# # # # 0-------2# expected_points = [ Point(np.array([1.0, 0.3])), Point(np.array([1.0, 10.0])), Point(np.array([5.0, 0.3])), Point(np.array([5.0, 10.0])), ] assert all(c == e for c, e in zip(corner_points, expected_points)) def test__generate_sub_rectangles_bad( self, spf: SequentialProgressiveFrontier ) -> None: utopia = Point(np.array([1, 0.3])) nadir = Point(np.array([5, 10])) middle = Point((utopia.objs + nadir.objs) / 2) rectangles = spf.generate_sub_rectangles( utopia, nadir, middle, successful=False ) ############ # 0 | 1 # ############ # - | - # ############ assert len(rectangles) == 2 assert rectangles[0].utopia == Point(np.array([1.0, 5.15])) assert rectangles[0].nadir == Point(np.array([3.0, 10])) assert rectangles[1].utopia == Point(np.array([3.0, 5.15])) assert rectangles[1].nadir == Point(np.array([5.0, 10])) def test__generate_sub_rectangles_good( self, spf: SequentialProgressiveFrontier ) -> None: utopia = Point(np.array([1, 0.3])) nadir = Point(np.array([5, 10])) middle = Point((utopia.objs + nadir.objs) / 2) rectangles = spf.generate_sub_rectangles(utopia, nadir, middle) ############ # 1 | _ # ############ # 0 | 2 # ############ assert len(rectangles) == 3 assert rectangles[0].utopia == Point(np.array([1.0, 0.3])) assert rectangles[0].nadir == Point(np.array([3.0, 5.15])) assert rectangles[1].utopia == Point(np.array([1.0, 5.15])) assert rectangles[1].nadir == Point(np.array([3.0, 10.0])) assert rectangles[2].utopia == Point(np.array([3.0, 0.3])) assert rectangles[2].nadir == Point(np.array([5.0, 5.15])) def test_get_utopia_and_nadir(self, spf: SequentialProgressiveFrontier) -> None: points = [ Point(np.array([1, 5]), {"v1": 0.2, "v2": 1}), Point(np.array([3, 10]), {"v1": 0.8, "v2": 6}), Point(np.array([5, 0.3]), {"v1": 0.5, "v2": 3}), ] utopia, nadir = spf.get_utopia_and_nadir(points) np.testing.assert_array_equal(utopia.objs, np.array([1, 0.3])) np.testing.assert_array_equal(nadir.objs, np.array([5, 10])) def test_solve( self, spf: SequentialProgressiveFrontier,
@pytest.fixture def spf(mogd: MOGD) -> SequentialProgressiveFrontier: spf = SequentialProgressiveFrontier( params=SequentialProgressiveFrontier.Params(), solver=mogd, ) return spf class TestProgressiveFrontier: def test__get_corner_points(self, spf: SequentialProgressiveFrontier) -> None: utopia = Point(np.array([1, 0.3])) nadir = Point(np.array([5, 10])) corner_points = spf._get_corner_points(utopia, nadir) # 1-------3# # # # 0-------2# expected_points = [ Point(np.array([1.0, 0.3])), Point(np.array([1.0, 10.0])), Point(np.array([5.0, 0.3])), Point(np.array([5.0, 10.0])), ] assert all(c == e for c, e in zip(corner_points, expected_points)) def test__generate_sub_rectangles_bad( self, spf: SequentialProgressiveFrontier ) -> None: utopia = Point(np.array([1, 0.3])) nadir = Point(np.array([5, 10])) middle = Point((utopia.objs + nadir.objs) / 2) rectangles = spf.generate_sub_rectangles( utopia, nadir, middle, successful=False ) ############ # 0 | 1 # ############ # - | - # ############ assert len(rectangles) == 2 assert rectangles[0].utopia == Point(np.array([1.0, 5.15])) assert rectangles[0].nadir == Point(np.array([3.0, 10])) assert rectangles[1].utopia == Point(np.array([3.0, 5.15])) assert rectangles[1].nadir == Point(np.array([5.0, 10])) def test__generate_sub_rectangles_good( self, spf: SequentialProgressiveFrontier ) -> None: utopia = Point(np.array([1, 0.3])) nadir = Point(np.array([5, 10])) middle = Point((utopia.objs + nadir.objs) / 2) rectangles = spf.generate_sub_rectangles(utopia, nadir, middle) ############ # 1 | _ # ############ # 0 | 2 # ############ assert len(rectangles) == 3 assert rectangles[0].utopia == Point(np.array([1.0, 0.3])) assert rectangles[0].nadir == Point(np.array([3.0, 5.15])) assert rectangles[1].utopia == Point(np.array([1.0, 5.15])) assert rectangles[1].nadir == Point(np.array([3.0, 10.0])) assert rectangles[2].utopia == Point(np.array([3.0, 0.3])) assert rectangles[2].nadir == Point(np.array([5.0, 5.15])) def test_get_utopia_and_nadir(self, spf: SequentialProgressiveFrontier) -> None: points = [ Point(np.array([1, 5]), {"v1": 0.2, "v2": 1}), Point(np.array([3, 10]), {"v1": 0.8, "v2": 6}), Point(np.array([5, 0.3]), {"v1": 0.5, "v2": 3}), ] utopia, nadir = spf.get_utopia_and_nadir(points) np.testing.assert_array_equal(utopia.objs, np.array([1, 0.3])) np.testing.assert_array_equal(nadir.objs, np.array([5, 10])) def test_solve( self, spf: SequentialProgressiveFrontier,
two_obj_problem: MOProblem,
2
2023-12-20 09:10:42+00:00
12k
XLearning-SCU/2023-TPAMI-SMILE
Net.py
[ { "identifier": "get_dist_release", "path": "DistComput.py", "snippet": "def get_dist_release(loader, dist_path):\r\n if not os.path.exists(dist_path):\r\n # loader = test_loader\r\n num_data = [10]\r\n with torch.no_grad():\r\n dist_list = [[] for i in range(len(num_d...
import math import os import time import warnings import numpy as np import torch import torchvision import torch.nn.functional as F import evaluate import faiss import scipy.io as sio from torch import nn from torch.autograd import Variable from DistComput import get_dist_release from _Utils.Calculator import get_nearest_k from _Utils.Logs import update_log from _Utils.Scatter import visualize2 from _Utils.Visualize import visualize, visual_matrix_console, visualize_image, plot_heat_map from _Utils import TimeOperator, DirectoryOperator from DataSetMaster.dataset import get_clusters from classification import svm_classify from evaluate import UMAP, evaluate2 from sklearn import metrics from munkres import Munkres from figures.ScatterMaster import visual_image_scatter
10,783
# class_labels1[is_pair == 0] = class_labels1[is_pair == 0][nearest[:, 0]] elif args.reAlign == 'Copy': if torch.sum(to_realign): h1[to_realign] = h0[to_realign] # class_labels1[is_pair == 0] = class_labels0[is_pair == 0] elif args.reAlign == 'KnnMapMean': if torch.sum(to_realign): targ_v1 = h1[is_pair] nearest = get_nearest_k(h0[to_realign], h0[is_pair], args.reAlignK) h1[to_realign] = torch.cat([torch.mean(targ_v1[ns], dim=0) for ns in nearest]) # class_labels1[is_pair == 0] = ... elif args.reAlign == 'Ignore': pass else: raise NotImplementedError('') if args.Rev: fea0_rec, fea1_rec = self.decode([h1, h0]) else: fea0_rec, fea1_rec = self.decode([h0, h1]) # if len(fea0_rec[0]) == len(fea1_rec[0]): # fea_rec = torch.concat([fea0_rec, fea1_rec]) # fea = torch.concat([fea0, fea1]) # mask_c = torch.concat([mask[:, 0], mask[:, 1]]) # if torch.sum(mask_c == 0): # rnmse_vec[0].extend( # evaluate.get_rnmse(xs_hat=fea_rec[mask_c == 0], xs=fea[mask_c == 0]).cpu().numpy()) # if torch.sum(mask_c == 1): # rnmse_vec[1].extend( # evaluate.get_rnmse(xs_hat=fea_rec[mask_c == 1], xs=fea[mask_c == 1]).cpu().numpy()) # else: # if torch.sum(mask == 0): # n0_v0 = evaluate.get_rnmse( # xs_hat=fea0_rec[mask[:, 0] == 0], xs=fea0[mask[:, 0] == 0]).cpu().numpy() # n0_v1 = evaluate.get_rnmse( # xs_hat=fea1_rec[mask[:, 1] == 0], xs=fea1[mask[:, 1] == 0]).cpu().numpy() # rnmse_vec[0].extend(n0_v0) # rnmse_vec[0].extend(n0_v1) # if torch.sum(mask == 1): # n1_v0 = evaluate.get_rnmse( # xs_hat=fea0_rec[mask[:, 0] == 1], xs=fea0[mask[:, 0] == 1]).cpu().numpy() # n1_v1 = evaluate.get_rnmse( # xs_hat=fea1_rec[mask[:, 1] == 1], xs=fea1[mask[:, 1] == 1]).cpu().numpy() # rnmse_vec[1].extend(n1_v0) # rnmse_vec[1].extend(n1_v1) g = torch.concat((torch.zeros(len(fea0), device=fea0.device, dtype=torch.int), torch.ones(len(fea1), device=fea0.device, dtype=torch.int))) h = torch.cat([h0, h1]).detach().cpu().numpy() feature_vec.extend(h) data_vec.extend(torch.cat([fea0, fea1]).detach().cpu().numpy()) group_vec.extend(g.cpu().numpy()) type_vec.extend(torch.concat((class_labels0, class_labels1)).numpy()) inf_data_t = time.time() feature_vec = np.array(feature_vec) data_vec = np.array(data_vec) feature_vec_cluster = np.array(feature_vec_cluster) is_pair_all = np.array(is_pair_all) feature_vec_classification = np.array(feature_vec_classification) group_vec = np.array(group_vec) group_vec_cluster = np.array(group_vec_cluster) type_vec = np.array(type_vec) type_vec_cluster = np.array(type_vec_cluster) rnmse_vec[0] = np.array(rnmse_vec[0]) rnmse_vec[1] = np.array(rnmse_vec[1]) kmeans_time = TimeOperator.Timer() if args.ShowReconstruct: if args.dataset == 'MNISTUSPS': dims = [np.product(d.data.shape[1:]) for d in test_dataloader.dataset.datasets] data_list = [np.asarray(it.data, dtype=np.float32) for it in test_dataloader.dataset.datasets] Y = test_dataloader.dataset.datasets[0].targets else: dims = [d.shape[1] for d in test_dataloader.dataset.data] data_list = [np.asarray(it, dtype=np.float32) for it in test_dataloader.dataset.data] Y = test_dataloader.dataset.class_labels0 mask = test_dataloader.dataset.mask n_per_cat = 10 rec0, rec1 = self.decode([ torch.from_numpy(feature_vec[group_vec == 0]).cuda(), torch.from_numpy(feature_vec[group_vec == 1]).cuda()]) rec0 = rec0.detach().cpu().numpy() rec1 = rec1.detach().cpu().numpy() show_img = np.asarray([]) inds_map = np.asarray([]) for v in range(2): col = np.asarray([]) inds_map_col = np.asarray([]) for y in range(10): inds = np.arange(len(Y))[ np.logical_and(np.logical_and(mask[:, v] == 1, mask[:, 1 - v] == 0), Y == y) ] np.random.shuffle(inds) assert len(inds) >= n_per_cat inds = inds[:n_per_cat] raw_imgs = data_list[v][inds] missing_imgs = data_list[1 - v][inds] rec_imgs = [rec0, rec1][v][inds] rec_imgs_miss = [rec0, rec1][1 - v][inds] pack = np.asarray( [raw_imgs, rec_imgs, missing_imgs, rec_imgs_miss]).reshape([-1, n_per_cat, 28, 28]) if len(col): col = np.concatenate([col, pack], axis=0) else: col = pack if len(inds_map_col): inds_map_col = np.concatenate([inds_map_col, inds.reshape([1, -1])], axis=0) else: inds_map_col = inds.reshape([1, -1]) if len(show_img): show_img = np.concatenate([show_img, col], axis=1) else: show_img = col if len(inds_map): inds_map = np.concatenate([inds_map, inds_map_col], axis=1) else: inds_map = inds_map_col
def show_distribution_ct(type_vec, group_vec, pred_vec, class_num, group_num): v = np.zeros((class_num, class_num, group_num), dtype=int) for t, c, g in zip(type_vec, pred_vec, group_vec): v[t, c, g] += 1 visual_matrix_console(x=v) def kmeans(feature_vec, class_num): d = feature_vec.shape[1] kmeans = faiss.Clustering(d, class_num) kmeans.verbose = False kmeans.niter = 300 kmeans.nredo = 10 # kmeans.spherical = True # if LimitKmeans: # kmeans.max_points_per_centroid = 1000 # kmeans.min_points_per_centroid = 10 res = faiss.StandardGpuResources() cfg = faiss.GpuIndexFlatConfig() cfg.useFloat16 = True cfg.device = 0 index = faiss.GpuIndexFlatL2(res, d, cfg) # print(feature_vec.shape) kmeans.train(feature_vec, index) centroids = faiss.vector_to_array(kmeans.centroids).reshape(class_num, d) return centroids def show_distribution(cluster_vec, group_vec, class_num, group_num): for it in np.arange(group_num): print('{:4d}, '.format(it), end='') print('') cluster_group = torch.zeros((class_num, group_num), dtype=torch.int) for i, j in zip(cluster_vec, group_vec): cluster_group[i, j] += 1 # cluster_group = cluster_group[torch.argsort(torch.sum(cluster_group, dim=1))] for line in cluster_group: print('{:4d}: '.format(torch.sum(line)), end='') for it in line: print('{:4d}, '.format(it), end='') print('') def save_checkpoint(state, epoch): """ it has been trained for *epoch* epochs """ filename = 'Epoch{:03d}.checkpoint'.format(epoch) checkpoint_dir = os.path.join( os.path.dirname(os.getcwd()), 'Checkpoints', filename ) DirectoryOperator.FoldOperator(directory=checkpoint_dir).make_fold() if os.path.exists(checkpoint_dir): warnings.warn('Checkpoint exist and been replaced.({})'.format(checkpoint_dir)) print('Save check point into {}'.format(checkpoint_dir)) torch.save(state, checkpoint_dir) def get_ffn(dims, last_layers=None, with_bn=False, drop_out=0): layers = [] for ind in range(len(dims) - 1): in_dim = dims[ind] out_dim = dims[ind + 1] layers.append(nn.Linear(in_dim, out_dim)) if with_bn: layers.append(nn.BatchNorm1d(out_dim)) layers.append(nn.ReLU()) if drop_out: layers.append(nn.Dropout(drop_out)) if last_layers is not None: layers.extend(last_layers) return nn.Sequential(*layers) def get_cov(dims, strides, last_layers=None, with_bn=False, drop_out=0): layers = [] for ind in range(len(dims) - 1): in_dim = dims[ind] out_dim = dims[ind + 1] stride = strides[ind] # layers.append(nn.Linear(in_dim, out_dim)) if stride >= 0: layers.append(nn.Conv2d(in_dim, out_dim, kernel_size=3, stride=stride, padding=1)) else: layers.append(nn.ConvTranspose2d( in_dim, out_dim, kernel_size=3, stride=-stride, padding=1, output_padding=0 if stride == -1 else 1)) if with_bn: # layers.append(nn.BatchNorm1d(out_dim)) layers.append(nn.BatchNorm2d(out_dim)) layers.append(nn.ReLU()) if drop_out: layers.append(nn.Dropout(drop_out)) if last_layers is not None: layers.extend(last_layers) return nn.Sequential(*layers) class Net(nn.Module): def __init__(self, args, in_dims, class_num, group_num): super(Net, self).__init__() self.encoder_adaption = nn.ModuleList([ get_ffn([in_dims[i], 1024], with_bn=args.BatchNormType[0] == '1', drop_out=args.Dropout) for i in range(group_num if args.GroupWiseLayer[0] == '1' else 1)]) self.encoder = nn.ModuleList([ get_ffn([1024, 1024, 512], with_bn=args.BatchNormType[1] == '1', drop_out=args.Dropout) for _ in range(group_num if args.GroupWiseLayer[1] == '1' else 1)]) if args.representation_dim == 0: args.representation_dim = class_num self.class_num = class_num self.group_num = group_num self.pred_cac = None self.pred_center_cac = None if args.ElActivationType == 'None': el_activation_ = [] elif args.ElActivationType == 'Normalize': el_activation_ = [] elif args.ElActivationType == 'BnNormalize': el_activation_ = [nn.BatchNorm1d(args.representation_dim)] elif args.ElActivationType == 'BnReNormalize': el_activation_ = [nn.BatchNorm1d(args.representation_dim), nn.ReLU()] elif args.ElActivationType == 'BnRe': el_activation_ = [nn.BatchNorm1d(args.representation_dim), nn.ReLU()] else: raise NotImplementedError('') self.el_activation_ = el_activation_ self.encoder_linear = nn.ModuleList([ get_ffn([512, 256], with_bn=args.BatchNormType[2] == '1', drop_out=args.Dropout, last_layers=[nn.Linear(256, args.representation_dim)] + self.el_activation_) for _ in range(group_num if args.GroupWiseLayer[2] == '1' else 1)]) dec_in = args.representation_dim if args.McDecoder: dec_in *= group_num self.dec_in = dec_in self.decoder_linear = nn.ModuleList([ get_ffn([self.dec_in, 256, 512], with_bn=args.BatchNormType[3] == '1', drop_out=args.Dropout) for _ in range(group_num if args.GroupWiseLayer[3] == '1' else 1)]) if args.ActivationType == 'None': final_activation_ = [] elif args.ActivationType == 'Sigmoid': final_activation_ = [nn.Sigmoid()] elif args.ActivationType == 'Tanh': final_activation_ = [nn.Tanh()] else: raise NotImplementedError('') self.final_activation_ = final_activation_ self.decoder = nn.ModuleList([ get_ffn([512, 1024, 1024], with_bn=args.BatchNormType[4] == '1', drop_out=args.Dropout) for _ in range(group_num if args.GroupWiseLayer[4] == '1' else 1)]) self.decoder_adaption = nn.ModuleList([ get_ffn([], last_layers=[nn.Linear(1024, in_dims[i])] + self.final_activation_) for i in range(group_num if args.GroupWiseLayer[5] == '1' else 1)]) self.args = args self.in_dims = in_dims # def update_cluster_center(self, center): # self.cluster_centers = F.normalize(torch.from_numpy(center), dim=1).cuda() def forward(self, x, **kwargs): return self.decode(self.encode([x])) def encode(self, xs: list): hs = [] for g, x in enumerate(xs): if self.args.noise_type == 'None': pass elif self.args.noise_type == 'Drop': x = x * (Variable(x.data.new(x.size()).normal_(0, 0.1)) < self.args.noise_weight).type_as(x) elif self.args.noise_type == 'Add': x = x + Variable(x.data.new(x.size()).normal_(0, self.args.noise_weight)).type_as(x) else: raise NotImplementedError('') if len(x) != 0: if len(x) == 1: x = torch.concat([x, x]) # print(x.shape) # x = x.view((len(x), -1)) # print(x.shape) x = self.encoder_adaption[g if self.args.GroupWiseLayer[0] == '1' else 0](x) x = self.encoder[g if self.args.GroupWiseLayer[1] == '1' else 0](x) x = self.encoder_linear[g if self.args.GroupWiseLayer[2] == '1' else 0](x) if len(x) == 1: x = x[[0]] if self.args.ElActivationType in ['Normalize', 'BnNormalize', 'BnReNormalize']: x = F.normalize(x, dim=1) else: x = torch.zeros([0, self.args.representation_dim], device=torch.device('cuda:0')) hs.append(x) return hs def soft_ass(self, h, centroids): if self.args.ElActivationType in ['Normalize', 'BnNormalize', 'BnReNormalize']: return h @ centroids.T else: dst = torch.cdist(h, centroids) # return (torch.mean(dst) - dst) / (torch.amax(dst) - torch.amin(dst)) * 2 return -dst / 2 # def encode_class(self, hs): # cs = [] # for h in hs: # c = h @ self.cluster_centers.T # cs.append(c) # return cs def decode(self, hs): xs = [] for g, h in enumerate(hs): if self.args.McDecoder: h = torch.cat(hs, dim=1) if len(h) != 0: if len(h) == 1: h = torch.concat([h, h]) h = self.decoder_linear[g if self.args.GroupWiseLayer[3] == '1' else 0](h) h = self.decoder[g if self.args.GroupWiseLayer[4] == '1' else 0](h) h = self.decoder_adaption[g if self.args.GroupWiseLayer[5] == '1' else 0](h) if len(h) == 1: h = h[[0]] else: h = torch.zeros([0, self.in_dims[g]], device=torch.device('cuda:0')) xs.append(h) return xs def run(self, epochs, train_dataloader, test_dataloader, args): # if args.loss_self_cons: # clusters = get_clusters(args=args) optimizer_g = torch.optim.Adam( self.parameters(), lr=args.LearnRate, betas=(args.betas_a, args.betas_v), weight_decay=args.WeightDecay ) mse_loss = nn.MSELoss().cuda() timer_all = TimeOperator.Timer() timer_train = TimeOperator.Timer() timer_save = TimeOperator.Timer() ce_loss = nn.CrossEntropyLoss().cuda() type_detail_shown = False start_epoch = 0 if args.resume: if os.path.isfile(args.resume): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) # if args.gpu is None: # checkpoint = torch.load(args.resume) # else: # # Map model to be loaded to specified single gpu. # loc = 'cuda:{}'.format(args.gpu) # checkpoint = torch.load(args.resume, map_location=loc) start_epoch = checkpoint['epoch'] self.load_state_dict(checkpoint['state_dict']) optimizer_g.load_state_dict(checkpoint['optimizer']['optimizer_g']) # self.__dict__ = checkpoint['self_dic'] print("=> loaded checkpoint '{}' (epoch {})" .format(args.resume, checkpoint['epoch'])) # self.args = args # warnings.warn('This is not equal to start from the beginning due to different rands states.') # else: raise NotImplementedError("=> no checkpoint found at '{}'".format(args.resume)) if args.CodeTest: args.train_epoch = start_epoch + 1 epochs = start_epoch + 1 best_acc = 0 for epoch in range(start_epoch, epochs): if (epoch + 1) <= args.LearnRateWarm: lr = args.LearnRate * (epoch + 1) / args.LearnRateWarm else: if args.LearnRateDecayType == 'None': lr = args.LearnRate elif args.LearnRateDecayType == 'Exp': lr = args.LearnRate * ((1 + 10 * (epoch + 1 - args.LearnRateWarm) / ( args.train_epoch - args.LearnRateWarm)) ** -0.75) elif args.LearnRateDecayType == 'Cosine': lr = args.LearnRate * 0.5 * (1. + math.cos( math.pi * (epoch + 1 - args.LearnRateWarm) / (args.train_epoch - args.LearnRateWarm))) else: raise NotImplementedError('args.LearnRateDecayType') if lr != args.LearnRate: def adjust_learning_rate(optimizer): print('adjust_learning_rate: {}'.format(lr)) for param_group in optimizer.param_groups: param_group['lr'] = lr adjust_learning_rate(optimizer_g) timer_all_time = time.time() # inf_t = time.time() # print('start epoch {}'.format(epoch)) self.eval() feature_vec, type_vec, group_vec = [], [], [] feature_vec_cluster = [] group_vec_cluster = [] feature_vec_classification = [] type_vec_cluster = [] data_vec = [] is_pair_all = [] timer_infer_data = TimeOperator.Timer() rnmse_vec = [[], []] # mask = 0 1 with torch.no_grad(): inf_data_t = time.time() for (fea0, fea1, class_labels0, class_labels1, mask, is_pair, index) in test_dataloader: timer_infer_data.update(time.time() - inf_data_t) # timer_infer_data.show(prefix='InferDataTime', total_count=len(test_dataloader), # print_end_time=False) fea0 = fea0.cuda() fea1 = fea1.cuda() if args.Rev: h1, h0 = self.encode([fea0, fea1]) if args.SingleView != -1: for v in range(len(mask[0])): if v != 1 - args.SingleView: mask[:, v] = 0 else: h0, h1 = self.encode([fea0, fea1]) if args.SingleView != -1: for v in range(len(mask[0])): if v != args.SingleView: mask[:, v] = 0 cluster_h0 = h0[mask[:, 0] == 1] cluster_h1 = h1[mask[:, 1] == 1] # if args.SingleView != -1: # mask[:, args.SingleView] = 0 # # if args.SingleView == 0: # # cluster_h1 = cluster_h1[[]] # # class_labels1 = class_labels1[[]] # # elif args.SingleView == 1: # # class_labels0 = class_labels0[[]] # # cluster_h0 = cluster_h0[[]] # # else: # # raise NotImplementedError('') is_pair_all.extend(is_pair) feature_vec_cluster.extend(torch.cat([cluster_h0, cluster_h1]).detach().cpu().numpy()) group_vec_cluster.extend(torch.concat((torch.zeros(len(cluster_h0), dtype=torch.int), torch.ones(len(cluster_h1), dtype=torch.int))).numpy()) type_vec_cluster.extend(torch.concat((class_labels0[mask[:, 0] == 1], class_labels1[mask[:, 1] == 1])).numpy()) feature_vec_classification.extend(torch.cat([h0, h1]).detach().cpu().numpy()) if (epoch + 1) == epochs or (epoch + 1) % args.VisualFreq == 0: if torch.sum(torch.logical_not(torch.logical_or(mask[:, 1], mask[:, 0]))): raise NotImplementedError('存在一个pair两个模态都缺失') if args.reFill == 'Copy': if torch.sum(mask[:, 0] == 0): h0[mask[:, 0] == 0] = h1[mask[:, 0] == 0] if torch.sum(mask[:, 1] == 0): h1[mask[:, 1] == 0] = h0[mask[:, 1] == 0] elif args.reFill == 'Center': # raise NotImplementedError('') if self.pred_center_cac is None: pass warnings.warn('self.pred_center_cac == None') else: centors = torch.zeros((len(mask), 2, len(self.pred_center_cac[0]))).cuda() centors[mask[:, 0] == 1, 0] = self.pred_center_cac[ self.pred_cac[:torch.sum(mask[:, 0] == 1)]] centors[mask[:, 1] == 1, 1] = self.pred_center_cac[ self.pred_cac[torch.sum(mask[:, 0] == 1):]] if torch.sum(mask[:, 0] == 0): h0[mask[:, 0] == 0] = centors[mask[:, 0] == 0, 1] if torch.sum(mask[:, 1] == 0): h1[mask[:, 1] == 0] = centors[mask[:, 1] == 0, 0] elif args.reFill == 'KnnMapMean': if torch.sum(mask[:, 0] == 0): nearest = get_nearest_k(h1[mask[:, 0] == 0], h1[is_pair], args.reAlignK) h0p = h0[is_pair] h1[mask[:, 0] == 0] = torch.cat([torch.mean(h0p[ns], dim=0) for ns in nearest]) if torch.sum(mask[:, 1] == 0): nearest = get_nearest_k(h0[mask[:, 1] == 0], h0[is_pair], args.reAlignK) h1p = h1[is_pair] h1[mask[:, 1] == 0] = torch.cat([torch.mean(h1p[ns], dim=0) for ns in nearest]) # raise NotImplementedError('') elif args.reFill == 'KnnMean': # 关联对齐, xi1 不变, xi2替换成离xi1最近的k个view2的点的mean if torch.sum(mask[:, 1] == 0): hs0 = h0[mask[:, 1] == 0] he1 = h1[mask[:, 1] == 1] nearest = get_nearest_k(hs0, he1, args.reAlignK) # nearest = torch.argsort(torch.cdist(hs0.cpu(), he1.cpu()), dim=1)[:, :args.reAlignK] h1[mask[:, 1] == 0] = torch.cat([torch.mean(he1[ns], dim=0) for ns in nearest]) # class_labels1[mask[:, 1] == 0] = class_labels1[mask[:, 1] == 1][nearest[:, 0]] if torch.sum(mask[:, 0] == 0): hs1 = h1[mask[:, 0] == 0] he0 = h0[mask[:, 0] == 1] nearest = get_nearest_k(hs1, he0, args.reAlignK) # nearest = torch.argsort(torch.cdist(hs1.cpu(), he0.cpu()), dim=1)[:, :args.reAlignK] h0[mask[:, 0] == 0] = torch.cat([torch.mean(he0[ns], dim=0) for ns in nearest]) # class_labels0[mask[:, 0] == 0] = class_labels0[mask[:, 0] == 1][nearest[:, 0]] ############################################################### # 缺失补全, xi2 = mean(离xi1最近的k个view2的点) # fill_num = k # C = euclidean_dist(h0, h1) # row_idx = C.argsort() # col_idx = (C.t()).argsort() # # Mij denotes the flag of i-th sample in view 0 and j-th sample in view 1 # M = torch.logical_and((mask[:, 0].repeat(test_num, 1)).t(), mask[:, 1].repeat(test_num, 1)) # for i in range(test_num): # idx0 = col_idx[i, :][ # M[col_idx[i, :], i]] # idx for view 0 to sort and find the non-missing neighbors # idx1 = row_idx[i, :][ # M[i, row_idx[i, :]]] # idx for view 1 to sort and find the non-missing neighbors # if len(idx1) != 0 and len(idx0) == 0: # i-th sample in view 1 is missing # avg_fill = h1[idx1[0:fill_num], :].sum(dim=0) / fill_num # cnt += (class_labels1[idx1[0:fill_num]] == class_labels1[i]).sum() # missing_cnt += 1 # recover_out0[i, :] = h0[i, :] # recover_out1[i, :] = avg_fill # missing # elif len(idx0) != 0 and len(idx1) == 0: # avg_fill = h0[idx0[0:fill_num], :].sum(dim=0) / fill_num # cnt += (class_labels0[idx0[0:fill_num]] == class_labels0[i]).sum() # missing_cnt += 1 # recover_out0[i, :] = avg_fill # missing # recover_out1[i, :] = h1[i, :] # elif len(idx0) != 0 and len(idx1) != 0: # recover_out0[i, :] = h0[i, :] # recover_out1[i, :] = h1[i, :] # else: # raise Exception('error') # if setting == 1: # align_out0.extend((recover_out0.cpu()).numpy()) # align_out1.extend((recover_out1.cpu()).numpy()) # continue # else: raise NotImplementedError('') to_realign = torch.logical_and(is_pair == 0, torch.logical_and(mask[:, 1], mask[:, 0])) if args.reAlign == 'KnnMean': # 关联对齐, xi1 不变, xi2替换成离xi1最近的k个view2的点的mean if torch.sum(to_realign): ha1 = h1[to_realign] nearest = get_nearest_k(h0[to_realign], ha1, args.reAlignK) # dist = torch.cdist(h0[to_realign].cpu(), ha1.cpu()) # nearest = torch.argsort(dist, dim=1)[:, :args.reAlignK] h1[to_realign] = torch.cat([torch.mean(ha1[ns], dim=0) for ns in nearest]) # class_labels1[is_pair == 0] = class_labels1[is_pair == 0][nearest[:, 0]] elif args.reAlign == 'Copy': if torch.sum(to_realign): h1[to_realign] = h0[to_realign] # class_labels1[is_pair == 0] = class_labels0[is_pair == 0] elif args.reAlign == 'KnnMapMean': if torch.sum(to_realign): targ_v1 = h1[is_pair] nearest = get_nearest_k(h0[to_realign], h0[is_pair], args.reAlignK) h1[to_realign] = torch.cat([torch.mean(targ_v1[ns], dim=0) for ns in nearest]) # class_labels1[is_pair == 0] = ... elif args.reAlign == 'Ignore': pass else: raise NotImplementedError('') if args.Rev: fea0_rec, fea1_rec = self.decode([h1, h0]) else: fea0_rec, fea1_rec = self.decode([h0, h1]) # if len(fea0_rec[0]) == len(fea1_rec[0]): # fea_rec = torch.concat([fea0_rec, fea1_rec]) # fea = torch.concat([fea0, fea1]) # mask_c = torch.concat([mask[:, 0], mask[:, 1]]) # if torch.sum(mask_c == 0): # rnmse_vec[0].extend( # evaluate.get_rnmse(xs_hat=fea_rec[mask_c == 0], xs=fea[mask_c == 0]).cpu().numpy()) # if torch.sum(mask_c == 1): # rnmse_vec[1].extend( # evaluate.get_rnmse(xs_hat=fea_rec[mask_c == 1], xs=fea[mask_c == 1]).cpu().numpy()) # else: # if torch.sum(mask == 0): # n0_v0 = evaluate.get_rnmse( # xs_hat=fea0_rec[mask[:, 0] == 0], xs=fea0[mask[:, 0] == 0]).cpu().numpy() # n0_v1 = evaluate.get_rnmse( # xs_hat=fea1_rec[mask[:, 1] == 0], xs=fea1[mask[:, 1] == 0]).cpu().numpy() # rnmse_vec[0].extend(n0_v0) # rnmse_vec[0].extend(n0_v1) # if torch.sum(mask == 1): # n1_v0 = evaluate.get_rnmse( # xs_hat=fea0_rec[mask[:, 0] == 1], xs=fea0[mask[:, 0] == 1]).cpu().numpy() # n1_v1 = evaluate.get_rnmse( # xs_hat=fea1_rec[mask[:, 1] == 1], xs=fea1[mask[:, 1] == 1]).cpu().numpy() # rnmse_vec[1].extend(n1_v0) # rnmse_vec[1].extend(n1_v1) g = torch.concat((torch.zeros(len(fea0), device=fea0.device, dtype=torch.int), torch.ones(len(fea1), device=fea0.device, dtype=torch.int))) h = torch.cat([h0, h1]).detach().cpu().numpy() feature_vec.extend(h) data_vec.extend(torch.cat([fea0, fea1]).detach().cpu().numpy()) group_vec.extend(g.cpu().numpy()) type_vec.extend(torch.concat((class_labels0, class_labels1)).numpy()) inf_data_t = time.time() feature_vec = np.array(feature_vec) data_vec = np.array(data_vec) feature_vec_cluster = np.array(feature_vec_cluster) is_pair_all = np.array(is_pair_all) feature_vec_classification = np.array(feature_vec_classification) group_vec = np.array(group_vec) group_vec_cluster = np.array(group_vec_cluster) type_vec = np.array(type_vec) type_vec_cluster = np.array(type_vec_cluster) rnmse_vec[0] = np.array(rnmse_vec[0]) rnmse_vec[1] = np.array(rnmse_vec[1]) kmeans_time = TimeOperator.Timer() if args.ShowReconstruct: if args.dataset == 'MNISTUSPS': dims = [np.product(d.data.shape[1:]) for d in test_dataloader.dataset.datasets] data_list = [np.asarray(it.data, dtype=np.float32) for it in test_dataloader.dataset.datasets] Y = test_dataloader.dataset.datasets[0].targets else: dims = [d.shape[1] for d in test_dataloader.dataset.data] data_list = [np.asarray(it, dtype=np.float32) for it in test_dataloader.dataset.data] Y = test_dataloader.dataset.class_labels0 mask = test_dataloader.dataset.mask n_per_cat = 10 rec0, rec1 = self.decode([ torch.from_numpy(feature_vec[group_vec == 0]).cuda(), torch.from_numpy(feature_vec[group_vec == 1]).cuda()]) rec0 = rec0.detach().cpu().numpy() rec1 = rec1.detach().cpu().numpy() show_img = np.asarray([]) inds_map = np.asarray([]) for v in range(2): col = np.asarray([]) inds_map_col = np.asarray([]) for y in range(10): inds = np.arange(len(Y))[ np.logical_and(np.logical_and(mask[:, v] == 1, mask[:, 1 - v] == 0), Y == y) ] np.random.shuffle(inds) assert len(inds) >= n_per_cat inds = inds[:n_per_cat] raw_imgs = data_list[v][inds] missing_imgs = data_list[1 - v][inds] rec_imgs = [rec0, rec1][v][inds] rec_imgs_miss = [rec0, rec1][1 - v][inds] pack = np.asarray( [raw_imgs, rec_imgs, missing_imgs, rec_imgs_miss]).reshape([-1, n_per_cat, 28, 28]) if len(col): col = np.concatenate([col, pack], axis=0) else: col = pack if len(inds_map_col): inds_map_col = np.concatenate([inds_map_col, inds.reshape([1, -1])], axis=0) else: inds_map_col = inds.reshape([1, -1]) if len(show_img): show_img = np.concatenate([show_img, col], axis=1) else: show_img = col if len(inds_map): inds_map = np.concatenate([inds_map, inds_map_col], axis=1) else: inds_map = inds_map_col
plot_heat_map(inds_map, show=True, fig_path='/xlearning/pengxin/Temp/MissingRecIM.svg')
7
2023-12-21 08:50:36+00:00
12k
botcs/wolfson-scheduler
tests/test_solver.py
[ { "identifier": "unravel_indices", "path": "solver.py", "snippet": "def unravel_indices(indices, shape):\n coord = []\n\n for dim in reversed(shape):\n coord.append(indices % dim)\n indices = indices // dim\n\n coord = torch.stack(coord[::-1], dim=-1)\n\n return coord" }, {...
import torch import unittest import math from unittest.mock import patch from solver import ( unravel_indices, generalized_outer_addition, compute_variances, get_max_numel, check_matrix_fit_and_num_chunks, convert_property_to_categorical, extract_best_assignment, get_no_overlap_inds, generate_binary_matrices, eliminate_invalid_boats, generate_valid_assignments, evaluate_skill_variance, evaluate_num_preferred_outings, evaluate_assignments_per_week, permute_top_assignments, )
9,482
A = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1 ,0], [0, 0, 0, 1]]) B = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1 ,0], [0, 0, 0, 1]]) C = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1 ,0], [0, 0, 0, 1]]) num_max_combinations = 2 result = generate_valid_assignments([A, B, C], num_max_combinations) self.assertLessEqual(len(result), num_max_combinations) def test_consistent_number_of_rowers(self): matrix1 = torch.tensor([[1, 0, 0], [0, 1, 0]]) matrix2 = torch.tensor([[1, 0], [0, 1]]) with self.assertRaises(AssertionError): generate_valid_assignments([matrix1, matrix2]) class TestEvaluateSkillVariance(unittest.TestCase): def test_predefined_skills_and_assignments(self): assignments = torch.tensor([[[1, 0, 1], [0, 1, 1]]]) # 1 outing, 2 combinations, 3 rowers skills = torch.tensor([3, 5, 7]) # Skill levels variance_1 = torch.var(torch.tensor([3., 7])) variance_2 = torch.var(torch.tensor([5., 7])) expected_result = torch.tensor([variance_1, variance_2], dtype=torch.float16) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) self.assertTrue(torch.equal(result, expected_result)) def test_multiple_boats(self): assignments = torch.tensor([[[1, 2, 1, 2], [2, 1, 1, 2], [1, 1, 2, 2]]]) # 1 outing, 3 combinations, 3 rowers skills = torch.tensor([3, 5, 7, 9]) # Skill levels variance_37 = torch.var(torch.tensor([3., 7])) variance_59 = torch.var(torch.tensor([5., 9])) variance_39 = torch.var(torch.tensor([3., 9])) variance_57 = torch.var(torch.tensor([5., 7])) variance_35 = torch.var(torch.tensor([3., 5])) variance_79 = torch.var(torch.tensor([7., 9])) expected_result = torch.tensor([ variance_37 + variance_59, variance_39 + variance_57, variance_35 + variance_79 ], dtype=torch.float16) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) self.assertIsInstance(result, torch.Tensor) self.assertTrue(torch.equal(result, expected_result)) def test_multiple_outings(self): assignments = torch.tensor([ [[1, 0, 1], [0, 1, 1]], # Outing 1 [[1, 0, 1], [0, 1, 1]] # Outing 2 ]) skills = torch.tensor([3, 5, 7]) variance_1 = torch.var(torch.tensor([3., 7])) variance_2 = torch.var(torch.tensor([5., 7])) expected_result = torch.tensor([ [2*variance_1, variance_2+variance_1], [variance_1+variance_2, 2*variance_2] ], dtype=torch.float16) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) self.assertTrue(torch.equal(result, expected_result)) def test_edge_case_no_rowers_assigned(self): assignments = torch.tensor([[[0, 0, 0], [0, 0, 0]]]) # No rowers assigned skills = torch.tensor([3, 5, 7]) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) # Expect zero variance as no rowers are assigned self.assertTrue(torch.all(result == 0)) def test_edge_case_same_skill_level(self): assignments = torch.tensor([[[1, 0, 1], [0, 1, 1]]]) skills = torch.tensor([5, 5, 5]) # All rowers have the same skill level result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) # Expect zero variance as all rowers have the same skill level self.assertTrue(torch.all(result == 0)) class TestEvaluateNumPreferredOutings(unittest.TestCase): def test_predefined_assignments_and_preferences(self): assignments = torch.tensor([ [[1,0,0], [0,1,0], [0,0,1]], # Outing 1 [[1,0,0], [0,1,0], [0,0,1]], # Outing 2 ]) preferred_outings = torch.tensor([0, 1, 2]) expected_result = torch.tensor([ [2, 1, 1], [1, 1, 0], [1, 0, 0] ]) result = evaluate_num_preferred_outings(assignments, preferred_outings) self.assertTrue(torch.equal(result, expected_result)) class TestPermuteTopAssignments(unittest.TestCase): def test_permute_top_assignments(self): # Small, handcrafted example assignments_per_week = torch.tensor([ [[1, 0, 0], [0, 1, 0]], # Outing 1 [[0, 1, 1], [1, 0, 1]] # Outing 2 ]) total_score = torch.tensor([ [0, 1], [3, 2] ]) # this means that the best assignment has the # index of [1, 0] in the score tensor # that translates to the assignment of # outing 1 is [0, 1, 0] (the 1st combination of the 1st outing) # outing 2 is [0, 1, 1] (the 0th combination of the 2nd outing) # The valid replacements are used for the permutation # to generate alternatives to a single outing at a time valid_assignments = [ torch.tensor([[2, 0, 0], [0, 2, 0], [0, 0, 2]]), torch.tensor([[0, 2, 2], [2, 0, 2], [2, 2, 0]]) ] # Although the algorithm would never generate these assignments # because if there are two boats available they would need to be used # so this scenario is just for illustrative purposes. num_permutations = 3
class TestUnravelIndices(unittest.TestCase): def test_simple_case(self): indices = torch.tensor([0, 1, 2, 3, 4, 5]) shape = (2, 3) expected_result = torch.tensor([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]) result = unravel_indices(indices, shape) self.assertTrue(torch.equal(result, expected_result)) def test_single_dimension(self): indices = torch.tensor([0, 1, 2, 3]) shape = (4,) expected_result = torch.tensor([[0], [1], [2], [3]]) result = unravel_indices(indices, shape) self.assertTrue(torch.equal(result, expected_result)) def test_multi_dimension(self): indices = torch.tensor([0, 1, 5, 11]) shape = (2, 3, 2) expected_result = torch.tensor([[0, 0, 0], [0, 0, 1], [0, 2, 1], [1, 2, 1]]) result = unravel_indices(indices, shape) self.assertTrue(torch.equal(result, expected_result)) def test_edge_cases(self): indices = torch.tensor([0]) shape = (1, 1, 1) expected_result = torch.tensor([[0, 0, 0]]) result = unravel_indices(indices, shape) self.assertTrue(torch.equal(result, expected_result)) def test_output_type_and_shape(self): indices = torch.tensor([3, 7]) shape = (2, 4) result = unravel_indices(indices, shape) self.assertIsInstance(result, torch.Tensor) self.assertEqual(result.shape, (2, 2)) class TestGeneralizedOuterAddition(unittest.TestCase): def test_correct_calculation(self): vectors = [torch.tensor([1, 2]), torch.tensor([3, 4])] expected_result = torch.tensor([[4, 5], [5, 6]]) result = generalized_outer_addition(vectors) self.assertTrue(torch.equal(result, expected_result)) def test_different_vector_sizes(self): vectors = [torch.tensor([1, 2]), torch.tensor([3, 4, 5])] expected_result = torch.tensor([[4, 5, 6], [5, 6, 7]]) result = generalized_outer_addition(vectors) self.assertTrue(torch.equal(result, expected_result)) def test_with_output_tensor(self): vectors = [torch.tensor([1, 2]), torch.tensor([3, 4])] output = torch.empty((2, 2)) expected_result = torch.tensor([[4, 5], [5, 6]]) result = generalized_outer_addition(vectors, output) self.assertTrue(torch.equal(result, expected_result)) def test_error_with_incorrect_output_shape(self): vectors = [torch.tensor([1, 2]), torch.tensor([3, 4])] output = torch.empty((3, 3)) with self.assertRaises(AssertionError): generalized_outer_addition(vectors, output) def test_type_and_device_consistency(self): vectors = [torch.tensor([1., 2.], device="cuda"), torch.tensor([3., 4.], device="cuda")] result = generalized_outer_addition(vectors) self.assertTrue(result.dtype == torch.float32) self.assertTrue(result.device.type == "cuda") class TestComputeVariances(unittest.TestCase): def test_variances(self): # Create sample data torch.manual_seed(0) # For reproducibility X = torch.rand(3, 7) Y = torch.rand(4, 5) # Expected variances computed by manual concatenation expected_variances = torch.zeros((X.size(0), Y.size(0))) for i in range(X.size(0)): for j in range(Y.size(0)): concatenated = torch.cat((X[i], Y[j])) expected_variances[i, j] = torch.var(concatenated, unbiased=False) # Variances computed by the function actual_variances = compute_variances(X, Y) # Assert equality (within a tolerance to account for floating-point errors) self.assertTrue(torch.allclose(expected_variances, actual_variances, atol=1e-6)) class TestGetMaxNumel(unittest.TestCase): @patch('solver.get_free_memory') def test_with_different_dtypes(self, mock_get_free_memory): mock_get_free_memory.return_value = 1024 # Mock 1024 bytes of free memory dtypes = [torch.float32, torch.int32, torch.float64] for dtype in dtypes: element_size = torch.tensor([], dtype=dtype).element_size() expected_result = 1024 // element_size result = get_max_numel(dtype) self.assertEqual(result, expected_result) @patch('solver.get_free_memory') def test_without_specified_memory_capacity(self, mock_get_free_memory): mock_get_free_memory.return_value = 2048 # Mock 2048 bytes of free memory dtype = torch.float32 element_size = torch.tensor([], dtype=dtype).element_size() expected_result = 2048 // element_size result = get_max_numel(dtype) self.assertEqual(result, expected_result) def test_with_specified_memory_capacity(self): dtype = torch.float32 memory_capacity = 4096 # Specify 4096 bytes of memory element_size = torch.tensor([], dtype=dtype).element_size() expected_result = 4096 // element_size result = get_max_numel(dtype, memory_capacity) self.assertEqual(result, expected_result) class TestCheckMatrixFitAndNumChunks(unittest.TestCase): def test_tensor_fits_memory(self): dimensions = (10, 10, 10) dtype = torch.float32 memory_capacity = 40000 # Set a capacity that's more than enough self.assertEqual(check_matrix_fit_and_num_chunks(dimensions, dtype, memory_capacity), 1) def test_tensor_exceeds_memory(self): dimensions = (100, 100, 100) dtype = torch.float32 memory_capacity = 1000 # Set a capacity that's too small self.assertRaises(ValueError, check_matrix_fit_and_num_chunks, dimensions, dtype, memory_capacity) def test_different_data_types(self): dimensions = (100, 100) memory_capacity = 100000 for dtype in [torch.float32, torch.int32, torch.float64]: self.assertIsInstance(check_matrix_fit_and_num_chunks(dimensions, dtype, memory_capacity), int) def test_various_dimensions(self): dtype = torch.float32 memory_capacity = 10000 test_dimensions = [ (100, 20, 5), (50, 40, 30), (200, 10, 10) ] for dimensions in test_dimensions: self.assertIsInstance(check_matrix_fit_and_num_chunks(dimensions, dtype, memory_capacity), int) def test_without_specified_memory_capacity(self): dimensions = (10, 10, 10) dtype = torch.float32 self.assertIsInstance(check_matrix_fit_and_num_chunks(dimensions, dtype), int) class TestConvertPropertyToCategorical(unittest.TestCase): def test_correct_conversion(self): property_list = ["red", "blue", "red"] expected_result = torch.tensor([1, 0, 1]) result = convert_property_to_categorical(property_list) self.assertTrue(torch.equal(result, expected_result)) def test_empty_input(self): property_list = [] expected_result = torch.tensor([]) result = convert_property_to_categorical(property_list) self.assertTrue(torch.equal(result, expected_result)) def test_mixed_values(self): property_list = ["apple", "banana", "apple", "cherry"] expected_result = torch.tensor([0, 1, 0, 2]) result = convert_property_to_categorical(property_list) self.assertTrue(torch.equal(result, expected_result)) def test_consistency_in_indexing(self): property_list = ["dog", "cat", "bird", "cat"] expected_result = torch.tensor([2, 1, 0, 1]) result = convert_property_to_categorical(property_list) self.assertTrue(torch.equal(result, expected_result)) def test_output_type_and_shape(self): property_list = ["one", "two", "three"] result = convert_property_to_categorical(property_list) self.assertIsInstance(result, torch.Tensor) self.assertEqual(result.dtype, torch.int64) self.assertEqual(result.shape, (3,)) class TestExtractBestAssignment(unittest.TestCase): def test_valid_inputs(self): # Mock data assignments_per_week = torch.randint(0, 2, (3, 4, 5), dtype=torch.uint8) total_score = torch.rand(4, 4, 4) # Mock score tensor for 3 outings # Expected output shape expected_shape = (3, 1, 5) result = extract_best_assignment(assignments_per_week, total_score) self.assertEqual(result.shape, expected_shape) def test_edge_case_single_outing(self): assignments_per_week = torch.randint(0, 2, (1, 4, 5), dtype=torch.uint8) total_score = torch.rand(4,) expected_shape = (1, 1, 5) result = extract_best_assignment(assignments_per_week, total_score) self.assertEqual(result.shape, expected_shape) def test_output_type(self): assignments_per_week = torch.randint(0, 2, (3, 4, 5), dtype=torch.uint8) total_score = torch.rand(4, 4, 4) result = extract_best_assignment(assignments_per_week, total_score) self.assertIsInstance(result, torch.Tensor) self.assertTrue(result.dtype, torch.uint8) def test_correctness_of_assignment_extraction(self): # Mock data for 3 outings with 4 combinations each assignments_per_week = torch.tensor([ [[0, 0], [0, 1], [1, 0], [1, 1]], # Outing 1 [[0, 0], [0, 1], [1, 0], [1, 1]], # Outing 2 [[0, 0], [0, 1], [1, 0], [1, 1]] # Outing 3 ], dtype=torch.uint8) # Mock total scores where the best scores are known # Assuming the best scores are for the combinations [1, 0, 3] for outings [1, 2, 3] total_score = torch.zeros((4, 4, 4)) total_score[1, 0, 3] = 1 # Highest score # Expected best assignments for each outing expected_assignments = torch.tensor([ [[0, 1]], # Outing 1 [[0, 0]], # Outing 2 [[1, 1]] # Outing 3 ], dtype=torch.uint8) # Add dimension to match the expected output shape result = extract_best_assignment(assignments_per_week, total_score) self.assertTrue(torch.equal(result, expected_assignments)) class TestGetNoOverlapInds(unittest.TestCase): def test_no_overlap(self): A = torch.tensor([[1, 0], [0, 1]]) B = torch.tensor([[0, 1], [1, 0]]) expected_result = torch.tensor([[0, 0], [1, 1]]) result = get_no_overlap_inds(A, B) self.assertTrue(torch.equal(result, expected_result)) def test_partial_overlap(self): A = torch.tensor([[1, 1], [0, 1]]) B = torch.tensor([[1, 0], [0, 1]]) expected_result = torch.tensor([[1, 0]]) result = get_no_overlap_inds(A, B) self.assertTrue(torch.equal(result, expected_result)) def test_complete_overlap(self): A = torch.tensor([[1, 1], [1, 1]]) B = torch.tensor([[1, 1], [1, 1]]) expected_result = torch.empty((0, 2), dtype=torch.int64) result = get_no_overlap_inds(A, B) self.assertTrue(torch.equal(result, expected_result)) def test_different_sizes(self): A = torch.tensor([[1, 1, 0, 0], [0, 1, 1, 0]]) B = torch.tensor([[1, 1, 0, 0], [0, 1, 1, 0], [1, 0, 0, 1]]) expected_result = torch.tensor([[1, 2]]) result = get_no_overlap_inds(A, B) self.assertTrue(torch.equal(result, expected_result)) class TestGenerateBinaryMatrices(unittest.TestCase): def test_correct_matrix_generation(self): num_rowers = 4 boat_sizes = [2, 3] expected_combinations = [math.comb(num_rowers, boat_size) for boat_size in boat_sizes] result_matrices = generate_binary_matrices(num_rowers, boat_sizes) for i, M in enumerate(result_matrices): self.assertEqual(M.shape[0], expected_combinations[i]) # Correct number of combinations self.assertEqual(M.shape[1], num_rowers) # Correct number of columns self.assertTrue(torch.all((M.sum(axis=1) == boat_sizes[i]).logical_or(M.sum(axis=1) == 0))) # Correct boat sizes def test_different_rower_and_boat_sizes(self): num_rowers = 5 boat_sizes = [1, 4] result_matrices = generate_binary_matrices(num_rowers, boat_sizes) for M, boat_size in zip(result_matrices, boat_sizes): self.assertEqual(M.shape, (math.comb(num_rowers, boat_size), num_rowers)) def test_output_type(self): num_rowers = 3 boat_sizes = [2] result_matrices = generate_binary_matrices(num_rowers, boat_sizes) for M in result_matrices: self.assertIsInstance(M, torch.Tensor) self.assertTrue(M.dtype, torch.bool) class TestEliminateInvalidBoats(unittest.TestCase): def test_no_elimination_of_valid_boats(self): binary_matrix = torch.tensor([[1, 0, 1], [1, 1, 0], [0, 1, 1]]) rower_sides = torch.tensor([1, -1, 0]) # Stroke, Bow, No preference expected_result = torch.tensor([[1, 0, 1], [1, 1, 0], [0, 1, 1]]) # Eliminate [1, 1, 0] combination result = eliminate_invalid_boats(binary_matrix, rower_sides) self.assertTrue(torch.equal(result, expected_result)) def test_elimination_of_invalid_boats(self): binary_matrix = torch.tensor([[1, 1, 0], [1, 0, 1]]) rower_sides = torch.tensor([1, 0, 1]) # Stroke, No preference, Stroke # Eliminate [1, 0, 1] combination because of two stroke siders expected_result = torch.tensor([[1, 1, 0]]) result = eliminate_invalid_boats(binary_matrix, rower_sides) self.assertTrue(torch.equal(result, expected_result)) def test_combination_limit(self): binary_matrix = torch.tensor([[1, 0, 1], [1, 0, 1], [0, 1, 1]]) rower_sides = torch.tensor([1, -1, 0]) # Stroke, Bow num_max_combinations = 2 result = eliminate_invalid_boats(binary_matrix, rower_sides, num_max_combinations) self.assertLessEqual(len(result), num_max_combinations) def test_output_type_and_shape(self): binary_matrix = torch.tensor([[1, 0, 1], [1, 1, 0], [0, 1, 1]]) rower_sides = torch.tensor([1, -1, 0]) result = eliminate_invalid_boats(binary_matrix, rower_sides) self.assertIsInstance(result, torch.Tensor) self.assertEqual(result.dim(), 2) class TestGenerateValidCombinations(unittest.TestCase): def test_valid_combinations(self): A = torch.tensor([[1, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0]]) B = torch.tensor([[1, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0], [1, 0, 0, 1, 0, 0]]) C = torch.tensor([[0, 0, 0, 0, 1, 1]]) result = generate_valid_assignments([A, B, C]) expected_result = torch.tensor([[2, 1, 1, 2, 3, 3]]) self.assertTrue(torch.equal(result, expected_result)) def test_combination_limit(self): A = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1 ,0], [0, 0, 0, 1]]) B = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1 ,0], [0, 0, 0, 1]]) C = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1 ,0], [0, 0, 0, 1]]) num_max_combinations = 2 result = generate_valid_assignments([A, B, C], num_max_combinations) self.assertLessEqual(len(result), num_max_combinations) def test_consistent_number_of_rowers(self): matrix1 = torch.tensor([[1, 0, 0], [0, 1, 0]]) matrix2 = torch.tensor([[1, 0], [0, 1]]) with self.assertRaises(AssertionError): generate_valid_assignments([matrix1, matrix2]) class TestEvaluateSkillVariance(unittest.TestCase): def test_predefined_skills_and_assignments(self): assignments = torch.tensor([[[1, 0, 1], [0, 1, 1]]]) # 1 outing, 2 combinations, 3 rowers skills = torch.tensor([3, 5, 7]) # Skill levels variance_1 = torch.var(torch.tensor([3., 7])) variance_2 = torch.var(torch.tensor([5., 7])) expected_result = torch.tensor([variance_1, variance_2], dtype=torch.float16) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) self.assertTrue(torch.equal(result, expected_result)) def test_multiple_boats(self): assignments = torch.tensor([[[1, 2, 1, 2], [2, 1, 1, 2], [1, 1, 2, 2]]]) # 1 outing, 3 combinations, 3 rowers skills = torch.tensor([3, 5, 7, 9]) # Skill levels variance_37 = torch.var(torch.tensor([3., 7])) variance_59 = torch.var(torch.tensor([5., 9])) variance_39 = torch.var(torch.tensor([3., 9])) variance_57 = torch.var(torch.tensor([5., 7])) variance_35 = torch.var(torch.tensor([3., 5])) variance_79 = torch.var(torch.tensor([7., 9])) expected_result = torch.tensor([ variance_37 + variance_59, variance_39 + variance_57, variance_35 + variance_79 ], dtype=torch.float16) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) self.assertIsInstance(result, torch.Tensor) self.assertTrue(torch.equal(result, expected_result)) def test_multiple_outings(self): assignments = torch.tensor([ [[1, 0, 1], [0, 1, 1]], # Outing 1 [[1, 0, 1], [0, 1, 1]] # Outing 2 ]) skills = torch.tensor([3, 5, 7]) variance_1 = torch.var(torch.tensor([3., 7])) variance_2 = torch.var(torch.tensor([5., 7])) expected_result = torch.tensor([ [2*variance_1, variance_2+variance_1], [variance_1+variance_2, 2*variance_2] ], dtype=torch.float16) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) self.assertTrue(torch.equal(result, expected_result)) def test_edge_case_no_rowers_assigned(self): assignments = torch.tensor([[[0, 0, 0], [0, 0, 0]]]) # No rowers assigned skills = torch.tensor([3, 5, 7]) result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) # Expect zero variance as no rowers are assigned self.assertTrue(torch.all(result == 0)) def test_edge_case_same_skill_level(self): assignments = torch.tensor([[[1, 0, 1], [0, 1, 1]]]) skills = torch.tensor([5, 5, 5]) # All rowers have the same skill level result = evaluate_skill_variance(assignments, skills, dtype=torch.float16) # Expect zero variance as all rowers have the same skill level self.assertTrue(torch.all(result == 0)) class TestEvaluateNumPreferredOutings(unittest.TestCase): def test_predefined_assignments_and_preferences(self): assignments = torch.tensor([ [[1,0,0], [0,1,0], [0,0,1]], # Outing 1 [[1,0,0], [0,1,0], [0,0,1]], # Outing 2 ]) preferred_outings = torch.tensor([0, 1, 2]) expected_result = torch.tensor([ [2, 1, 1], [1, 1, 0], [1, 0, 0] ]) result = evaluate_num_preferred_outings(assignments, preferred_outings) self.assertTrue(torch.equal(result, expected_result)) class TestPermuteTopAssignments(unittest.TestCase): def test_permute_top_assignments(self): # Small, handcrafted example assignments_per_week = torch.tensor([ [[1, 0, 0], [0, 1, 0]], # Outing 1 [[0, 1, 1], [1, 0, 1]] # Outing 2 ]) total_score = torch.tensor([ [0, 1], [3, 2] ]) # this means that the best assignment has the # index of [1, 0] in the score tensor # that translates to the assignment of # outing 1 is [0, 1, 0] (the 1st combination of the 1st outing) # outing 2 is [0, 1, 1] (the 0th combination of the 2nd outing) # The valid replacements are used for the permutation # to generate alternatives to a single outing at a time valid_assignments = [ torch.tensor([[2, 0, 0], [0, 2, 0], [0, 0, 2]]), torch.tensor([[0, 2, 2], [2, 0, 2], [2, 2, 0]]) ] # Although the algorithm would never generate these assignments # because if there are two boats available they would need to be used # so this scenario is just for illustrative purposes. num_permutations = 3
result = permute_top_assignments(
14
2023-12-18 05:12:36+00:00
12k
Azure-Samples/functions-python-web-crawler
.venv/Lib/site-packages/charset_normalizer/cd.py
[ { "identifier": "FREQUENCIES", "path": ".venv/Lib/site-packages/charset_normalizer/constant.py", "snippet": "FREQUENCIES: Dict[str, List[str]] = {\n \"English\": [\n \"e\",\n \"a\",\n \"t\",\n \"i\",\n \"o\",\n \"n\",\n \"s\",\n \"r\",\n ...
import importlib from codecs import IncrementalDecoder from collections import Counter from functools import lru_cache from typing import Counter as TypeCounter, Dict, List, Optional, Tuple from .constant import ( FREQUENCIES, KO_NAMES, LANGUAGE_SUPPORTED_COUNT, TOO_SMALL_SEQUENCE, ZH_NAMES, ) from .md import is_suspiciously_successive_range from .models import CoherenceMatches from .utils import ( is_accentuated, is_latin, is_multi_byte_encoding, is_unicode_range_secondary, unicode_range, )
10,302
def encoding_unicode_range(iana_name: str) -> List[str]: """ Return associated unicode ranges in a single byte code page. """ if is_multi_byte_encoding(iana_name): raise IOError("Function not supported on multi-byte code page") decoder = importlib.import_module( "encodings.{}".format(iana_name) ).IncrementalDecoder p: IncrementalDecoder = decoder(errors="ignore") seen_ranges: Dict[str, int] = {} character_count: int = 0 for i in range(0x40, 0xFF): chunk: str = p.decode(bytes([i])) if chunk: character_range: Optional[str] = unicode_range(chunk) if character_range is None: continue if is_unicode_range_secondary(character_range) is False: if character_range not in seen_ranges: seen_ranges[character_range] = 0 seen_ranges[character_range] += 1 character_count += 1 return sorted( [ character_range for character_range in seen_ranges if seen_ranges[character_range] / character_count >= 0.15 ] ) def unicode_range_languages(primary_range: str) -> List[str]: """ Return inferred languages used with a unicode range. """ languages: List[str] = [] for language, characters in FREQUENCIES.items(): for character in characters: if unicode_range(character) == primary_range: languages.append(language) break return languages @lru_cache() def encoding_languages(iana_name: str) -> List[str]: """ Single-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ unicode_ranges: List[str] = encoding_unicode_range(iana_name) primary_range: Optional[str] = None for specified_range in unicode_ranges: if "Latin" not in specified_range: primary_range = specified_range break if primary_range is None: return ["Latin Based"] return unicode_range_languages(primary_range) @lru_cache() def mb_encoding_languages(iana_name: str) -> List[str]: """ Multi-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ if ( iana_name.startswith("shift_") or iana_name.startswith("iso2022_jp") or iana_name.startswith("euc_j") or iana_name == "cp932" ): return ["Japanese"] if iana_name.startswith("gb") or iana_name in ZH_NAMES: return ["Chinese"] if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: return ["Korean"] return [] @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) def get_target_features(language: str) -> Tuple[bool, bool]: """ Determine main aspects from a supported language if it contains accents and if is pure Latin. """ target_have_accents: bool = False target_pure_latin: bool = True for character in FREQUENCIES[language]: if not target_have_accents and is_accentuated(character): target_have_accents = True
def encoding_unicode_range(iana_name: str) -> List[str]: """ Return associated unicode ranges in a single byte code page. """ if is_multi_byte_encoding(iana_name): raise IOError("Function not supported on multi-byte code page") decoder = importlib.import_module( "encodings.{}".format(iana_name) ).IncrementalDecoder p: IncrementalDecoder = decoder(errors="ignore") seen_ranges: Dict[str, int] = {} character_count: int = 0 for i in range(0x40, 0xFF): chunk: str = p.decode(bytes([i])) if chunk: character_range: Optional[str] = unicode_range(chunk) if character_range is None: continue if is_unicode_range_secondary(character_range) is False: if character_range not in seen_ranges: seen_ranges[character_range] = 0 seen_ranges[character_range] += 1 character_count += 1 return sorted( [ character_range for character_range in seen_ranges if seen_ranges[character_range] / character_count >= 0.15 ] ) def unicode_range_languages(primary_range: str) -> List[str]: """ Return inferred languages used with a unicode range. """ languages: List[str] = [] for language, characters in FREQUENCIES.items(): for character in characters: if unicode_range(character) == primary_range: languages.append(language) break return languages @lru_cache() def encoding_languages(iana_name: str) -> List[str]: """ Single-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ unicode_ranges: List[str] = encoding_unicode_range(iana_name) primary_range: Optional[str] = None for specified_range in unicode_ranges: if "Latin" not in specified_range: primary_range = specified_range break if primary_range is None: return ["Latin Based"] return unicode_range_languages(primary_range) @lru_cache() def mb_encoding_languages(iana_name: str) -> List[str]: """ Multi-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ if ( iana_name.startswith("shift_") or iana_name.startswith("iso2022_jp") or iana_name.startswith("euc_j") or iana_name == "cp932" ): return ["Japanese"] if iana_name.startswith("gb") or iana_name in ZH_NAMES: return ["Chinese"] if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: return ["Korean"] return [] @lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) def get_target_features(language: str) -> Tuple[bool, bool]: """ Determine main aspects from a supported language if it contains accents and if is pure Latin. """ target_have_accents: bool = False target_pure_latin: bool = True for character in FREQUENCIES[language]: if not target_have_accents and is_accentuated(character): target_have_accents = True
if target_pure_latin and is_latin(character) is False:
8
2023-12-16 04:12:01+00:00
12k
liebrandapps/FindMyGUI
main.py
[ { "identifier": "AirTag", "path": "airTag.py", "snippet": "class AirTag:\n\n def __init__(self, ctx, jsonFile=None):\n self.log = ctx.log\n self.cfg = ctx.cfg\n self.__id = uuid.uuid4().hex\n self._name = \"\"\n self._privateKey = None\n self._advertisementKe...
import glob import logging import signal import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from logging.handlers import RotatingFileHandler from os import makedirs from os.path import join, exists, splitext from threading import Thread from urllib.parse import parse_qs, urlparse from airTag import AirTag from api import API from config import Config from context import Context from daemon import Daemon
7,320
loghdl.setLevel(cfg.logging_logLevel) _log.addHandler(loghdl) if cfg.logging_stdout and not runAsDaemon: loghdl = logging.StreamHandler(sys.stdout) loghdl.setFormatter(logging.Formatter(cfg.logging_msgFormat)) loghdl.setLevel(cfg.logging_logLevel) _log.addHandler(loghdl) _log.disabled = False return _log except Exception as e: print("[%s] Unable to initialize logging. Reason: %s" % (APP, e)) return None def terminate(sigNo, _): global doTerminate global myServer global httpIsRunning if doTerminate: return doTerminate = True ctx.log.info(f"[{APP}] Terminating with Signal {sigNo} {sigs[sigNo]}") if httpIsRunning: Thread(target=myServer.shutdown).start() def loadAirTags(): global ctx airTagDir = ctx.cfg.general_airTagDirectory airTagSuffix = ctx.cfg.general_airTagSuffix if not exists(airTagDir): ctx.log.info( f"[loadAirTags] Airtags Directory '{airTagDir}' does not exist, creating it. This will be used to store Airtag key information.") makedirs(airTagDir) tags = glob.glob(join(airTagDir, '*' + airTagSuffix)) for t in tags: airtag = AirTag(ctx, jsonFile=t) ctx.airtags[airtag.id] = airtag class FindMyServer(BaseHTTPRequestHandler): ''' Extension: ContentType, Encode ''' contentTypeDct = {'.html': ["text/html", True], '.js': ["application/javascript", True], '.css': ["text/css", True], '.png': ["image/png", False], } def do_GET(self): if self.path.startswith('/api'): api = API(ctx) query_components = parse_qs(urlparse(self.path).query) cmd = query_components["command"] result = api.call(cmd[0], params=query_components) self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(result.encode('UTF-8')) else: file = "/index.html" if self.path == "/" else self.path file = join('www', file[1:]) ext = splitext(file)[1] ct = self.contentTypeDct[ext] if ext in self.contentTypeDct.keys() else None if exists(file) and ct is not None: contentType = ct[0] encode = ct[1] self.send_response(200) self.send_header("Content-type", contentType) self.end_headers() with open(file, 'r' if encode else 'rb') as f: data = f.read() self.wfile.write(data.encode('UTF-8') if encode else data) else: self.send_response(404) self.end_headers() if __name__ == '__main__': doTerminate = False initialConfig = { "general": { "httpHost": ['String', '0.0.0.0'], "httpPort": ['Integer', 8008], "httpFiles": ['String', 'www'], "anisetteHost": ['String', 'http://192.168.2.15'], "anisettePort": ['Integer', 6969], "airTagDirectory": ['String', 'airtags'], "airTagSuffix": ['String', '.json'], "history": ["Integer", 30], }, "logging": { "logFile": ["String", "/tmp/findMyGUI.log"], "maxFilesize": ["Integer", 1000000], "msgFormat": ["String", "%(asctime)s, %(levelname)s, %(module)s {%(process)d}, %(lineno)d, %(message)s"], "logLevel": ["Integer", 10], "stdout": ["Boolean", True], }, "appleId": { "appleId": ["String", ''], "password": ["String", ''], "trustedDevice": ["Boolean", False], } } path = join(CONFIG_DIR, CONFIG_FILE) if not (exists(path)): print(f"[{APP}] No config file {CONFIG_FILE} found at {CONFIG_DIR}, using defaults") cfg = Config(path) cfg.addScope(initialConfig) runAsDaemon = False if len(sys.argv) > 1: todo = sys.argv[1] if todo in ['start', 'stop', 'restart', 'status']: runAsDaemon = True pidFile = cfg.general_pidFile logFile = cfg.logging_logFile d = Daemon(pidFile, APP, logFile) d.startstop(todo, stdout=logFile, stderr=logFile) log = setupLogger() if log is None: sys.exit(-126)
""" Mark Liebrand 2024 This file is part of FindMyGUI which is released under the Apache 2.0 License See file LICENSE or go to for full license details https://github.com/liebrandapps/FindMyGUI """ APP = "findMyGUI" CONFIG_DIR = "./" CONFIG_FILE = "findMyGUI.ini" def setupLogger(): global runAsDaemon try: _log = logging.Logger(APP) loghdl = RotatingFileHandler(cfg.logging_logFile, 'a', cfg.logging_maxFilesize, 4) loghdl.setFormatter(logging.Formatter(cfg.logging_msgFormat)) loghdl.setLevel(cfg.logging_logLevel) _log.addHandler(loghdl) if cfg.logging_stdout and not runAsDaemon: loghdl = logging.StreamHandler(sys.stdout) loghdl.setFormatter(logging.Formatter(cfg.logging_msgFormat)) loghdl.setLevel(cfg.logging_logLevel) _log.addHandler(loghdl) _log.disabled = False return _log except Exception as e: print("[%s] Unable to initialize logging. Reason: %s" % (APP, e)) return None def terminate(sigNo, _): global doTerminate global myServer global httpIsRunning if doTerminate: return doTerminate = True ctx.log.info(f"[{APP}] Terminating with Signal {sigNo} {sigs[sigNo]}") if httpIsRunning: Thread(target=myServer.shutdown).start() def loadAirTags(): global ctx airTagDir = ctx.cfg.general_airTagDirectory airTagSuffix = ctx.cfg.general_airTagSuffix if not exists(airTagDir): ctx.log.info( f"[loadAirTags] Airtags Directory '{airTagDir}' does not exist, creating it. This will be used to store Airtag key information.") makedirs(airTagDir) tags = glob.glob(join(airTagDir, '*' + airTagSuffix)) for t in tags: airtag = AirTag(ctx, jsonFile=t) ctx.airtags[airtag.id] = airtag class FindMyServer(BaseHTTPRequestHandler): ''' Extension: ContentType, Encode ''' contentTypeDct = {'.html': ["text/html", True], '.js': ["application/javascript", True], '.css': ["text/css", True], '.png': ["image/png", False], } def do_GET(self): if self.path.startswith('/api'): api = API(ctx) query_components = parse_qs(urlparse(self.path).query) cmd = query_components["command"] result = api.call(cmd[0], params=query_components) self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(result.encode('UTF-8')) else: file = "/index.html" if self.path == "/" else self.path file = join('www', file[1:]) ext = splitext(file)[1] ct = self.contentTypeDct[ext] if ext in self.contentTypeDct.keys() else None if exists(file) and ct is not None: contentType = ct[0] encode = ct[1] self.send_response(200) self.send_header("Content-type", contentType) self.end_headers() with open(file, 'r' if encode else 'rb') as f: data = f.read() self.wfile.write(data.encode('UTF-8') if encode else data) else: self.send_response(404) self.end_headers() if __name__ == '__main__': doTerminate = False initialConfig = { "general": { "httpHost": ['String', '0.0.0.0'], "httpPort": ['Integer', 8008], "httpFiles": ['String', 'www'], "anisetteHost": ['String', 'http://192.168.2.15'], "anisettePort": ['Integer', 6969], "airTagDirectory": ['String', 'airtags'], "airTagSuffix": ['String', '.json'], "history": ["Integer", 30], }, "logging": { "logFile": ["String", "/tmp/findMyGUI.log"], "maxFilesize": ["Integer", 1000000], "msgFormat": ["String", "%(asctime)s, %(levelname)s, %(module)s {%(process)d}, %(lineno)d, %(message)s"], "logLevel": ["Integer", 10], "stdout": ["Boolean", True], }, "appleId": { "appleId": ["String", ''], "password": ["String", ''], "trustedDevice": ["Boolean", False], } } path = join(CONFIG_DIR, CONFIG_FILE) if not (exists(path)): print(f"[{APP}] No config file {CONFIG_FILE} found at {CONFIG_DIR}, using defaults") cfg = Config(path) cfg.addScope(initialConfig) runAsDaemon = False if len(sys.argv) > 1: todo = sys.argv[1] if todo in ['start', 'stop', 'restart', 'status']: runAsDaemon = True pidFile = cfg.general_pidFile logFile = cfg.logging_logFile d = Daemon(pidFile, APP, logFile) d.startstop(todo, stdout=logFile, stderr=logFile) log = setupLogger() if log is None: sys.exit(-126)
ctx = Context(cfg, log)
3
2023-12-16 12:39:52+00:00
12k
YaoFANGUK/video-subtitle-remover
backend/scenedetect/backends/opencv.py
[ { "identifier": "FrameTimecode", "path": "backend/scenedetect/frame_timecode.py", "snippet": "class FrameTimecode:\n \"\"\"Object for frame-based timecodes, using the video framerate to compute back and\n forth between frame number and seconds/timecode.\n\n A timecode is valid only if it compli...
from logging import getLogger from typing import AnyStr, Tuple, Union, Optional from numpy import ndarray from backend.scenedetect.frame_timecode import FrameTimecode, MAX_FPS_DELTA from backend.scenedetect.platform import get_file_name from backend.scenedetect.video_stream import VideoStream, SeekError, VideoOpenFailure, FrameRateUnavailable import math import os.path import cv2
9,093
For 1-based indices (first frame is frame #1), the target frame number needs to be converted to 0-based by subtracting one. For example, if we want to seek to the first frame, we call seek(0) followed by read(). If we want to seek to the 5th frame, we call seek(4) followed by read(), at which point frame_number will be 5. Not supported if the VideoStream is a device/camera. Untested with web streams. Arguments: target: Target position in video stream to seek to. If float, interpreted as time in seconds. If int, interpreted as frame number. Raises: SeekError: An error occurs while seeking, or seeking is not supported. ValueError: `target` is not a valid value (i.e. it is negative). """ if self._is_device: raise SeekError("Cannot seek if input is a device!") if target < 0: raise ValueError("Target seek position cannot be negative!") # Have to seek one behind and call grab() after to that the VideoCapture # returns a valid timestamp when using CAP_PROP_POS_MSEC. target_frame_cv2 = (self.base_timecode + target).get_frames() if target_frame_cv2 > 0: target_frame_cv2 -= 1 self._cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame_cv2) self._has_grabbed = False # Preemptively grab the frame behind the target position if possible. if target > 0: self._has_grabbed = self._cap.grab() # If we seeked past the end of the video, need to seek one frame backwards # from the current position and grab that frame instead. if not self._has_grabbed: seek_pos = round(self._cap.get(cv2.CAP_PROP_POS_FRAMES) - 1.0) self._cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, seek_pos)) self._has_grabbed = self._cap.grab() def reset(self): """ Close and re-open the VideoStream (should be equivalent to calling `seek(0)`). """ self._cap.release() self._open_capture(self._frame_rate) def read(self, decode: bool = True, advance: bool = True) -> Union[ndarray, bool]: """Read and decode the next frame as a numpy.ndarray. Returns False when video ends, or the maximum number of decode attempts has passed. Arguments: decode: Decode and return the frame. advance: Seek to the next frame. If False, will return the current (last) frame. Returns: If decode = True, the decoded frame (numpy.ndarray), or False (bool) if end of video. If decode = False, a bool indicating if advancing to the the next frame succeeded. """ if not self._cap.isOpened(): return False # Grab the next frame if possible. if advance: has_grabbed = self._cap.grab() # If we failed to grab the frame, retry a few times if required. if not has_grabbed: if self.duration > 0 and self.position < (self.duration - 1): for _ in range(self._max_decode_attempts): has_grabbed = self._cap.grab() if has_grabbed: break # Report previous failure in debug mode. if has_grabbed: self._decode_failures += 1 logger.debug('Frame failed to decode.') if not self._warning_displayed and self._decode_failures > 1: logger.warning('Failed to decode some frames, results may be inaccurate.') # We didn't manage to grab a frame even after retrying, so just return. if not has_grabbed: return False self._has_grabbed = True # Need to make sure we actually grabbed a frame before calling retrieve. if decode and self._has_grabbed: _, frame = self._cap.retrieve() return frame return self._has_grabbed # # Private Methods # def _open_capture(self, framerate: Optional[float] = None): """Opens capture referenced by this object and resets internal state.""" if self._is_device and self._path_or_device < 0: raise ValueError('Invalid/negative device ID specified.') input_is_video_file = not self._is_device and not any( identifier in self._path_or_device for identifier in NON_VIDEO_FILE_INPUT_IDENTIFIERS) # We don't have a way of querying why opening a video fails (errors are logged at least), # so provide a better error message if we try to open a file that doesn't exist. if input_is_video_file: if not os.path.exists(self._path_or_device): raise OSError('Video file not found.') cap = cv2.VideoCapture(self._path_or_device) if not cap.isOpened(): raise VideoOpenFailure( 'Ensure file is valid video and system dependencies are up to date.\n') # Display an error if the video codec type seems unsupported (#86) as this indicates # potential video corruption, or may explain missing frames. We only perform this check # for video files on-disk (skipped for devices, image sequences, streams, etc...). codec_unsupported: bool = (int(abs(cap.get(cv2.CAP_PROP_FOURCC))) == 0) if codec_unsupported and input_is_video_file: logger.error('Video codec detection failed. If output is incorrect:\n' ' - Re-encode the input video with ffmpeg\n' ' - Update OpenCV (pip install --upgrade opencv-python)\n' ' - Use the PyAV backend (--backend pyav)\n' 'For details, see https://github.com/Breakthrough/PySceneDetect/issues/86') # Ensure the framerate is correct to avoid potential divide by zero errors. This can be # addressed in the PyAV backend if required since it supports integer timebases. assert framerate is None or framerate > MAX_FPS_DELTA, "Framerate must be validated if set!" if framerate is None: framerate = cap.get(cv2.CAP_PROP_FPS) if framerate < MAX_FPS_DELTA:
# -*- coding: utf-8 -*- # # PySceneDetect: Python-Based Video Scene Detector # ------------------------------------------------------------------- # [ Site: https://scenedetect.com ] # [ Docs: https://scenedetect.com/docs/ ] # [ Github: https://github.com/Breakthrough/PySceneDetect/ ] # # Copyright (C) 2014-2023 Brandon Castellano <http://www.bcastell.com>. # PySceneDetect is licensed under the BSD 3-Clause License; see the # included LICENSE file, or visit one of the above pages for details. # """:class:`VideoStreamCv2` is backed by the OpenCV `VideoCapture` object. This is the default backend. Works with video files, image sequences, and network streams/URLs. For wrapping input devices or pipes, there is also :class:`VideoCaptureAdapter` which can be constructed from an existing `cv2.VideoCapture`. This allows performing scene detection on inputs which do not support seeking. """ logger = getLogger('pyscenedetect') IMAGE_SEQUENCE_IDENTIFIER = '%' NON_VIDEO_FILE_INPUT_IDENTIFIERS = ( IMAGE_SEQUENCE_IDENTIFIER, # image sequence '://', # URL/network stream ' ! ', # gstreamer pipe ) def _get_aspect_ratio(cap: cv2.VideoCapture, epsilon: float = 0.0001) -> float: """Display/pixel aspect ratio of the VideoCapture as a float (1.0 represents square pixels).""" # Versions of OpenCV < 3.4.1 do not support this, so we fall back to 1.0. if not 'CAP_PROP_SAR_NUM' in dir(cv2): return 1.0 num: float = cap.get(cv2.CAP_PROP_SAR_NUM) den: float = cap.get(cv2.CAP_PROP_SAR_DEN) # If numerator or denominator are close to zero, so we fall back to 1.0. if abs(num) < epsilon or abs(den) < epsilon: return 1.0 return num / den class VideoStreamCv2(VideoStream): """OpenCV `cv2.VideoCapture` backend.""" def __init__( self, path: AnyStr = None, framerate: Optional[float] = None, max_decode_attempts: int = 5, path_or_device: Union[bytes, str, int] = None, ): """Open a video file, image sequence, or network stream. Arguments: path: Path to the video. Can be a file, image sequence (`'folder/DSC_%04d.jpg'`), or network stream. framerate: If set, overrides the detected framerate. max_decode_attempts: Number of attempts to continue decoding the video after a frame fails to decode. This allows processing videos that have a few corrupted frames or metadata (in which case accuracy of detection algorithms may be lower). Once this limit is passed, decoding will stop and emit an error. path_or_device: [DEPRECATED] Specify `path` for files, image sequences, or network streams/URLs. Use `VideoCaptureAdapter` for devices/pipes. Raises: OSError: file could not be found or access was denied VideoOpenFailure: video could not be opened (may be corrupted) ValueError: specified framerate is invalid """ super().__init__() # TODO(v0.7): Replace with DeprecationWarning that `path_or_device` will be removed in v0.8. if path_or_device is not None: logger.error('path_or_device is deprecated, use path or VideoCaptureAdapter instead.') path = path_or_device if path is None: raise ValueError('Path must be specified!') if framerate is not None and framerate < MAX_FPS_DELTA: raise ValueError('Specified framerate (%f) is invalid!' % framerate) if max_decode_attempts < 0: raise ValueError('Maximum decode attempts must be >= 0!') self._path_or_device = path self._is_device = isinstance(self._path_or_device, int) # Initialized in _open_capture: self._cap: Optional[ cv2.VideoCapture] = None # Reference to underlying cv2.VideoCapture object. self._frame_rate: Optional[float] = None # VideoCapture state self._has_grabbed = False self._max_decode_attempts = max_decode_attempts self._decode_failures = 0 self._warning_displayed = False self._open_capture(framerate) # # Backend-Specific Methods/Properties # @property def capture(self) -> cv2.VideoCapture: """Returns reference to underlying VideoCapture object. Use with caution. Prefer to use this property only to take ownership of the underlying cv2.VideoCapture object backing this object. Seeking or using the read/grab methods through this property are unsupported and will leave this object in an inconsistent state. """ assert self._cap return self._cap # # VideoStream Methods/Properties # BACKEND_NAME = 'opencv' """Unique name used to identify this backend.""" @property def frame_rate(self) -> float: """Framerate in frames/sec.""" assert self._frame_rate return self._frame_rate @property def path(self) -> Union[bytes, str]: """Video or device path.""" if self._is_device: assert isinstance(self._path_or_device, (int)) return "Device %d" % self._path_or_device assert isinstance(self._path_or_device, (bytes, str)) return self._path_or_device @property def name(self) -> str: """Name of the video, without extension, or device.""" if self._is_device: return self.path file_name: str = get_file_name(self.path, include_extension=False) if IMAGE_SEQUENCE_IDENTIFIER in file_name: # file_name is an image sequence, trim everything including/after the %. # TODO: This excludes any suffix after the sequence identifier. file_name = file_name[:file_name.rfind(IMAGE_SEQUENCE_IDENTIFIER)] return file_name @property def is_seekable(self) -> bool: """True if seek() is allowed, False otherwise. Always False if opening a device/webcam.""" return not self._is_device @property def frame_size(self) -> Tuple[int, int]: """Size of each video frame in pixels as a tuple of (width, height).""" return (math.trunc(self._cap.get(cv2.CAP_PROP_FRAME_WIDTH)), math.trunc(self._cap.get(cv2.CAP_PROP_FRAME_HEIGHT))) @property def duration(self) -> Optional[FrameTimecode]: """Duration of the stream as a FrameTimecode, or None if non terminating.""" if self._is_device: return None return self.base_timecode + math.trunc(self._cap.get(cv2.CAP_PROP_FRAME_COUNT)) @property def aspect_ratio(self) -> float: """Display/pixel aspect ratio as a float (1.0 represents square pixels).""" return _get_aspect_ratio(self._cap) @property def position(self) -> FrameTimecode: """Current position within stream as FrameTimecode. This can be interpreted as presentation time stamp of the last frame which was decoded by calling `read` with advance=True. This method will always return 0 (e.g. be equal to `base_timecode`) if no frames have been `read`.""" if self.frame_number < 1: return self.base_timecode return self.base_timecode + (self.frame_number - 1) @property def position_ms(self) -> float: """Current position within stream as a float of the presentation time in milliseconds. The first frame has a time of 0.0 ms. This method will always return 0.0 if no frames have been `read`.""" return self._cap.get(cv2.CAP_PROP_POS_MSEC) @property def frame_number(self) -> int: """Current position within stream in frames as an int. 1 indicates the first frame was just decoded by the last call to `read` with advance=True, whereas 0 indicates that no frames have been `read`. This method will always return 0 if no frames have been `read`.""" return math.trunc(self._cap.get(cv2.CAP_PROP_POS_FRAMES)) def seek(self, target: Union[FrameTimecode, float, int]): """Seek to the given timecode. If given as a frame number, represents the current seek pointer (e.g. if seeking to 0, the next frame decoded will be the first frame of the video). For 1-based indices (first frame is frame #1), the target frame number needs to be converted to 0-based by subtracting one. For example, if we want to seek to the first frame, we call seek(0) followed by read(). If we want to seek to the 5th frame, we call seek(4) followed by read(), at which point frame_number will be 5. Not supported if the VideoStream is a device/camera. Untested with web streams. Arguments: target: Target position in video stream to seek to. If float, interpreted as time in seconds. If int, interpreted as frame number. Raises: SeekError: An error occurs while seeking, or seeking is not supported. ValueError: `target` is not a valid value (i.e. it is negative). """ if self._is_device: raise SeekError("Cannot seek if input is a device!") if target < 0: raise ValueError("Target seek position cannot be negative!") # Have to seek one behind and call grab() after to that the VideoCapture # returns a valid timestamp when using CAP_PROP_POS_MSEC. target_frame_cv2 = (self.base_timecode + target).get_frames() if target_frame_cv2 > 0: target_frame_cv2 -= 1 self._cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame_cv2) self._has_grabbed = False # Preemptively grab the frame behind the target position if possible. if target > 0: self._has_grabbed = self._cap.grab() # If we seeked past the end of the video, need to seek one frame backwards # from the current position and grab that frame instead. if not self._has_grabbed: seek_pos = round(self._cap.get(cv2.CAP_PROP_POS_FRAMES) - 1.0) self._cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, seek_pos)) self._has_grabbed = self._cap.grab() def reset(self): """ Close and re-open the VideoStream (should be equivalent to calling `seek(0)`). """ self._cap.release() self._open_capture(self._frame_rate) def read(self, decode: bool = True, advance: bool = True) -> Union[ndarray, bool]: """Read and decode the next frame as a numpy.ndarray. Returns False when video ends, or the maximum number of decode attempts has passed. Arguments: decode: Decode and return the frame. advance: Seek to the next frame. If False, will return the current (last) frame. Returns: If decode = True, the decoded frame (numpy.ndarray), or False (bool) if end of video. If decode = False, a bool indicating if advancing to the the next frame succeeded. """ if not self._cap.isOpened(): return False # Grab the next frame if possible. if advance: has_grabbed = self._cap.grab() # If we failed to grab the frame, retry a few times if required. if not has_grabbed: if self.duration > 0 and self.position < (self.duration - 1): for _ in range(self._max_decode_attempts): has_grabbed = self._cap.grab() if has_grabbed: break # Report previous failure in debug mode. if has_grabbed: self._decode_failures += 1 logger.debug('Frame failed to decode.') if not self._warning_displayed and self._decode_failures > 1: logger.warning('Failed to decode some frames, results may be inaccurate.') # We didn't manage to grab a frame even after retrying, so just return. if not has_grabbed: return False self._has_grabbed = True # Need to make sure we actually grabbed a frame before calling retrieve. if decode and self._has_grabbed: _, frame = self._cap.retrieve() return frame return self._has_grabbed # # Private Methods # def _open_capture(self, framerate: Optional[float] = None): """Opens capture referenced by this object and resets internal state.""" if self._is_device and self._path_or_device < 0: raise ValueError('Invalid/negative device ID specified.') input_is_video_file = not self._is_device and not any( identifier in self._path_or_device for identifier in NON_VIDEO_FILE_INPUT_IDENTIFIERS) # We don't have a way of querying why opening a video fails (errors are logged at least), # so provide a better error message if we try to open a file that doesn't exist. if input_is_video_file: if not os.path.exists(self._path_or_device): raise OSError('Video file not found.') cap = cv2.VideoCapture(self._path_or_device) if not cap.isOpened(): raise VideoOpenFailure( 'Ensure file is valid video and system dependencies are up to date.\n') # Display an error if the video codec type seems unsupported (#86) as this indicates # potential video corruption, or may explain missing frames. We only perform this check # for video files on-disk (skipped for devices, image sequences, streams, etc...). codec_unsupported: bool = (int(abs(cap.get(cv2.CAP_PROP_FOURCC))) == 0) if codec_unsupported and input_is_video_file: logger.error('Video codec detection failed. If output is incorrect:\n' ' - Re-encode the input video with ffmpeg\n' ' - Update OpenCV (pip install --upgrade opencv-python)\n' ' - Use the PyAV backend (--backend pyav)\n' 'For details, see https://github.com/Breakthrough/PySceneDetect/issues/86') # Ensure the framerate is correct to avoid potential divide by zero errors. This can be # addressed in the PyAV backend if required since it supports integer timebases. assert framerate is None or framerate > MAX_FPS_DELTA, "Framerate must be validated if set!" if framerate is None: framerate = cap.get(cv2.CAP_PROP_FPS) if framerate < MAX_FPS_DELTA:
raise FrameRateUnavailable()
6
2023-10-25 02:50:01+00:00
12k
Genesis-Embodied-AI/RoboGen
manipulation/sim.py
[ { "identifier": "Panda", "path": "manipulation/panda.py", "snippet": "class Panda(Robot):\n def __init__(self, controllable_joints='right', slider=True, floating=False):\n self.slider = slider\n self.floating = floating\n if not floating:\n if not slider:\n ...
import numpy as np import pybullet as p import gym import pickle import yaml import os.path as osp from gym.utils import seeding from gym import spaces from collections import defaultdict from scipy.spatial.transform import Rotation as R from manipulation.panda import Panda from manipulation.ur5 import UR5 from manipulation.sawyer import Sawyer from manipulation.utils import parse_config, load_env, download_and_parse_objavarse_obj_from_yaml_config from manipulation.gpt_reward_api import get_joint_id_from_name, get_link_id_from_name from manipulation.table_utils import table_paths, table_scales, table_poses, table_bbox_scale_down_factors
7,486
skip = False for spatial_relationship in spatial_relationships: words = spatial_relationship.lower().split(",") words = [word.strip().lstrip() for word in words] if name in words and name2 in words: skip = True break if skip: continue contact_points = p.getClosestPoints(id, id2, 0.01, physicsClientId=self.id) if len(contact_points) > 0: contact_point = contact_points[0] push_direction = contact_point[7] push_direction = np.array([push_direction[0], push_direction[1], push_direction[2]]) # both are distractors or both are not, push both objects away if (self.is_distractor[name] and self.is_distractor[name2]) or \ (not self.is_distractor[name] and not self.is_distractor[name2]): push_directions[id].append(-push_direction) push_directions[id2].append(push_direction) # only 1 is distractor, only pushes the distractor if self.is_distractor[name] and not self.is_distractor[name2]: push_directions[id].append(push_direction) if not self.is_distractor[name] and self.is_distractor[name2]: push_directions[id2].append(-push_direction) detected_collision = True # collisions between robot and objects, only push object away for name, id in self.urdf_ids.items(): if name == 'robot' or name == 'plane' or name == 'init_table': continue contact_points = p.getClosestPoints(self.robot.body, id, 0.05, physicsClientId=self.id) if len(contact_points) > 0: contact_point = contact_points[0] push_direction = contact_point[7] push_direction = np.array([push_direction[0], push_direction[1], push_direction[2]]) push_directions[id].append(-push_direction) detected_collision = True # between table and objects that should not be placed on table if self.use_table: for name, id in self.urdf_ids.items(): if name == 'robot' or name == 'plane' or name == 'init_table': continue if self.on_tables[name]: continue contact_points = p.getClosestPoints(self.robot.body, id, 0.05, physicsClientId=self.id) if len(contact_points) > 0: contact_point = contact_points[0] push_direction = contact_point[7] push_direction = np.array([push_direction[0], push_direction[1], push_direction[2]]) push_directions[id].append(-push_direction) detected_collision = True # move objects push_distance = 0.1 for id in push_directions: for direction in push_directions[id]: pos, orient = p.getBasePositionAndOrientation(id, physicsClientId=self.id) new_pos = np.array(pos) + push_distance * direction new_pos = self.clip_within_workspace(robot_base_pos, new_pos, self.on_tables[name]) new_pos[2] = object_height[id] p.resetBasePositionAndOrientation(id, new_pos, orient, physicsClientId=self.id) p.stepSimulation(physicsClientId=self.id) collision = detected_collision collision_cnt += 1 if collision_cnt > 1000: break def record_initial_joint_and_pose(self): self.initial_joint_angle = {} for name in self.urdf_ids: obj_id = self.urdf_ids[name.lower()] if name == 'robot' or name == 'plane' or name == "init_table": continue if self.urdf_types[name.lower()] == 'urdf': self.initial_joint_angle[name] = {} num_joints = p.getNumJoints(obj_id, physicsClientId=self.id) for joint_idx in range(num_joints): joint_name = p.getJointInfo(obj_id, joint_idx, physicsClientId=self.id)[1].decode("utf-8") joint_angle = p.getJointState(obj_id, joint_idx, physicsClientId=self.id)[0] self.initial_joint_angle[name][joint_name] = joint_angle self.initial_pos = {} self.initial_orient = {} for name in self.urdf_ids: obj_id = self.urdf_ids[name.lower()] if name == 'robot' or name == 'plane' or name == "init_table": continue pos, orient = p.getBasePositionAndOrientation(obj_id, physicsClientId=self.id) self.initial_pos[name] = pos self.initial_orient[name] = orient def set_to_default_joint_angles(self): for obj_name in self.urdf_ids: if obj_name == 'robot' or obj_name == 'plane' or obj_name == "init_table": continue obj_id = self.urdf_ids[obj_name] num_joints = p.getNumJoints(obj_id, physicsClientId=self.id) for joint_idx in range(num_joints): joint_limit_low, joint_limit_high = p.getJointInfo(obj_id, joint_idx, physicsClientId=self.id)[8:10] if joint_limit_low > joint_limit_high: joint_limit_low, joint_limit_high = joint_limit_high, joint_limit_low joint_val = joint_limit_low + 0.06 * (joint_limit_high - joint_limit_low) p.resetJointState(obj_id, joint_idx, joint_val, physicsClientId=self.id) def handle_gpt_special_relationships(self, spatial_relationships): # we support "on" and "in" for now, but this can be extended to more relationships for spatial_relationship in spatial_relationships: words = spatial_relationship.lower().split(",") words = [word.strip().lstrip() for word in words] if words[0] == "on": obj_a = words[1] obj_b = words[2] if len(words) == 4: obj_b_link = words[3]
class SimpleEnv(gym.Env): def __init__(self, dt=0.01, config_path=None, gui=False, frameskip=2, horizon=120, restore_state_file=None, rotation_mode='delta-axis-angle-local', translation_mode='delta-translation', max_rotation=np.deg2rad(5), max_translation=0.15, use_suction=True, # whether to use a suction gripper object_candidate_num=6, # how many candidate objects to sample from objaverse vhacd=False, # if to perform vhacd on the object for better collision detection for pybullet randomize=0, # if to randomize the scene obj_id=0, # which object to choose to use from the candidates ): super().__init__() # Task self.config_path = config_path self.restore_state_file = restore_state_file self.frameskip = frameskip self.horizon = horizon self.gui = gui self.object_candidate_num = object_candidate_num self.solution_path = None self.success = False # not really used, keeped for now self.primitive_save_path = None # to be used for saving the primitives execution results self.randomize = randomize self.obj_id = obj_id # which object to choose to use from the candidates # physics self.gravity = -9.81 self.contact_constraint = None self.vhacd = vhacd # action space self.use_suction = use_suction self.rotation_mode = rotation_mode self.translation_mode = translation_mode self.max_rotation_angle = max_rotation self.max_translation = max_translation self.suction_to_obj_pose = 0 self.suction_contact_link = None self.suction_obj_id = None self.activated = 0 if self.gui: try: self.id = p.connect(p.GUI) except: self.id = p.connect(p.DIRECT) else: self.id = p.connect(p.DIRECT) self.asset_dir = osp.join(osp.dirname(osp.realpath(__file__)), "assets/") hz=int(1/dt) p.setTimeStep(1.0 / hz, physicsClientId=self.id) self.seed() self.set_scene() self.setup_camera_rpy() self.scene_lower, self.scene_upper = self.get_scene_bounds() self.scene_center = (self.scene_lower + self.scene_upper) / 2 self.scene_range = (self.scene_upper - self.scene_lower) / 2 self.grasp_action_mag = 0.06 if not self.use_suction else 1 self.action_low = np.array([-1, -1, -1, -1, -1, -1, -1]) self.action_high = np.array([1, 1, 1, 1, 1, 1, self.grasp_action_mag]) self.action_space = spaces.Box(low=self.action_low, high=self.action_high, dtype=np.float32) self.base_action_space = spaces.Box(low=self.action_low, high=self.action_high, dtype=np.float32) self.num_objects = len(self.urdf_ids) - 2 # exclude plane, robot distractor_object_num = np.sum(list(self.is_distractor.values())) self.num_objects -= distractor_object_num ### For RL policy learning, observation space includes: # 1. object positions and orientations (6 * num_objects) # 2. object min and max bounding box (6 * num_objects) # 3. articulated object joint angles (num_objects * num_joints) # 4. articulated object link position and orientation (num_objects * num_joints * 6) # 5. robot base position (xy) # 6. robot end-effector position and orientation (6) # 7. gripper suction activated/deactivate or gripper joint angle (if not using suction gripper) (1) num_obs = self.num_objects * 12 # obs 1 and 2 for name in self.urdf_types: if self.urdf_types[name] == 'urdf' and not self.is_distractor[name]: # obs 3 and 4 num_joints = p.getNumJoints(self.urdf_ids[name], physicsClientId=self.id) num_obs += num_joints num_obs += 6 * num_joints num_obs += 2 + 6 + 1 # obs 5 6 7 self.base_num_obs = num_obs self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(num_obs, ), dtype=np.float32) self.base_observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(self.base_num_obs, ), dtype=np.float32) self.detected_position = {} # not used for now, keep it def normalize_position(self, pos): if self.translation_mode == 'normalized-direct-translation': return (pos - self.scene_center) / self.scene_range else: return pos def seed(self, seed=None): self.np_random, _ = seeding.np_random() def get_aabb(self, id): num_joints = p.getNumJoints(id, physicsClientId=self.id) min_aabbs, max_aabbs = [], [] for link_idx in range(-1, num_joints): min_aabb, max_aabb = p.getAABB(id, link_idx, physicsClientId=self.id) min_aabbs.append(list(min_aabb)) max_aabbs.append(list(max_aabb)) min_aabb = np.min(np.concatenate(min_aabbs, axis=0).reshape(-1, 3), axis=0) max_aabb = np.max(np.concatenate(max_aabbs, axis=0).reshape(-1, 3), axis=0) return min_aabb, max_aabb def get_aabb_link(self, id, link_id): min_aabb, max_aabb = p.getAABB(id, link_id, physicsClientId=self.id) return np.array(min_aabb), np.array(max_aabb) def get_scene_bounds(self): min_aabbs = [] max_aabbs = [] for name, id in self.urdf_ids.items(): if name == 'plane': continue min_aabb, max_aabb = self.get_aabb(id) min_aabbs.append(min_aabb) max_aabbs.append(max_aabb) min_aabb = np.min(np.stack(min_aabbs, axis=0).reshape(-1, 3), axis=0) max_aabb = np.max(np.stack(max_aabbs, axis=0).reshape(-1, 3), axis=0) range = max_aabb - min_aabb return min_aabb - 0.5 * range, max_aabb + 0.5 * range def clip_within_workspace(self, robot_pos, ori_pos, on_table): pos = ori_pos.copy() if not on_table: # If objects are too close to the robot, push them away x_near_low, x_near_high = robot_pos[0] - 0.3, robot_pos[0] + 0.3 y_near_low, y_near_high = robot_pos[1] - 0.3, robot_pos[1] + 0.3 if pos[0] > x_near_low and pos[0] < x_near_high: pos[0] = x_near_low if pos[0] < robot_pos[0] else x_near_high if pos[1] > y_near_low and pos[1] < y_near_high: pos[1] = y_near_low if pos[1] < robot_pos[1] else y_near_high return pos else: # Object is on table, should be within table's bounding box new_pos = pos.copy() new_pos[:2] = np.clip(new_pos[:2], self.table_bbox_min[:2], self.table_bbox_max[:2]) return new_pos def get_robot_base_pos(self): robot_base_pos = [1, 1, 0.28] return robot_base_pos def get_robot_init_joint_angles(self): init_joint_angles = [0 for _ in range(len(self.robot.right_arm_joint_indices))] if self.robot_name == 'panda': init_joint_angles = [0, -1.10916842e-04, 7.33823451e-05, -5.47701370e-01, -5.94950533e-01, 2.62857916e+00, -4.85316284e-01, 1.96042022e+00, 2.15271531e+00, -7.35304443e-01] return init_joint_angles def set_scene( self, ): ### simulation preparation p.resetSimulation(physicsClientId=self.id) if self.gui: p.resetDebugVisualizerCamera(cameraDistance=1.75, cameraYaw=-25, cameraPitch=-45, cameraTargetPosition=[-0.2, 0, 0.4], physicsClientId=self.id) p.configureDebugVisualizer(p.COV_ENABLE_MOUSE_PICKING, 0, physicsClientId=self.id) p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0, physicsClientId=self.id) p.setRealTimeSimulation(0, physicsClientId=self.id) p.setGravity(0, 0, self.gravity, physicsClientId=self.id) ### load restore state restore_state = None if self.restore_state_file is not None: with open(self.restore_state_file, 'rb') as f: restore_state = pickle.load(f) ### load plane planeId = p.loadURDF(osp.join(self.asset_dir, "plane", "plane.urdf"), physicsClientId=self.id) ### create and load a robot robot_base_pos = self.load_robot(restore_state) ### load and parse task config (including semantically meaningful distractor objects) self.urdf_ids = { "robot": self.robot.body, "plane": planeId, } self.urdf_paths = {} self.urdf_types = {} self.init_positions = {} self.on_tables = {} self.simulator_sizes = {} self.is_distractor = { "robot": 0, "plane": 0, } urdf_paths, urdf_sizes, urdf_positions, urdf_names, urdf_types, urdf_on_table, urdf_movables, \ use_table, articulated_init_joint_angles, spatial_relationships = self.load_and_parse_config(restore_state) ### handle the case if there is a table self.load_table(use_table, restore_state) ### load each object from the task config self.load_object(urdf_paths, urdf_sizes, urdf_positions, urdf_names, urdf_types, urdf_on_table, urdf_movables) ### adjusting object positions ### place the lowest point on the object to be the height where GPT specifies object_height = self.adjust_object_positions(robot_base_pos) ### resolve collisions between objects self.resolve_collision(robot_base_pos, object_height, spatial_relationships) ### handle any special relationships outputted by GPT self.handle_gpt_special_relationships(spatial_relationships) ### set all object's joint angles to the lower joint limit self.set_to_default_joint_angles() ### overwrite joint angles specified by GPT self.handle_gpt_joint_angle(articulated_init_joint_angles) ### record initial joint angles and positions self.record_initial_joint_and_pose() ### stabilize the scene for _ in range(500): p.stepSimulation(physicsClientId=self.id) ### restore to a state if provided if self.restore_state_file is not None: load_env(self, self.restore_state_file) ### Enable debug rendering if self.gui: p.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 1, physicsClientId=self.id) self.init_state = p.saveState(physicsClientId=self.id) def load_robot(self, restore_state): robot_classes = { "panda": Panda, "sawyer": Sawyer, "ur5": UR5, } robot_names = list(robot_classes.keys()) self.robot_name = robot_names[np.random.randint(len(robot_names))] if restore_state is not None and "robot_name" in restore_state: self.robot_name = restore_state['robot_name'] self.robot_class = robot_classes[self.robot_name] # Create robot self.robot = self.robot_class() self.robot.init(self.asset_dir, self.id, self.np_random, fixed_base=True, use_suction=self.use_suction) self.agents = [self.robot] self.suction_id = self.robot.right_gripper_indices[0] # Update robot motor gains self.robot.motor_gains = 0.05 self.robot.motor_forces = 100.0 # Set robot base position & orientation, and joint angles robot_base_pos = self.get_robot_base_pos() robot_base_orient = [0, 0, 0, 1] self.robot_base_orient = robot_base_orient self.robot.set_base_pos_orient(robot_base_pos, robot_base_orient) init_joint_angles = self.get_robot_init_joint_angles() self.robot.set_joint_angles(self.robot.right_arm_joint_indices, init_joint_angles) return robot_base_pos def load_and_parse_config(self, restore_state): ### select and download objects from objaverse res = download_and_parse_objavarse_obj_from_yaml_config(self.config_path, candidate_num=self.object_candidate_num, vhacd=self.vhacd) if not res: print("=" * 20) print("some objects cannot be found in objaverse, task_build failed, now exit ...") print("=" * 20) exit() self.config = None while self.config is None: with open(self.config_path, 'r') as file: self.config = yaml.safe_load(file) for obj in self.config: if "solution_path" in obj: self.solution_path = obj["solution_path"] break ### parse config urdf_paths, urdf_sizes, urdf_positions, urdf_names, urdf_types, urdf_on_table, use_table, \ articulated_init_joint_angles, spatial_relationships, distractor_config_path, urdf_movables = parse_config(self.config, use_bard=True, obj_id=self.obj_id) if not use_table: urdf_on_table = [False for _ in urdf_on_table] urdf_names = [x.lower() for x in urdf_names] for name in urdf_names: self.is_distractor[name] = 0 ### parse distractor object config (semantically meaningful objects that are related but not used for the task) if distractor_config_path is not None: self.distractor_config_path = distractor_config_path res = download_and_parse_objavarse_obj_from_yaml_config(distractor_config_path, candidate_num=self.object_candidate_num, vhacd=self.vhacd) with open(distractor_config_path, 'r') as f: self.distractor_config = yaml.safe_load(f) distractor_urdf_paths, distractor_urdf_sizes, distractor_urdf_positions, distractor_urdf_names, distractor_urdf_types, \ distractor_urdf_on_table, _, _, _, _, _ = \ parse_config(self.distractor_config, use_bard=True, obj_id=self.obj_id, use_vhacd=False) distractor_urdf_names = [x.lower() for x in distractor_urdf_names] if not use_table: distractor_urdf_on_table = [False for _ in distractor_urdf_on_table] for name in distractor_urdf_names: self.is_distractor[name] = 1 distractor_movables = [True for _ in distractor_urdf_names] urdf_paths += distractor_urdf_paths urdf_sizes += distractor_urdf_sizes urdf_positions += distractor_urdf_positions urdf_names += distractor_urdf_names urdf_types += distractor_urdf_types urdf_on_table += distractor_urdf_on_table urdf_movables += distractor_movables if restore_state is not None: if "urdf_paths" in restore_state: self.urdf_paths = restore_state['urdf_paths'] urdf_paths = [self.urdf_paths[name] for name in urdf_names] if "object_sizes" in restore_state: self.simulator_sizes = restore_state['object_sizes'] urdf_sizes = [self.simulator_sizes[name] for name in urdf_names] return urdf_paths, urdf_sizes, urdf_positions, urdf_names, urdf_types, urdf_on_table, urdf_movables, \ use_table, articulated_init_joint_angles, spatial_relationships def load_table(self, use_table, restore_state): self.use_table = use_table if use_table: self.table_path = table_paths[np.random.randint(len(table_paths))] if restore_state is not None: self.table_path = restore_state['table_path'] table_scale = table_scales[self.table_path] table_pos = table_poses[self.table_path] table_orientation = [np.pi/2, 0, 0] self.table = p.loadURDF(osp.join(self.asset_dir, self.table_path, "material.urdf"), physicsClientId=self.id, useFixedBase=True, globalScaling=table_scale) if not self.randomize: random_orientation = p.getQuaternionFromEuler(table_orientation, physicsClientId=self.id) else: random_orientations = [0, np.pi / 2, np.pi, np.pi * 3 / 2] random_orientation = p.getQuaternionFromEuler([np.pi/2, 0, random_orientations[np.random.randint(4)]], physicsClientId=self.id) p.resetBasePositionAndOrientation(self.table, table_pos, random_orientation, physicsClientId=self.id) self.table_bbox_min, self.table_bbox_max = self.get_aabb(self.table) table_range = self.table_bbox_max - self.table_bbox_min self.table_bbox_min[:2] += table_range[:2] * table_bbox_scale_down_factors[self.table_path] self.table_bbox_max[:2] -= table_range[:2] * table_bbox_scale_down_factors[self.table_path] self.table_height = self.table_bbox_max[2] p.addUserDebugLine([*self.table_bbox_min[:2], self.table_height], self.table_bbox_max, [1, 0, 0], lineWidth=10, lifeTime=0, physicsClientId=self.id) self.simulator_sizes["init_table"] = table_scale self.urdf_ids["init_table"] = self.table self.is_distractor['init_table'] = 0 def load_object(self, urdf_paths, urdf_sizes, urdf_positions, urdf_names, urdf_types, urdf_on_table, urdf_movables): for path, size, pos, name, type, on_table, moveable in zip(urdf_paths, urdf_sizes, urdf_positions, urdf_names, urdf_types, urdf_on_table, urdf_movables): name = name.lower() # by default, all objects movable, except the urdf files use_fixed_base = (type == 'urdf' and not self.is_distractor[name]) if type == 'urdf' and moveable: # if gpt specified the object is movable, then it is movable use_fixed_base = False size = min(size, 1.2) size = max(size, 0.1) # if the object is too small, current gripper cannot really manipulate it. x_orient = np.pi/2 if type == 'mesh' else 0 # handle different coordinate axis by objaverse and partnet-mobility if self.randomize or self.is_distractor[name]: orientation = p.getQuaternionFromEuler([x_orient, 0, self.np_random.uniform(-np.pi/3, np.pi/3)], physicsClientId=self.id) else: orientation = p.getQuaternionFromEuler([x_orient, 0, 0], physicsClientId=self.id) if not on_table: load_pos = pos else: # change to be table coordinate table_xy_range = self.table_bbox_max[:2] - self.table_bbox_min[:2] obj_x = self.table_bbox_min[0] + pos[0] * table_xy_range[0] obj_y = self.table_bbox_min[1] + pos[1] * table_xy_range[1] obj_z = self.table_height load_pos = [obj_x, obj_y, obj_z] id = p.loadURDF(path, basePosition=load_pos, baseOrientation=orientation, physicsClientId=self.id, useFixedBase=use_fixed_base, globalScaling=size) # scale size if name in self.simulator_sizes: p.removeBody(id, physicsClientId=self.id) saved_size = self.simulator_sizes[name] id = p.loadURDF(path, basePosition=load_pos, baseOrientation=orientation, physicsClientId=self.id, useFixedBase=use_fixed_base, globalScaling=saved_size) else: min_aabb, max_aabb = self.get_aabb(id) actual_size = np.linalg.norm(max_aabb - min_aabb) if np.abs(actual_size - size) > 0.05: p.removeBody(id, physicsClientId=self.id) id = p.loadURDF(path, basePosition=load_pos, baseOrientation=orientation, physicsClientId=self.id, useFixedBase=use_fixed_base, globalScaling=size ** 2 / actual_size) self.simulator_sizes[name] = size ** 2 / actual_size else: self.simulator_sizes[name] = size self.urdf_ids[name] = id self.urdf_paths[name] = path self.urdf_types[name] = type self.init_positions[name] = np.array(load_pos) self.on_tables[name] = on_table print("Finished loading object: ", name) def adjust_object_positions(self, robot_base_pos): object_height = {} for name, id in self.urdf_ids.items(): if name == 'robot' or name == 'plane' or name == 'init_table': continue min_aabb, max_aabb = self.get_aabb(id) min_z = min_aabb[2] object_height[id] = 2 * self.init_positions[name][2] - min_z pos, orient = p.getBasePositionAndOrientation(id, physicsClientId=self.id) new_pos = np.array(pos) new_pos = self.clip_within_workspace(robot_base_pos, new_pos, self.on_tables[name]) new_pos[2] = object_height[id] p.resetBasePositionAndOrientation(id, new_pos, orient, physicsClientId=self.id) self.init_positions[name] = new_pos return object_height def resolve_collision(self, robot_base_pos, object_height, spatial_relationships): collision = True collision_cnt = 1 while collision: if collision_cnt % 50 == 0: # if collision is not resolved every 50 iterations, we randomly reset object's position for name, id in self.urdf_ids.items(): if name == 'robot' or name == 'plane' or name == "init_table": continue pos = self.init_positions[name] _, orient = p.getBasePositionAndOrientation(id, physicsClientId=self.id) new_pos = np.array(pos) + np.random.uniform(-0.2, 0.2, size=3) new_pos = self.clip_within_workspace(robot_base_pos, new_pos, self.on_tables[name]) new_pos[2] = object_height[id] p.resetBasePositionAndOrientation(id, new_pos, orient, physicsClientId=self.id) p.stepSimulation(physicsClientId=self.id) push_directions = defaultdict(list) # store the push direction for each object # detect collisions between objects detected_collision = False for name, id in self.urdf_ids.items(): if name == 'robot' or name == 'plane' or name == 'init_table': continue for name2, id2 in self.urdf_ids.items(): if name == name2 or name2 == 'robot' or name2 == 'plane' or name2 == 'init_table': continue # if gpt specifies obj a and obj b should have some special relationship, then skip collision resolution skip = False for spatial_relationship in spatial_relationships: words = spatial_relationship.lower().split(",") words = [word.strip().lstrip() for word in words] if name in words and name2 in words: skip = True break if skip: continue contact_points = p.getClosestPoints(id, id2, 0.01, physicsClientId=self.id) if len(contact_points) > 0: contact_point = contact_points[0] push_direction = contact_point[7] push_direction = np.array([push_direction[0], push_direction[1], push_direction[2]]) # both are distractors or both are not, push both objects away if (self.is_distractor[name] and self.is_distractor[name2]) or \ (not self.is_distractor[name] and not self.is_distractor[name2]): push_directions[id].append(-push_direction) push_directions[id2].append(push_direction) # only 1 is distractor, only pushes the distractor if self.is_distractor[name] and not self.is_distractor[name2]: push_directions[id].append(push_direction) if not self.is_distractor[name] and self.is_distractor[name2]: push_directions[id2].append(-push_direction) detected_collision = True # collisions between robot and objects, only push object away for name, id in self.urdf_ids.items(): if name == 'robot' or name == 'plane' or name == 'init_table': continue contact_points = p.getClosestPoints(self.robot.body, id, 0.05, physicsClientId=self.id) if len(contact_points) > 0: contact_point = contact_points[0] push_direction = contact_point[7] push_direction = np.array([push_direction[0], push_direction[1], push_direction[2]]) push_directions[id].append(-push_direction) detected_collision = True # between table and objects that should not be placed on table if self.use_table: for name, id in self.urdf_ids.items(): if name == 'robot' or name == 'plane' or name == 'init_table': continue if self.on_tables[name]: continue contact_points = p.getClosestPoints(self.robot.body, id, 0.05, physicsClientId=self.id) if len(contact_points) > 0: contact_point = contact_points[0] push_direction = contact_point[7] push_direction = np.array([push_direction[0], push_direction[1], push_direction[2]]) push_directions[id].append(-push_direction) detected_collision = True # move objects push_distance = 0.1 for id in push_directions: for direction in push_directions[id]: pos, orient = p.getBasePositionAndOrientation(id, physicsClientId=self.id) new_pos = np.array(pos) + push_distance * direction new_pos = self.clip_within_workspace(robot_base_pos, new_pos, self.on_tables[name]) new_pos[2] = object_height[id] p.resetBasePositionAndOrientation(id, new_pos, orient, physicsClientId=self.id) p.stepSimulation(physicsClientId=self.id) collision = detected_collision collision_cnt += 1 if collision_cnt > 1000: break def record_initial_joint_and_pose(self): self.initial_joint_angle = {} for name in self.urdf_ids: obj_id = self.urdf_ids[name.lower()] if name == 'robot' or name == 'plane' or name == "init_table": continue if self.urdf_types[name.lower()] == 'urdf': self.initial_joint_angle[name] = {} num_joints = p.getNumJoints(obj_id, physicsClientId=self.id) for joint_idx in range(num_joints): joint_name = p.getJointInfo(obj_id, joint_idx, physicsClientId=self.id)[1].decode("utf-8") joint_angle = p.getJointState(obj_id, joint_idx, physicsClientId=self.id)[0] self.initial_joint_angle[name][joint_name] = joint_angle self.initial_pos = {} self.initial_orient = {} for name in self.urdf_ids: obj_id = self.urdf_ids[name.lower()] if name == 'robot' or name == 'plane' or name == "init_table": continue pos, orient = p.getBasePositionAndOrientation(obj_id, physicsClientId=self.id) self.initial_pos[name] = pos self.initial_orient[name] = orient def set_to_default_joint_angles(self): for obj_name in self.urdf_ids: if obj_name == 'robot' or obj_name == 'plane' or obj_name == "init_table": continue obj_id = self.urdf_ids[obj_name] num_joints = p.getNumJoints(obj_id, physicsClientId=self.id) for joint_idx in range(num_joints): joint_limit_low, joint_limit_high = p.getJointInfo(obj_id, joint_idx, physicsClientId=self.id)[8:10] if joint_limit_low > joint_limit_high: joint_limit_low, joint_limit_high = joint_limit_high, joint_limit_low joint_val = joint_limit_low + 0.06 * (joint_limit_high - joint_limit_low) p.resetJointState(obj_id, joint_idx, joint_val, physicsClientId=self.id) def handle_gpt_special_relationships(self, spatial_relationships): # we support "on" and "in" for now, but this can be extended to more relationships for spatial_relationship in spatial_relationships: words = spatial_relationship.lower().split(",") words = [word.strip().lstrip() for word in words] if words[0] == "on": obj_a = words[1] obj_b = words[2] if len(words) == 4: obj_b_link = words[3]
obj_b_link_id = get_link_id_from_name(self, obj_b, obj_b_link)
7
2023-10-31 19:44:09+00:00
12k
KoeAI/LLVC
minimal_rvc/model.py
[ { "identifier": "SynthesizerTrnMs256NSFSid", "path": "minimal_rvc/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_h...
import os import re import torch from typing import * from fairseq import checkpoint_utils from fairseq.models.hubert.hubert import HubertModel from pydub import AudioSegment from .models import (SynthesizerTrnMs256NSFSid, SynthesizerTrnMs256NSFSidNono) from .pipeline import VocalConvertPipeline from .cmd_opts import opts from .shared import ROOT_DIR, device, is_half from .utils import load_audio
7,758
# This module is based on code from ddPn08, liujing04, and teftef6220 # https://github.com/ddPn08/rvc-webui # https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI # https://github.com/teftef6220/Voice_Separation_and_Selection # These modules are licensed under the MIT License. AUDIO_OUT_DIR = opts.output_dir or os.path.join(ROOT_DIR, "outputs") EMBEDDINGS_LIST = { "hubert-base-japanese": ( "rinna_hubert_base_jp.pt", "hubert-base-japanese", "local", ), "contentvec": ("checkpoint_best_legacy_500.pt", "contentvec", "local"), } def update_state_dict(state_dict): if "params" in state_dict and state_dict["params"] is not None: return keys = [ "spec_channels", "segment_size", "inter_channels", "hidden_channels", "filter_channels", "n_heads", "n_layers", "kernel_size", "p_dropout", "resblock", "resblock_kernel_sizes", "resblock_dilation_sizes", "upsample_rates", "upsample_initial_channel", "upsample_kernel_sizes", "spk_embed_dim", "gin_channels", "emb_channels", "sr", ] state_dict["params"] = {} n = 0 for i, key in enumerate(keys): i = i - n if len(state_dict["config"]) != 19 and key == "emb_channels": # backward compat. n += 1 continue state_dict["params"][key] = state_dict["config"][i] if not "emb_channels" in state_dict["params"]: if state_dict.get("version", "v1") == "v1": state_dict["params"]["emb_channels"] = 256 # for backward compat. state_dict["embedder_output_layer"] = 9 else: state_dict["params"]["emb_channels"] = 768 # for backward compat. state_dict["embedder_output_layer"] = 12 class VoiceConvertModel: def __init__(self, model_name: str, state_dict: Dict[str, Any]) -> None: update_state_dict(state_dict) self.model_name = model_name self.state_dict = state_dict self.tgt_sr = state_dict["params"]["sr"] f0 = state_dict.get("f0", 1) state_dict["params"]["spk_embed_dim"] = state_dict["weight"][ "emb_g.weight" ].shape[0] if not "emb_channels" in state_dict["params"]: state_dict["params"]["emb_channels"] = 768 # for backward compat. if f0 == 1:
# This module is based on code from ddPn08, liujing04, and teftef6220 # https://github.com/ddPn08/rvc-webui # https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI # https://github.com/teftef6220/Voice_Separation_and_Selection # These modules are licensed under the MIT License. AUDIO_OUT_DIR = opts.output_dir or os.path.join(ROOT_DIR, "outputs") EMBEDDINGS_LIST = { "hubert-base-japanese": ( "rinna_hubert_base_jp.pt", "hubert-base-japanese", "local", ), "contentvec": ("checkpoint_best_legacy_500.pt", "contentvec", "local"), } def update_state_dict(state_dict): if "params" in state_dict and state_dict["params"] is not None: return keys = [ "spec_channels", "segment_size", "inter_channels", "hidden_channels", "filter_channels", "n_heads", "n_layers", "kernel_size", "p_dropout", "resblock", "resblock_kernel_sizes", "resblock_dilation_sizes", "upsample_rates", "upsample_initial_channel", "upsample_kernel_sizes", "spk_embed_dim", "gin_channels", "emb_channels", "sr", ] state_dict["params"] = {} n = 0 for i, key in enumerate(keys): i = i - n if len(state_dict["config"]) != 19 and key == "emb_channels": # backward compat. n += 1 continue state_dict["params"][key] = state_dict["config"][i] if not "emb_channels" in state_dict["params"]: if state_dict.get("version", "v1") == "v1": state_dict["params"]["emb_channels"] = 256 # for backward compat. state_dict["embedder_output_layer"] = 9 else: state_dict["params"]["emb_channels"] = 768 # for backward compat. state_dict["embedder_output_layer"] = 12 class VoiceConvertModel: def __init__(self, model_name: str, state_dict: Dict[str, Any]) -> None: update_state_dict(state_dict) self.model_name = model_name self.state_dict = state_dict self.tgt_sr = state_dict["params"]["sr"] f0 = state_dict.get("f0", 1) state_dict["params"]["spk_embed_dim"] = state_dict["weight"][ "emb_g.weight" ].shape[0] if not "emb_channels" in state_dict["params"]: state_dict["params"]["emb_channels"] = 768 # for backward compat. if f0 == 1:
self.net_g = SynthesizerTrnMs256NSFSid(
0
2023-10-28 01:58:49+00:00
12k
baaivision/JudgeLM
judgelm/model/model_adapter.py
[ { "identifier": "GptqConfig", "path": "judgelm/modules/gptq.py", "snippet": "class GptqConfig:\n ckpt: str = field(\n default=None,\n metadata={\n \"help\": \"Load quantized model. The path to the local GPTQ checkpoint.\"\n },\n )\n wbits: int = field(default=16,...
import math import os import sys import warnings import accelerate import psutil import torch import intel_extension_for_pytorch as ipex from typing import Dict, List, Optional from functools import cache from functools import lru_cache as cache from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer, LlamaTokenizer, LlamaForCausalLM, T5Tokenizer, ) from judgelm.modules.gptq import GptqConfig, load_gptq_quantized from judgelm.conversation import Conversation, get_conv_template from judgelm.model.compression import load_compress_model from judgelm.model.model_chatglm import generate_stream_chatglm from judgelm.model.model_codet5p import generate_stream_codet5p from judgelm.model.model_falcon import generate_stream_falcon from judgelm.model.monkey_patch_non_inplace import ( replace_llama_attn_with_non_inplace_operations, ) from judgelm.utils import get_gpu_memory from transformers import BitsAndBytesConfig from judgelm.serve.inference import generate_stream from peft import PeftConfig, PeftModel from peft import PeftConfig, PeftModel from fastchat.model.llama_condense_monkey_patch import ( replace_llama_with_condense, ) from fastchat.model.rwkv_model import RwkvModel
7,687
model = AutoModelForCausalLM.from_pretrained( model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs ) except NameError: model = AutoModel.from_pretrained( model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs ) return model, tokenizer def load_compress_model(self, model_path, device, torch_dtype, revision="main"): return load_compress_model( model_path, device, torch_dtype, use_fast=self.use_fast_tokenizer, revision=revision, ) def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("one_shot") # A global registry for all model adapters # TODO (lmzheng): make it a priority queue. model_adapters: List[BaseModelAdapter] = [] def register_model_adapter(cls): """Register a model adapter.""" model_adapters.append(cls()) @cache def get_model_adapter(model_path: str) -> BaseModelAdapter: """Get a model adapter for a model_path.""" model_path_basename = os.path.basename(os.path.normpath(model_path)) # Try the basename of model_path at first for adapter in model_adapters: if adapter.match(model_path_basename) and type(adapter) != BaseModelAdapter: return adapter # Then try the full path for adapter in model_adapters: if adapter.match(model_path): return adapter raise ValueError(f"No valid model adapter for {model_path}") def raise_warning_for_incompatible_cpu_offloading_configuration( device: str, load_8bit: bool, cpu_offloading: bool ): if cpu_offloading: if not load_8bit: warnings.warn( "The cpu-offloading feature can only be used while also using 8-bit-quantization.\n" "Use '--load-8bit' to enable 8-bit-quantization\n" "Continuing without cpu-offloading enabled\n" ) return False if not "linux" in sys.platform: warnings.warn( "CPU-offloading is only supported on linux-systems due to the limited compatability with the bitsandbytes-package\n" "Continuing without cpu-offloading enabled\n" ) return False if device != "cuda": warnings.warn( "CPU-offloading is only enabled when using CUDA-devices\n" "Continuing without cpu-offloading enabled\n" ) return False return cpu_offloading def load_model( model_path: str, device: str, num_gpus: int, max_gpu_memory: Optional[str] = None, load_8bit: bool = False, cpu_offloading: bool = False, gptq_config: Optional[GptqConfig] = None, revision: str = "main", debug: bool = False, ): """Load a model from Hugging Face.""" # get model adapter adapter = get_model_adapter(model_path) # Handle device mapping cpu_offloading = raise_warning_for_incompatible_cpu_offloading_configuration( device, load_8bit, cpu_offloading ) if device == "cpu": kwargs = {"torch_dtype": torch.float32} elif device == "cuda": kwargs = {"torch_dtype": torch.float16} if num_gpus != 1: kwargs["device_map"] = "auto" if max_gpu_memory is None: kwargs[ "device_map" ] = "sequential" # This is important for not the same VRAM sizes available_gpu_memory = get_gpu_memory(num_gpus) kwargs["max_memory"] = { i: str(int(available_gpu_memory[i] * 0.99)) + "GiB" # change it to 0.93 to avoid OOM for i in range(num_gpus) } # 将 key 为 1 时的 max_memory 设置为 0.93 倍 available_gpu_memory kwargs["max_memory"][0] = str(int(available_gpu_memory[0] * 0.72)) + "GiB" # print content of kwargs["max_memory"] print("kwargs['max_memory'] = ", kwargs["max_memory"]) else: kwargs["max_memory"] = {i: max_gpu_memory for i in range(num_gpus)} elif device == "mps": kwargs = {"torch_dtype": torch.float16} # Avoid bugs in mps backend by not using in-place operations.
"""Model adapter registration.""" if sys.version_info >= (3, 9): else: # Check an environment variable to check if we should be sharing Peft model # weights. When false we treat all Peft models as separate. peft_share_base_weights = ( os.environ.get("PEFT_SHARE_BASE_WEIGHTS", "false").lower() == "true" ) class BaseModelAdapter: """The base and the default model adapter.""" use_fast_tokenizer = True def match(self, model_path: str): return True def load_model(self, model_path: str, from_pretrained_kwargs: dict): revision = from_pretrained_kwargs.get("revision", "main") try: tokenizer = AutoTokenizer.from_pretrained( model_path, use_fast=self.use_fast_tokenizer, revision=revision, ) except TypeError: tokenizer = AutoTokenizer.from_pretrained( model_path, use_fast=False, revision=revision, ) try: model = AutoModelForCausalLM.from_pretrained( model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs ) except NameError: model = AutoModel.from_pretrained( model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs ) return model, tokenizer def load_compress_model(self, model_path, device, torch_dtype, revision="main"): return load_compress_model( model_path, device, torch_dtype, use_fast=self.use_fast_tokenizer, revision=revision, ) def get_default_conv_template(self, model_path: str) -> Conversation: return get_conv_template("one_shot") # A global registry for all model adapters # TODO (lmzheng): make it a priority queue. model_adapters: List[BaseModelAdapter] = [] def register_model_adapter(cls): """Register a model adapter.""" model_adapters.append(cls()) @cache def get_model_adapter(model_path: str) -> BaseModelAdapter: """Get a model adapter for a model_path.""" model_path_basename = os.path.basename(os.path.normpath(model_path)) # Try the basename of model_path at first for adapter in model_adapters: if adapter.match(model_path_basename) and type(adapter) != BaseModelAdapter: return adapter # Then try the full path for adapter in model_adapters: if adapter.match(model_path): return adapter raise ValueError(f"No valid model adapter for {model_path}") def raise_warning_for_incompatible_cpu_offloading_configuration( device: str, load_8bit: bool, cpu_offloading: bool ): if cpu_offloading: if not load_8bit: warnings.warn( "The cpu-offloading feature can only be used while also using 8-bit-quantization.\n" "Use '--load-8bit' to enable 8-bit-quantization\n" "Continuing without cpu-offloading enabled\n" ) return False if not "linux" in sys.platform: warnings.warn( "CPU-offloading is only supported on linux-systems due to the limited compatability with the bitsandbytes-package\n" "Continuing without cpu-offloading enabled\n" ) return False if device != "cuda": warnings.warn( "CPU-offloading is only enabled when using CUDA-devices\n" "Continuing without cpu-offloading enabled\n" ) return False return cpu_offloading def load_model( model_path: str, device: str, num_gpus: int, max_gpu_memory: Optional[str] = None, load_8bit: bool = False, cpu_offloading: bool = False, gptq_config: Optional[GptqConfig] = None, revision: str = "main", debug: bool = False, ): """Load a model from Hugging Face.""" # get model adapter adapter = get_model_adapter(model_path) # Handle device mapping cpu_offloading = raise_warning_for_incompatible_cpu_offloading_configuration( device, load_8bit, cpu_offloading ) if device == "cpu": kwargs = {"torch_dtype": torch.float32} elif device == "cuda": kwargs = {"torch_dtype": torch.float16} if num_gpus != 1: kwargs["device_map"] = "auto" if max_gpu_memory is None: kwargs[ "device_map" ] = "sequential" # This is important for not the same VRAM sizes available_gpu_memory = get_gpu_memory(num_gpus) kwargs["max_memory"] = { i: str(int(available_gpu_memory[i] * 0.99)) + "GiB" # change it to 0.93 to avoid OOM for i in range(num_gpus) } # 将 key 为 1 时的 max_memory 设置为 0.93 倍 available_gpu_memory kwargs["max_memory"][0] = str(int(available_gpu_memory[0] * 0.72)) + "GiB" # print content of kwargs["max_memory"] print("kwargs['max_memory'] = ", kwargs["max_memory"]) else: kwargs["max_memory"] = {i: max_gpu_memory for i in range(num_gpus)} elif device == "mps": kwargs = {"torch_dtype": torch.float16} # Avoid bugs in mps backend by not using in-place operations.
replace_llama_attn_with_non_inplace_operations()
8
2023-10-26 19:41:07+00:00
12k