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
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
12,914
self.project_name, self.baseline_name, self.experiment_name, f"{self.project_name}_{self.baseline_name}_{self.experiment_name}.bin", ) request_trt_benchmark(benchmark_key, bin_path) log.info("TensorRT engine execution and benchmark successfully requested") poll_run_benchmark(self.project_id, benchmark_key) exp_info = get_run_info(self.project_id, self.baseline_name, self.experiment_name) assert exp_info is not None if self.is_baseline: log.info( "Latency\n" f"\t\tBaseline - {exp_info['latency']} on {exp_info['device_name']}\n" "\t\tConfigure the quantization settings located at " f"{OWLITE_FRONT_BASE_URL}/project/detail/{self.project_id}" ) else: log.info( "Latency\n" f"\t\tConfigured - {exp_info['latency']} on {exp_info['device_name']}\n" "\t\tRetrieve the specifics of the experiment at " f"{OWLITE_FRONT_BASE_URL}/project/detail/{self.project_id}" ) engine_path = os.path.join( OWLITE_REPO_PATH, self.project_name, self.baseline_name, self.experiment_name, f"{self.project_name}_{self.baseline_name}_{self.experiment_name}.engine", ) download_trt_engine(benchmark_key, engine_path) def log(self, **kwargs) -> None: """Logs the model's metrics. Notes: Log metrics with OwLite like below ... owl = owlite.init(...) ... owl.log(accuracy=0.72, loss=1.2) Raises: TypeError: When data is not JSON serializable. """ try: logs = json.dumps(kwargs) except TypeError as e: log.error("Data is not JSON serializable") raise e update_run_info(self.project_id, self.baseline_name, self.experiment_name, logs) # pylint: disable-next=too-many-branches def init( project: str, baseline: str, experiment: Optional[str] = None, duplicate_from: Optional[str] = None, description: str = "", onnx_export_options: Optional[ONNXExportOptions] = None, ) -> OwLite: """Sets project, baseline and experiment information in DB to proper state and creates `OwLite` instance. Args: project (str): OwLite project name. baseline (str): OwLite baseline name. experiment (str, optional): OwLite experiment name. Defaults to None. duplicate_from (str, optional): OwLite source experiment name. Defaults to None. description (str, optional): OwLite project description. Defaults to "". onnx_export_options (ONNXExportOptions, optional): Options for ONNX export. Defaults to None. Raises: RuntimeError: When not authenticated. ValueError: When invalid experiment name or baseline name is given. Returns: OwLite: Created `OwLite` instance. """ if OWLITE_SETTINGS.tokens is None: log.error("Please log in using 'owlite login'. Account not found on this device") raise RuntimeError("OwLite token not found") if OWLITE_DEVICE_NAME is None: log.warning("Connected device not found. Please connect device by 'owlite device connect --name (name)'") else: log.info(f"Connected device: {OWLITE_DEVICE_NAME}") if experiment == baseline: log.error(f"Experiment name '{baseline}' is reserved for baseline. Please try with a different experiment name") raise ValueError("Invalid experiment name") dir_path = os.path.join( OWLITE_REPO_PATH, project, baseline, experiment or baseline, ) if os.path.exists(dir_path): log.warning(f"Existing local directory found at {dir_path}. Continuing this code will overwrite the data") else: os.makedirs(dir_path, exist_ok=True) log.info(f"Experiment data will be saved in {dir_path}") # create or load project project_id = create_or_load_project(project, description) if experiment is None: if duplicate_from: log.warning(f"duplicate_from='{duplicate_from}' will be ignored as no value for experiment was provided")
# 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 module_args: Optional[tuple[Any, ...]] = None module_kwargs: Optional[dict[str, Any]] = None @property def is_baseline(self) -> bool: # pylint: disable=missing-function-docstring return self.baseline_name == self.experiment_name def convert(self, model: torch.nn.Module, *args, **kwargs) -> GraphModule: """Converts input model to compressed model. Args: model (torch.nn.Module): Model to compress. Returns: GraphModule: Compressed graph module. Raises: HTTPError: When request for compression configuration was not successful. """ log.info("Model conversion initiated") try: model = symbolic_trace(model, *args, **kwargs) except Exception as e: # pylint: disable=broad-exception-caught log.error( "Failed to extract the computation graph from the provided model. " "Please check the error message for details.\n" "If the issue persists, try replacing with a traceable node. " "In case the problem remain unresolved, kindly report it at " f"{OWLITE_REPORT_URL} for further assistance" ) raise e self.module_args = args self.module_kwargs = kwargs if self.is_baseline: onnx_path = os.path.join( OWLITE_REPO_PATH, self.project_name, self.baseline_name, self.experiment_name, f"{self.project_name}_{self.baseline_name}_{self.experiment_name}.onnx", ) export( model, (*self.module_args, self.module_kwargs), onnx_path, **asdict(self.onnx_export_options), ) log.info("Baseline ONNX saved") upload_baseline(self.project_id, self.baseline_name, onnx_path, model) log.info("Uploaded the model excluding parameters") else: exp_info = get_run_info(self.project_id, self.baseline_name, self.experiment_name) assert exp_info is not None if not exp_info["config_id"]: log.warning("No compression configuration found, skipping the compression process") else: log.info(f"Compression configuration found for '{self.experiment_name}'") configuration_string = get_configuration(self.project_id, self.baseline_name, self.experiment_name) options = GraphQuantizationOptions.load(configuration_string) log.info("Applying compression configuration") model = quantize(model, options) log.info("Converted the model") return model def benchmark( self, model: GraphModule, dynamic_axes: Optional[dict[str, dict[int, dict[str, int]]]] = None, ) -> None: """Benchmarks given model. Args: model (GraphModule): Model to benchmark. dynamic_axes (Optional[dict[str, dict[int, dict[str, int]]]]): By default the exported model will have the shapes of all input tensors set to exactly match those given when calling convert. To specify axes of tensors as dynamic (i.e. known only at run-time), set `dynamic_axes` to a dict with schema: * KEY (str): an input name. * VALUE (dict[int, dict[str, int]]): a single item dictionary whose key is dynamic dimension of input and value is a dynamic range setting dictionary containing min, opt, max, test dimension size settings. For example:: import owlite owl = owlite.init( ... ) class SumModule(torch.nn.Module): def forward(self, x): return torch.sum(x, dim=1) model = owl.convert( ... ) ... # set first(0-th) dimension of input x to be dynamic within the range of 1 ~ 8 # optimize for 4 and benchmark for 5 owl.benchmark(model, dynamic_axes={ "x": { 0: { "min": 1, "opt": 4, "max": 8, "test": 5, } } }) Raises: TypeError: When the `model` is an instance of `torch.nn.DataParallel` or `torch.nn.DistributedDataParallel`. RuntimeError: When `dynamic_axes` is set for baseline benchmark. ValueError: When invalid `dynamic_axes` is given. """ if isinstance(model, (DataParallel, DistributedDataParallel)): _model_type = f"torch.nn.parallel.{type(model).__name__}" log.error( f"{_model_type} is not supported by benchmark, please use attribute module " f"to unwrap model from {_model_type}. Try owlite.benchmark(model.module)" ) raise TypeError(f"{_model_type} is not supported by benchmark") if self.is_baseline: log.info( f"Benchmark initiated. '{self.baseline_name}' " "ONNX will be uploaded to the connected device for TensorRT execution and benchmark" ) if dynamic_axes is not None: log.error( "Baseline cannot be done with dynamic input. To benchmark baseline model with dynamic input, " "please create a run without compression configuration and benchmark that run with dynamic input" ) raise RuntimeError("Attempted dynamic baseline benchmark") else: log.info( f"Benchmark initiated. '{self.experiment_name}' " "ONNX will be created and uploaded to the connected device for TensorRT execution and benchmark" ) dynamic_dimensions = None if dynamic_axes is not None: sep = "', '" log.info(f"dynamic_axes setting for following inputs are provided. '{sep.join(dynamic_axes.keys())}'") input_signature = get_input_shape_signature( model, *(self.module_args or ()), **(self.module_kwargs or {}) ) dynamic_dimensions = configure_dynamic_dimensions(input_signature, dynamic_axes) onnx_path = os.path.join( OWLITE_REPO_PATH, self.project_name, self.baseline_name, self.experiment_name, f"{self.project_name}_{self.baseline_name}_{self.experiment_name}.onnx", ) export( model, (*(self.module_args or ()), self.module_kwargs), onnx_path, **asdict(self.onnx_export_options), dynamic_dimensions=dynamic_dimensions, ) log.info("Experiment ONNX saved") upload_run_onnx_proto(self.project_id, self.baseline_name, self.experiment_name, onnx_path, dynamic_axes) log.info("Uploaded the model excluding parameters") benchmark_key = get_benchmark_key(self.project_id, self.baseline_name, self.experiment_name) bin_path = os.path.join( OWLITE_REPO_PATH, self.project_name, self.baseline_name, self.experiment_name, f"{self.project_name}_{self.baseline_name}_{self.experiment_name}.bin", ) request_trt_benchmark(benchmark_key, bin_path) log.info("TensorRT engine execution and benchmark successfully requested") poll_run_benchmark(self.project_id, benchmark_key) exp_info = get_run_info(self.project_id, self.baseline_name, self.experiment_name) assert exp_info is not None if self.is_baseline: log.info( "Latency\n" f"\t\tBaseline - {exp_info['latency']} on {exp_info['device_name']}\n" "\t\tConfigure the quantization settings located at " f"{OWLITE_FRONT_BASE_URL}/project/detail/{self.project_id}" ) else: log.info( "Latency\n" f"\t\tConfigured - {exp_info['latency']} on {exp_info['device_name']}\n" "\t\tRetrieve the specifics of the experiment at " f"{OWLITE_FRONT_BASE_URL}/project/detail/{self.project_id}" ) engine_path = os.path.join( OWLITE_REPO_PATH, self.project_name, self.baseline_name, self.experiment_name, f"{self.project_name}_{self.baseline_name}_{self.experiment_name}.engine", ) download_trt_engine(benchmark_key, engine_path) def log(self, **kwargs) -> None: """Logs the model's metrics. Notes: Log metrics with OwLite like below ... owl = owlite.init(...) ... owl.log(accuracy=0.72, loss=1.2) Raises: TypeError: When data is not JSON serializable. """ try: logs = json.dumps(kwargs) except TypeError as e: log.error("Data is not JSON serializable") raise e update_run_info(self.project_id, self.baseline_name, self.experiment_name, logs) # pylint: disable-next=too-many-branches def init( project: str, baseline: str, experiment: Optional[str] = None, duplicate_from: Optional[str] = None, description: str = "", onnx_export_options: Optional[ONNXExportOptions] = None, ) -> OwLite: """Sets project, baseline and experiment information in DB to proper state and creates `OwLite` instance. Args: project (str): OwLite project name. baseline (str): OwLite baseline name. experiment (str, optional): OwLite experiment name. Defaults to None. duplicate_from (str, optional): OwLite source experiment name. Defaults to None. description (str, optional): OwLite project description. Defaults to "". onnx_export_options (ONNXExportOptions, optional): Options for ONNX export. Defaults to None. Raises: RuntimeError: When not authenticated. ValueError: When invalid experiment name or baseline name is given. Returns: OwLite: Created `OwLite` instance. """ if OWLITE_SETTINGS.tokens is None: log.error("Please log in using 'owlite login'. Account not found on this device") raise RuntimeError("OwLite token not found") if OWLITE_DEVICE_NAME is None: log.warning("Connected device not found. Please connect device by 'owlite device connect --name (name)'") else: log.info(f"Connected device: {OWLITE_DEVICE_NAME}") if experiment == baseline: log.error(f"Experiment name '{baseline}' is reserved for baseline. Please try with a different experiment name") raise ValueError("Invalid experiment name") dir_path = os.path.join( OWLITE_REPO_PATH, project, baseline, experiment or baseline, ) if os.path.exists(dir_path): log.warning(f"Existing local directory found at {dir_path}. Continuing this code will overwrite the data") else: os.makedirs(dir_path, exist_ok=True) log.info(f"Experiment data will be saved in {dir_path}") # create or load project project_id = create_or_load_project(project, description) if experiment is None: if duplicate_from: log.warning(f"duplicate_from='{duplicate_from}' will be ignored as no value for experiment was provided")
created_baseline = create_baseline(project_id, baseline)
11
2023-12-08 06:41:50+00:00
16k
qitan/devops-backend-lite
apps/deploy/ext_func.py
[ { "identifier": "convert_xml_to_str_with_pipeline", "path": "common/custom_format.py", "snippet": "def convert_xml_to_str_with_pipeline(xml, url, secret, desc, jenkinsfile, scm=True):\n \"\"\"\n scm\n True: jenkinsfile为指定的git地址\n False: jenkinsfile为具体的pipeline\n \"\"\"\n xml_dict = xml...
import base64 import datetime import os import time import logging from django.core.cache import cache from django.db.models import Q from django.db import transaction from django_q.tasks import async_task, schedule from django_q.models import Schedule from common.custom_format import convert_xml_to_str_with_pipeline from common.utils.AesCipher import AesCipher from common.variables import CI_LATEST_KEY from deploy.documents import BuildJobDocument, DeployJobDocument from deploy.serializers import BuildJobListSerializer, DeployJobSerializer from deploy.rds_transfer import rds_transfer_es from qtasks.tasks_build import JenkinsBuild from dbapp.models import AppInfo from dbapp.model.model_cmdb import DevLanguage, KubernetesDeploy from common.ext_fun import get_datadict, get_redis_data, harbor_cli, template_generate from config import PLAYBOOK_PATH from dbapp.model.model_deploy import BuildJob, DeployJob, PublishOrder from dbapp.model.model_ucenter import DataDict, UserProfile from dbapp.model.model_workflow import Workflow
11,866
logger = logging.getLogger(__name__) @transaction.atomic def app_build_handle(request_data, appinfo_obj: AppInfo, user: UserProfile): """ 应用构建 """ cipher = AesCipher('sdevops-platform') commit_tag = request_data.get('commit_tag', None) commits = request_data.get('commits', '') modules = request_data.get('modules', 'dist') custom_tag = request_data.get('custom_tag', None) # {0: 构建, 1: 构建发布} is_deploy = request_data.get('is_deploy', False) language = DevLanguage.objects.get(name=appinfo_obj.app.language) OPS_URL = get_redis_data('platform')['url'] jenkins = get_redis_data('cicd-jenkins') category = appinfo_obj.app.category namespace = appinfo_obj.namespace job_name = appinfo_obj.jenkins_jobname forward = 'no' opshost = '' # 定义harbor空配置 harbor_config = {} build_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S') JENKINS_CONFIG = get_redis_data('cicd-jenkins')
logger = logging.getLogger(__name__) @transaction.atomic def app_build_handle(request_data, appinfo_obj: AppInfo, user: UserProfile): """ 应用构建 """ cipher = AesCipher('sdevops-platform') commit_tag = request_data.get('commit_tag', None) commits = request_data.get('commits', '') modules = request_data.get('modules', 'dist') custom_tag = request_data.get('custom_tag', None) # {0: 构建, 1: 构建发布} is_deploy = request_data.get('is_deploy', False) language = DevLanguage.objects.get(name=appinfo_obj.app.language) OPS_URL = get_redis_data('platform')['url'] jenkins = get_redis_data('cicd-jenkins') category = appinfo_obj.app.category namespace = appinfo_obj.namespace job_name = appinfo_obj.jenkins_jobname forward = 'no' opshost = '' # 定义harbor空配置 harbor_config = {} build_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S') JENKINS_CONFIG = get_redis_data('cicd-jenkins')
jbuild = JenkinsBuild(JENKINS_CONFIG['url'], username=JENKINS_CONFIG['user'],
3
2023-12-13 03:09:32+00:00
16k
liujin112/PortraitDiffusion
app.py
[ { "identifier": "AttentionBase", "path": "utils/masactrl_utils.py", "snippet": "class AttentionBase:\n def __init__(self):\n self.cur_step = 0\n self.num_att_layers = -1\n self.cur_att_layer = 0\n\n def after_step(self):\n pass\n\n def __call__(self, q, k, v, sim, at...
import os import torch import random import numpy as np import gradio as gr import torch.nn.functional as F from glob import glob from datetime import datetime from diffusers import StableDiffusionPipeline from diffusers import DDIMScheduler, LCMScheduler from PIL import Image,ImageDraw from utils.masactrl_utils import (AttentionBase, regiter_attention_editor_diffusers) from utils.free_lunch_utils import register_upblock2d,register_crossattn_upblock2d,register_free_upblock2d, register_free_crossattn_upblock2d from utils.style_attn_control import MaskPromptedStyleAttentionControl from utils.pipeline import MasaCtrlPipeline from torchvision.utils import save_image from segment_anything import sam_model_registry, SamPredictor
12,314
self.personal_model_loaded = base_model_dropdown.split('.')[0] print(f'load {base_model_dropdown} model success!') return gr.Dropdown() def update_lora_model(self, lora_model_dropdown,lora_alpha_slider): if self.pipeline is None: gr.Info(f"Please select a pretrained model path.") return None else: if lora_model_dropdown == "none": self.pipeline.unfuse_lora() self.pipeline.unload_lora_weights() self.lora_loaded = None print("Restore lora.") else: lora_model_path = self.lora_model_list[lora_model_dropdown] self.pipeline.load_lora_weights(lora_model_path) self.pipeline.fuse_lora(lora_alpha_slider) self.lora_loaded = lora_model_dropdown.split('.')[0] print(f'load {lora_model_dropdown} LoRA Model Success!') return gr.Dropdown() def load_lcm_lora(self, lora_alpha_slider=1.0): # set scheduler self.pipeline = MasaCtrlPipeline.from_pretrained(self.stable_diffusion_list[0]).to(self.device) self.pipeline.scheduler = LCMScheduler.from_config(self.pipeline.scheduler.config) # load LCM-LoRA self.pipeline.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") self.pipeline.fuse_lora(lora_alpha_slider) self.lcm_lora_loaded = True print(f'load LCM-LoRA model success!') def generate(self, source, style, source_mask, style_mask, start_step, start_layer, Style_attn_step, Method, Style_Guidance, ddim_steps, scale, seed, de_bug, target_prompt, negative_prompt_textbox, inter_latents, freeu, b1, b2, s1, s2, width_slider,height_slider, ): os.makedirs(self.savedir, exist_ok=True) os.makedirs(self.savedir_sample, exist_ok=True) os.makedirs(self.savedir_mask, exist_ok=True) model = self.pipeline if seed != -1 and seed != "": torch.manual_seed(int(seed)) else: torch.seed() seed = torch.initial_seed() sample_count = len(os.listdir(self.savedir_sample)) os.makedirs(os.path.join(self.savedir_mask, f"results_{sample_count}"), exist_ok=True) # ref_prompt = [source_prompt, target_prompt] # prompts = ref_prompt+[''] ref_prompt = [target_prompt, target_prompt] prompts = ref_prompt+[target_prompt] source_image,style_image,source_mask,style_mask = load_mask_images(source,style,source_mask,style_mask,self.device,width_slider,height_slider,out_dir=os.path.join(self.savedir_mask, f"results_{sample_count}")) # global START_CODE, LATENTS_LIST with torch.no_grad(): #import pdb;pdb.set_trace() #prev_source if self.start_code is None and self.latents_list is None: content_style = torch.cat([style_image, source_image], dim=0) editor = AttentionBase() regiter_attention_editor_diffusers(model, editor) st_code, latents_list = model.invert(content_style, ref_prompt, guidance_scale=scale, num_inference_steps=ddim_steps, return_intermediates=True) start_code = torch.cat([st_code, st_code[1:]], dim=0) self.start_code = start_code self.latents_list = latents_list else: start_code = self.start_code latents_list = self.latents_list print('------------------------------------------ Use previous latents ------------------------------------------ ') #["Without mask", "Only masked region", "Seperate Background Foreground"] if Method == "Without mask": style_mask = None source_mask = None only_masked_region = False elif Method == "Only masked region": assert style_mask is not None and source_mask is not None only_masked_region = True else: assert style_mask is not None and source_mask is not None only_masked_region = False controller = MaskPromptedStyleAttentionControl(start_step, start_layer, style_attn_step=Style_attn_step, style_guidance=Style_Guidance, style_mask=style_mask, source_mask=source_mask, only_masked_region=only_masked_region, guidance=scale, de_bug=de_bug, ) if freeu: # model.enable_freeu(s1=0.9, s2=0.2, b1=1.2, b2=1.4) print(f'++++++++++++++++++ Run with FreeU {b1}_{b2}_{s1}_{s2} ++++++++++++++++') if Method != "Without mask": register_free_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=source_mask) register_free_crossattn_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=source_mask) else: register_free_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=None) register_free_crossattn_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=None) else: print(f'++++++++++++++++++ Run without FreeU ++++++++++++++++') # model.disable_freeu()
css = """ .toolbutton { margin-buttom: 0em 0em 0em 0em; max-width: 2.5em; min-width: 2.5em !important; height: 2.5em; } """ class GlobalText: def __init__(self): # config dirs self.basedir = os.getcwd() self.stable_diffusion_dir = os.path.join(self.basedir, "models", "StableDiffusion") self.personalized_model_dir = './models/Stable-diffusion' self.lora_model_dir = './models/Lora' self.savedir = os.path.join(self.basedir, "samples", datetime.now().strftime("Gradio-%Y-%m-%dT%H-%M-%S")) self.savedir_sample = os.path.join(self.savedir, "sample") self.savedir_mask = os.path.join(self.savedir, "mask") self.stable_diffusion_list = ["runwayml/stable-diffusion-v1-5", "latent-consistency/lcm-lora-sdv1-5"] self.personalized_model_list = [] self.lora_model_list = [] # config models self.tokenizer = None self.text_encoder = None self.vae = None self.unet = None self.pipeline = None self.lora_loaded = None self.lcm_lora_loaded = False self.personal_model_loaded = None self.sam_predictor = None self.lora_model_state_dict = {} self.device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") # self.refresh_stable_diffusion() self.refresh_personalized_model() self.reset_start_code() def load_base_pipeline(self, model_path): print(f'loading {model_path} model') scheduler = DDIMScheduler.from_pretrained(model_path,subfolder="scheduler") self.pipeline = MasaCtrlPipeline.from_pretrained(model_path, scheduler=scheduler).to(self.device) def refresh_stable_diffusion(self): self.load_base_pipeline(self.stable_diffusion_list[0]) self.lora_loaded = None self.personal_model_loaded = None self.lcm_lora_loaded = False return self.stable_diffusion_list[0] def refresh_personalized_model(self): personalized_model_list = glob(os.path.join(self.personalized_model_dir, "**/*.safetensors"), recursive=True) self.personalized_model_list = {os.path.basename(file): file for file in personalized_model_list} lora_model_list = glob(os.path.join(self.lora_model_dir, "**/*.safetensors"), recursive=True) self.lora_model_list = {os.path.basename(file): file for file in lora_model_list} def update_stable_diffusion(self, stable_diffusion_dropdown): if stable_diffusion_dropdown == 'latent-consistency/lcm-lora-sdv1-5': self.load_lcm_lora() else: self.load_base_pipeline(stable_diffusion_dropdown) self.lora_loaded = None self.personal_model_loaded = None return gr.Dropdown() def update_base_model(self, base_model_dropdown): if self.pipeline is None: gr.Info(f"Please select a pretrained model path.") return None else: base_model = self.personalized_model_list[base_model_dropdown] mid_model = StableDiffusionPipeline.from_single_file(base_model) self.pipeline.vae = mid_model.vae self.pipeline.unet = mid_model.unet self.pipeline.text_encoder = mid_model.text_encoder self.pipeline.to(self.device) self.personal_model_loaded = base_model_dropdown.split('.')[0] print(f'load {base_model_dropdown} model success!') return gr.Dropdown() def update_lora_model(self, lora_model_dropdown,lora_alpha_slider): if self.pipeline is None: gr.Info(f"Please select a pretrained model path.") return None else: if lora_model_dropdown == "none": self.pipeline.unfuse_lora() self.pipeline.unload_lora_weights() self.lora_loaded = None print("Restore lora.") else: lora_model_path = self.lora_model_list[lora_model_dropdown] self.pipeline.load_lora_weights(lora_model_path) self.pipeline.fuse_lora(lora_alpha_slider) self.lora_loaded = lora_model_dropdown.split('.')[0] print(f'load {lora_model_dropdown} LoRA Model Success!') return gr.Dropdown() def load_lcm_lora(self, lora_alpha_slider=1.0): # set scheduler self.pipeline = MasaCtrlPipeline.from_pretrained(self.stable_diffusion_list[0]).to(self.device) self.pipeline.scheduler = LCMScheduler.from_config(self.pipeline.scheduler.config) # load LCM-LoRA self.pipeline.load_lora_weights("latent-consistency/lcm-lora-sdv1-5") self.pipeline.fuse_lora(lora_alpha_slider) self.lcm_lora_loaded = True print(f'load LCM-LoRA model success!') def generate(self, source, style, source_mask, style_mask, start_step, start_layer, Style_attn_step, Method, Style_Guidance, ddim_steps, scale, seed, de_bug, target_prompt, negative_prompt_textbox, inter_latents, freeu, b1, b2, s1, s2, width_slider,height_slider, ): os.makedirs(self.savedir, exist_ok=True) os.makedirs(self.savedir_sample, exist_ok=True) os.makedirs(self.savedir_mask, exist_ok=True) model = self.pipeline if seed != -1 and seed != "": torch.manual_seed(int(seed)) else: torch.seed() seed = torch.initial_seed() sample_count = len(os.listdir(self.savedir_sample)) os.makedirs(os.path.join(self.savedir_mask, f"results_{sample_count}"), exist_ok=True) # ref_prompt = [source_prompt, target_prompt] # prompts = ref_prompt+[''] ref_prompt = [target_prompt, target_prompt] prompts = ref_prompt+[target_prompt] source_image,style_image,source_mask,style_mask = load_mask_images(source,style,source_mask,style_mask,self.device,width_slider,height_slider,out_dir=os.path.join(self.savedir_mask, f"results_{sample_count}")) # global START_CODE, LATENTS_LIST with torch.no_grad(): #import pdb;pdb.set_trace() #prev_source if self.start_code is None and self.latents_list is None: content_style = torch.cat([style_image, source_image], dim=0) editor = AttentionBase() regiter_attention_editor_diffusers(model, editor) st_code, latents_list = model.invert(content_style, ref_prompt, guidance_scale=scale, num_inference_steps=ddim_steps, return_intermediates=True) start_code = torch.cat([st_code, st_code[1:]], dim=0) self.start_code = start_code self.latents_list = latents_list else: start_code = self.start_code latents_list = self.latents_list print('------------------------------------------ Use previous latents ------------------------------------------ ') #["Without mask", "Only masked region", "Seperate Background Foreground"] if Method == "Without mask": style_mask = None source_mask = None only_masked_region = False elif Method == "Only masked region": assert style_mask is not None and source_mask is not None only_masked_region = True else: assert style_mask is not None and source_mask is not None only_masked_region = False controller = MaskPromptedStyleAttentionControl(start_step, start_layer, style_attn_step=Style_attn_step, style_guidance=Style_Guidance, style_mask=style_mask, source_mask=source_mask, only_masked_region=only_masked_region, guidance=scale, de_bug=de_bug, ) if freeu: # model.enable_freeu(s1=0.9, s2=0.2, b1=1.2, b2=1.4) print(f'++++++++++++++++++ Run with FreeU {b1}_{b2}_{s1}_{s2} ++++++++++++++++') if Method != "Without mask": register_free_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=source_mask) register_free_crossattn_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=source_mask) else: register_free_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=None) register_free_crossattn_upblock2d(model, b1=b1, b2=b2, s1=s1, s2=s1,source_mask=None) else: print(f'++++++++++++++++++ Run without FreeU ++++++++++++++++') # model.disable_freeu()
register_upblock2d(model)
2
2023-12-06 01:18:39+00:00
16k
AsuradaYuci/TF-CLIP
datasets/make_dataloader_clipreid.py
[ { "identifier": "VideoDataset", "path": "datasets/video_loader_xh.py", "snippet": "class VideoDataset(Dataset):\n \"\"\"Video Person ReID Dataset.\n Note batch data has shape (batch, seq_len, channel, height, width).\n \"\"\"\n sample_methods = ['evenly', 'random', 'dense']\n\n def __init...
import torch import utils.spatial_transforms as ST import utils.temporal_transforms as TT import utils.transforms as T import utils.seqtransforms as SeqT from torch.utils.data import DataLoader from datasets.video_loader_xh import VideoDataset from datasets.samplers import RandomIdentitySampler, RandomIdentitySamplerForSeq, RandomIdentitySamplerWYQ from datasets.seqpreprocessor import SeqTrainPreprocessor, SeqTestPreprocessor from datasets.set.mars import Mars from datasets.set.ilidsvidsequence import iLIDSVIDSEQUENCE from datasets.set.lsvid import LSVID
12,722
# from torchvision.transforms import InterpolationMode # import torchvision.transforms as T __factory = { 'mars': Mars, 'ilidsvidsequence': iLIDSVIDSEQUENCE, 'lsvid': LSVID } def train_collate_fn(batch): """ # collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果 """ imgs, pids, camids, viewids, _ = zip(*batch) pids = torch.tensor(pids, dtype=torch.int64) viewids = torch.tensor(viewids, dtype=torch.int64) camids = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, viewids, def val_collate_fn(batch): imgs, pids, camids, viewids, img_paths = zip(*batch) viewids = torch.tensor(viewids, dtype=torch.int64) camids_batch = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, camids_batch, viewids, img_paths def train_collate_fn_seq(batch): """ # collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果 """ imgs, flows, pids, camids = zip(*batch) viewids = 1 pids = torch.tensor(pids, dtype=torch.int64) viewids = torch.tensor(viewids, dtype=torch.int64) camids = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, viewids, def val_collate_fn_seq(batch): imgs, flows, pids, camids = zip(*batch) viewids = 1 img_paths = None viewids = torch.tensor(viewids, dtype=torch.int64) camids_batch = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, camids_batch, viewids, img_paths def make_dataloader(cfg): split_id = cfg.DATASETS.SPLIT seq_srd = cfg.INPUT.SEQ_SRD seq_len = cfg.INPUT.SEQ_LEN num_workers = cfg.DATALOADER.NUM_WORKERS if cfg.DATASETS.NAMES != 'mars' and cfg.DATASETS.NAMES != 'duke' and cfg.DATASETS.NAMES != 'lsvid': dataset = __factory[cfg.DATASETS.NAMES](root=cfg.DATASETS.ROOT_DIR, split_id=split_id, seq_len=seq_len, seq_srd=seq_srd, num_val=1) num_classes = dataset.num_trainval_ids cam_num = dataset.num_train_cams view_num = dataset.num_train_vids train_set = SeqTrainPreprocessor(dataset.trainval, dataset, seq_len, transform=SeqT.Compose([SeqT.RectScale(256, 128), SeqT.RandomHorizontalFlip(), SeqT.RandomSizedEarser(), SeqT.ToTensor(), SeqT.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])) train_set_normal = SeqTrainPreprocessor(dataset.trainval, dataset, seq_len, transform=SeqT.Compose([SeqT.RectScale(256, 128), SeqT.ToTensor(), SeqT.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])) val_set = SeqTestPreprocessor(dataset.query + dataset.gallery, dataset, seq_len, transform=SeqT.Compose([SeqT.RectScale(256, 128), SeqT.ToTensor(), SeqT.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])) train_loader_stage2 = DataLoader( train_set,
# from torchvision.transforms import InterpolationMode # import torchvision.transforms as T __factory = { 'mars': Mars, 'ilidsvidsequence': iLIDSVIDSEQUENCE, 'lsvid': LSVID } def train_collate_fn(batch): """ # collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果 """ imgs, pids, camids, viewids, _ = zip(*batch) pids = torch.tensor(pids, dtype=torch.int64) viewids = torch.tensor(viewids, dtype=torch.int64) camids = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, viewids, def val_collate_fn(batch): imgs, pids, camids, viewids, img_paths = zip(*batch) viewids = torch.tensor(viewids, dtype=torch.int64) camids_batch = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, camids_batch, viewids, img_paths def train_collate_fn_seq(batch): """ # collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果 """ imgs, flows, pids, camids = zip(*batch) viewids = 1 pids = torch.tensor(pids, dtype=torch.int64) viewids = torch.tensor(viewids, dtype=torch.int64) camids = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, viewids, def val_collate_fn_seq(batch): imgs, flows, pids, camids = zip(*batch) viewids = 1 img_paths = None viewids = torch.tensor(viewids, dtype=torch.int64) camids_batch = torch.tensor(camids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids, camids, camids_batch, viewids, img_paths def make_dataloader(cfg): split_id = cfg.DATASETS.SPLIT seq_srd = cfg.INPUT.SEQ_SRD seq_len = cfg.INPUT.SEQ_LEN num_workers = cfg.DATALOADER.NUM_WORKERS if cfg.DATASETS.NAMES != 'mars' and cfg.DATASETS.NAMES != 'duke' and cfg.DATASETS.NAMES != 'lsvid': dataset = __factory[cfg.DATASETS.NAMES](root=cfg.DATASETS.ROOT_DIR, split_id=split_id, seq_len=seq_len, seq_srd=seq_srd, num_val=1) num_classes = dataset.num_trainval_ids cam_num = dataset.num_train_cams view_num = dataset.num_train_vids train_set = SeqTrainPreprocessor(dataset.trainval, dataset, seq_len, transform=SeqT.Compose([SeqT.RectScale(256, 128), SeqT.RandomHorizontalFlip(), SeqT.RandomSizedEarser(), SeqT.ToTensor(), SeqT.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])) train_set_normal = SeqTrainPreprocessor(dataset.trainval, dataset, seq_len, transform=SeqT.Compose([SeqT.RectScale(256, 128), SeqT.ToTensor(), SeqT.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])) val_set = SeqTestPreprocessor(dataset.query + dataset.gallery, dataset, seq_len, transform=SeqT.Compose([SeqT.RectScale(256, 128), SeqT.ToTensor(), SeqT.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])) train_loader_stage2 = DataLoader( train_set,
sampler=RandomIdentitySamplerForSeq(dataset.trainval, batch_size=cfg.SOLVER.STAGE2.IMS_PER_BATCH,
2
2023-12-11 04:03:46+00:00
16k
MarilynKeller/aitviewer-skel
aitviewer/renderables/markers.py
[ { "identifier": "Spheres", "path": "aitviewer/renderables/spheres.py", "snippet": "class Spheres(Node):\n \"\"\"Render some simple spheres.\"\"\"\n\n def __init__(\n self,\n positions,\n radius=0.01,\n color=(0.0, 0.0, 1.0, 1.0),\n rings=16,\n sectors=32,\...
import numpy as np import os import pickle as pkl import tqdm import nimblephysics as nimble from aitviewer.renderables.spheres import Spheres from aitviewer.scene.node import Node from aitviewer.renderables.point_clouds import PointClouds from aitviewer.utils import mocap from aitviewer.utils.mocap import clean_CMU_mocap_labels
11,724
# Code Developed by: # Marilyn Keller, marilyn.keller@tuebingen.mpg.de # Do not share or distribute without permission of the author class Markers(Node): """ Draw a point clouds man! """ def __init__(self, points, markers_labels, name="Mocap data", colors=None, lengths=None, point_size=5.0, radius = 0.0075, color=(0.0, 0.0, 1.0, 1.0), as_spheres=True, **kwargs): """ A sequence of point clouds. Each point cloud can have a varying number of points. Internally represented as a list of arrays. :param points: Sequence of points (F, P, 3) :param colors: Sequence of Colors (F, C, 4) :param lengths: Length mask for each frame of points denoting the usable part of the array :param point_size: Initial point size """ # self.points = points super(Markers, self).__init__(name, n_frames=points.shape[0], color=color, **kwargs) # Check that the marker labels are sorted # markers_labels_copy = markers_labels.copy() # markers_labels_copy.sort() # assert markers_labels == markers_labels_copy self.markers_labels = markers_labels self.marker_trajectory = points # FxMx3 self.color = color if self.marker_trajectory.shape[1]>200: as_spheres = False print(f"Too many markers ({self.marker_trajectory.shape[1]}). Switching to pointcloud.") #todo fix color bug for mi, marker_name in enumerate(self.markers_labels): if colors is not None: color = tuple(colors[mi]) if as_spheres: markers_seq = Spheres(self.marker_trajectory[:,mi,:][:,np.newaxis,:], color=color, radius = radius, name=marker_name, **kwargs) else:
# Code Developed by: # Marilyn Keller, marilyn.keller@tuebingen.mpg.de # Do not share or distribute without permission of the author class Markers(Node): """ Draw a point clouds man! """ def __init__(self, points, markers_labels, name="Mocap data", colors=None, lengths=None, point_size=5.0, radius = 0.0075, color=(0.0, 0.0, 1.0, 1.0), as_spheres=True, **kwargs): """ A sequence of point clouds. Each point cloud can have a varying number of points. Internally represented as a list of arrays. :param points: Sequence of points (F, P, 3) :param colors: Sequence of Colors (F, C, 4) :param lengths: Length mask for each frame of points denoting the usable part of the array :param point_size: Initial point size """ # self.points = points super(Markers, self).__init__(name, n_frames=points.shape[0], color=color, **kwargs) # Check that the marker labels are sorted # markers_labels_copy = markers_labels.copy() # markers_labels_copy.sort() # assert markers_labels == markers_labels_copy self.markers_labels = markers_labels self.marker_trajectory = points # FxMx3 self.color = color if self.marker_trajectory.shape[1]>200: as_spheres = False print(f"Too many markers ({self.marker_trajectory.shape[1]}). Switching to pointcloud.") #todo fix color bug for mi, marker_name in enumerate(self.markers_labels): if colors is not None: color = tuple(colors[mi]) if as_spheres: markers_seq = Spheres(self.marker_trajectory[:,mi,:][:,np.newaxis,:], color=color, radius = radius, name=marker_name, **kwargs) else:
markers_seq = PointClouds(self.marker_trajectory[:,mi,:][:,np.newaxis,:], name=marker_name, point_size=point_size, color=color, **kwargs)
2
2023-12-07 16:13:50+00:00
16k
nexB/dejacode
dejacode/urls.py
[ { "identifier": "ComponentViewSet", "path": "component_catalog/api.py", "snippet": "class ComponentViewSet(CreateRetrieveUpdateListViewSet):\n queryset = Component.objects.all()\n serializer_class = ComponentSerializer\n filterset_class = ComponentFilterSet\n lookup_field = \"uuid\"\n sea...
from django.conf import settings from django.conf.urls import include from django.contrib import admin from django.contrib.auth import views as auth_views from django.contrib.auth.decorators import login_required from django.template.loader import render_to_string from django.urls import path from django.views.defaults import page_not_found from django.views.generic import RedirectView from django.views.generic import TemplateView from notifications.views import mark_all_as_read from rest_framework.documentation import include_docs_urls from rest_framework.routers import DefaultRouter from component_catalog.api import ComponentViewSet from component_catalog.api import PackageViewSet from component_catalog.api import SubcomponentViewSet from component_catalog.views import send_scan_notification from dje import two_factor from dje.admin import dejacode_site from dje.api import ExternalReferenceViewSet from dje.forms import DejaCodeAuthenticationForm from dje.registration import DejaCodeActivationView from dje.registration import DejaCodeRegistrationForm from dje.views import AccountProfileView from dje.views import AllNotificationsList from dje.views import DataspaceAwareAutocompleteLookup from dje.views import DataspaceAwareRelatedLookup from dje.views import GlobalSearchListView from dje.views import IntegrationsStatusView from dje.views import UnreadNotificationsList from dje.views import home_view from dje.views import index_dispatch from dje.views import urn_resolve_view from license_library.api import LicenseAnnotationViewSet from license_library.api import LicenseViewSet from organization.api import OwnerViewSet from policy.api import UsagePolicyViewSet from product_portfolio.api import CodebaseResourceViewSet from product_portfolio.api import ProductComponentViewSet from product_portfolio.api import ProductPackageViewSet from product_portfolio.api import ProductViewSet from reporting.api import ReportViewSet from workflow.api import RequestTemplateViewSet from workflow.api import RequestViewSet from django_registration.backends.activation.views import RegistrationView
12,474
# # 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. # # Replace the default admin site with the DejaCode one. admin.site = dejacode_site # Restframework API api_router = DefaultRouter() api_router.register("owners", OwnerViewSet) api_router.register("licenses", LicenseViewSet) api_router.register("license_annotations", LicenseAnnotationViewSet) api_router.register("components", ComponentViewSet) api_router.register("subcomponents", SubcomponentViewSet) api_router.register("packages", PackageViewSet) api_router.register("products", ProductViewSet) api_router.register("product_components", ProductComponentViewSet) api_router.register("product_packages", ProductPackageViewSet) api_router.register("codebase_resources", CodebaseResourceViewSet) api_router.register("request_templates", RequestTemplateViewSet) api_router.register("requests", RequestViewSet) api_router.register("reports", ReportViewSet) api_router.register("external_references", ExternalReferenceViewSet) api_router.register("usage_policies", UsagePolicyViewSet) urlpatterns = [ path("", index_dispatch, name="index_dispatch"), path("home/", home_view, name="home"), path("integrations_status/", IntegrationsStatusView.as_view(), name="integrations_status"), path("account/", include("django.contrib.auth.urls")), path("account/profile/", AccountProfileView.as_view(), name="account_profile"), path("logout/", auth_views.LogoutView.as_view(next_page="login"), name="logout"), path( "login/", two_factor.LoginView.as_view( authentication_form=DejaCodeAuthenticationForm, redirect_authenticated_user=True, ), name="login", ), # Activation and password views are required for the user creation flow. # registration_activation_complete needs to be register before registration_activate # so the 'complete/' segment is not caught as the activation_key path( "account/activate/complete/", TemplateView.as_view(template_name="django_registration/activation_complete.html"), name="django_registration_activation_complete", ), path( "account/activate/<str:activation_key>/", DejaCodeActivationView.as_view(), name="django_registration_activate", ), # Two-factor authentication path("account/2fa/enable/", two_factor.EnableView.as_view(), name="account_2fa_enable"), path("account/2fa/disable/", two_factor.DisableView.as_view(), name="account_2fa_disable"), path("account/2fa/verify/", two_factor.VerifyView.as_view(), name="account_2fa_verify"), path("urn/", urn_resolve_view, name="urn_resolve"), path("urn/<urn>/", urn_resolve_view, name="urn_resolve"), path("admin/", dejacode_site.urls), # Grappelli does not have a hook for replacing the ``RelatedLookup`` view # class so we hijack the url used by that view and use our own version of # ``RelatedLookup``. The same is done for ``AutocompleteLookup``. path( "grappelli/lookup/related/", DataspaceAwareRelatedLookup.as_view(), name="grp_related_lookup", ), path( "grappelli/lookup/autocomplete/", DataspaceAwareAutocompleteLookup.as_view(), name="grp_autocomplete_lookup", ), # Disable Grappelli's M2M lookup. path("grappelli/lookup/m2m/", page_not_found, name="grp_m2m_lookup"), # This need to be registered after the overrides. path("grappelli/", include("grappelli.urls")), path("favicon.ico", RedirectView.as_view(url="/static/img/favicon.ico", permanent=True)), ] urlpatterns += [ path("licenses/", include(("license_library.urls", "license_library"))), path("", include(("component_catalog.urls", "component_catalog"))), path("products/", include(("product_portfolio.urls", "product_portfolio"))), path("owners/", include(("organization.urls", "organization"))), path("requests/", include(("workflow.urls", "workflow"))), path("reports/", include(("reporting.urls", "reporting"))), path("global_search/", GlobalSearchListView.as_view(), name="global_search"), ] notification_patterns = [
# # 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. # # Replace the default admin site with the DejaCode one. admin.site = dejacode_site # Restframework API api_router = DefaultRouter() api_router.register("owners", OwnerViewSet) api_router.register("licenses", LicenseViewSet) api_router.register("license_annotations", LicenseAnnotationViewSet) api_router.register("components", ComponentViewSet) api_router.register("subcomponents", SubcomponentViewSet) api_router.register("packages", PackageViewSet) api_router.register("products", ProductViewSet) api_router.register("product_components", ProductComponentViewSet) api_router.register("product_packages", ProductPackageViewSet) api_router.register("codebase_resources", CodebaseResourceViewSet) api_router.register("request_templates", RequestTemplateViewSet) api_router.register("requests", RequestViewSet) api_router.register("reports", ReportViewSet) api_router.register("external_references", ExternalReferenceViewSet) api_router.register("usage_policies", UsagePolicyViewSet) urlpatterns = [ path("", index_dispatch, name="index_dispatch"), path("home/", home_view, name="home"), path("integrations_status/", IntegrationsStatusView.as_view(), name="integrations_status"), path("account/", include("django.contrib.auth.urls")), path("account/profile/", AccountProfileView.as_view(), name="account_profile"), path("logout/", auth_views.LogoutView.as_view(next_page="login"), name="logout"), path( "login/", two_factor.LoginView.as_view( authentication_form=DejaCodeAuthenticationForm, redirect_authenticated_user=True, ), name="login", ), # Activation and password views are required for the user creation flow. # registration_activation_complete needs to be register before registration_activate # so the 'complete/' segment is not caught as the activation_key path( "account/activate/complete/", TemplateView.as_view(template_name="django_registration/activation_complete.html"), name="django_registration_activation_complete", ), path( "account/activate/<str:activation_key>/", DejaCodeActivationView.as_view(), name="django_registration_activate", ), # Two-factor authentication path("account/2fa/enable/", two_factor.EnableView.as_view(), name="account_2fa_enable"), path("account/2fa/disable/", two_factor.DisableView.as_view(), name="account_2fa_disable"), path("account/2fa/verify/", two_factor.VerifyView.as_view(), name="account_2fa_verify"), path("urn/", urn_resolve_view, name="urn_resolve"), path("urn/<urn>/", urn_resolve_view, name="urn_resolve"), path("admin/", dejacode_site.urls), # Grappelli does not have a hook for replacing the ``RelatedLookup`` view # class so we hijack the url used by that view and use our own version of # ``RelatedLookup``. The same is done for ``AutocompleteLookup``. path( "grappelli/lookup/related/", DataspaceAwareRelatedLookup.as_view(), name="grp_related_lookup", ), path( "grappelli/lookup/autocomplete/", DataspaceAwareAutocompleteLookup.as_view(), name="grp_autocomplete_lookup", ), # Disable Grappelli's M2M lookup. path("grappelli/lookup/m2m/", page_not_found, name="grp_m2m_lookup"), # This need to be registered after the overrides. path("grappelli/", include("grappelli.urls")), path("favicon.ico", RedirectView.as_view(url="/static/img/favicon.ico", permanent=True)), ] urlpatterns += [ path("licenses/", include(("license_library.urls", "license_library"))), path("", include(("component_catalog.urls", "component_catalog"))), path("products/", include(("product_portfolio.urls", "product_portfolio"))), path("owners/", include(("organization.urls", "organization"))), path("requests/", include(("workflow.urls", "workflow"))), path("reports/", include(("reporting.urls", "reporting"))), path("global_search/", GlobalSearchListView.as_view(), name="global_search"), ] notification_patterns = [
path("", UnreadNotificationsList.as_view(), name="unread"),
16
2023-12-07 16:57:42+00:00
16k
wusize/CLIM
src/open_clip/factory.py
[ { "identifier": "OPENAI_DATASET_MEAN", "path": "src/open_clip/constants.py", "snippet": "OPENAI_DATASET_MEAN = (0.48145466, 0.4578275, 0.40821073)" }, { "identifier": "OPENAI_DATASET_STD", "path": "src/open_clip/constants.py", "snippet": "OPENAI_DATASET_STD = (0.26862954, 0.26130258, 0.2...
import json import logging import os import pathlib import re import torch from copy import deepcopy from pathlib import Path from typing import Any, Dict, Optional, Tuple, Union from .constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD from .model import CLIP, CustomTextCLIP, convert_weights_to_lp, convert_to_custom_text_state_dict,\ resize_pos_embed, get_cast_dtype from .coca_model import CoCa from .loss import ClipLoss, DistillClipLoss, CoCaLoss from .openai import load_openai_model from .pretrained import is_pretrained_cfg, get_pretrained_cfg, \ download_pretrained, list_pretrained_tags_by_model, download_pretrained_from_hf from .transform import image_transform, AugmentationCfg, det_image_transform from .tokenizer import HFTokenizer, tokenize from open_clip import eva_clip from open_clip import eva_clip
13,630
with open(config_path, 'r', encoding='utf-8') as f: config = json.load(f) pretrained_cfg = config['preprocess_cfg'] model_cfg = config['model_cfg'] else: model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names checkpoint_path = None pretrained_cfg = {} model_cfg = None if isinstance(device, str): device = torch.device(device) if pretrained == 'eva': return eva_clip.create_model(model_name=model_name, pretrained=cache_dir, force_custom_clip=True, precision=precision, 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, ) # to always output dict even if it is clip if output_dict and hasattr(model, "output_dict"): model.output_dict = True else: model_cfg = model_cfg or 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 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 if force_image_size is not None: # override model config's image size model_cfg["vision_cfg"]["image_size"] = force_image_size if 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 else: assert False, 'pretrained image towers currently only supported for timm models' cast_dtype = get_cast_dtype(precision) is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {}) custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model if custom_text: if is_hf_model: model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf if "coca" in model_name: model = CoCa(**model_cfg, cast_dtype=cast_dtype) else: model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype) else: model = CLIP(**model_cfg, cast_dtype=cast_dtype) pretrained_loaded = False 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: print(f'Loading pretrained {model_name} weights ({pretrained}).', flush=True) logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') load_checkpoint(model, checkpoint_path) 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) pretrained_loaded = True elif has_hf_hub_prefix: logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') load_checkpoint(model, checkpoint_path) pretrained_loaded = True if require_pretrained and not pretrained_loaded: # callers of create_model_from_pretrained always expect pretrained weights raise RuntimeError( f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.') model.to(device=device) if precision in ("fp16", "bf16"): convert_weights_to_lp(model, dtype=torch.bfloat16 if precision == 'bf16' else torch.float16) # 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 # to always output dict even if it is clip if output_dict and hasattr(model, "output_dict"): model.output_dict = True if jit: model = torch.jit.script(model) return model def create_loss(args):
HF_HUB_PREFIX = 'hf-hub:' _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') 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 = {k: v for k, v in 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): if 'EVA' in model_name: return eva_clip.get_tokenizer(model_name) if model_name.startswith(HF_HUB_PREFIX): tokenizer = HFTokenizer(model_name[len(HF_HUB_PREFIX):]) else: 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 def load_state_dict(checkpoint_path: str, map_location='cpu'): checkpoint = torch.load(checkpoint_path, map_location=map_location) if isinstance(checkpoint, dict) and 'state_dict' in checkpoint: state_dict = checkpoint['state_dict'] 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()} return state_dict def load_checkpoint(model, checkpoint_path, strict=True): state_dict = load_state_dict(checkpoint_path) # 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) resize_pos_embed(state_dict, model) incompatible_keys = model.load_state_dict(state_dict, strict=strict) return 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_text: bool = False, force_patch_dropout: Optional[float] = None, force_image_size: Optional[Union[int, Tuple[int, int]]] = None, pretrained_image: bool = False, pretrained_hf: bool = True, cache_dir: Optional[str] = None, output_dict: Optional[bool] = None, require_pretrained: bool = False, ): has_hf_hub_prefix = model_name.startswith(HF_HUB_PREFIX) if has_hf_hub_prefix: model_id = model_name[len(HF_HUB_PREFIX):] checkpoint_path = download_pretrained_from_hf(model_id, cache_dir=cache_dir) config_path = download_pretrained_from_hf(model_id, filename='open_clip_config.json', cache_dir=cache_dir) with open(config_path, 'r', encoding='utf-8') as f: config = json.load(f) pretrained_cfg = config['preprocess_cfg'] model_cfg = config['model_cfg'] else: model_name = model_name.replace('/', '-') # for callers using old naming with / in ViT names checkpoint_path = None pretrained_cfg = {} model_cfg = None if isinstance(device, str): device = torch.device(device) if pretrained == 'eva': return eva_clip.create_model(model_name=model_name, pretrained=cache_dir, force_custom_clip=True, precision=precision, 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, ) # to always output dict even if it is clip if output_dict and hasattr(model, "output_dict"): model.output_dict = True else: model_cfg = model_cfg or 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 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 if force_image_size is not None: # override model config's image size model_cfg["vision_cfg"]["image_size"] = force_image_size if 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 else: assert False, 'pretrained image towers currently only supported for timm models' cast_dtype = get_cast_dtype(precision) is_hf_model = 'hf_model_name' in model_cfg.get('text_cfg', {}) custom_text = model_cfg.pop('custom_text', False) or force_custom_text or is_hf_model if custom_text: if is_hf_model: model_cfg['text_cfg']['hf_model_pretrained'] = pretrained_hf if "coca" in model_name: model = CoCa(**model_cfg, cast_dtype=cast_dtype) else: model = CustomTextCLIP(**model_cfg, cast_dtype=cast_dtype) else: model = CLIP(**model_cfg, cast_dtype=cast_dtype) pretrained_loaded = False 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: print(f'Loading pretrained {model_name} weights ({pretrained}).', flush=True) logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') load_checkpoint(model, checkpoint_path) 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) pretrained_loaded = True elif has_hf_hub_prefix: logging.info(f'Loading pretrained {model_name} weights ({pretrained}).') load_checkpoint(model, checkpoint_path) pretrained_loaded = True if require_pretrained and not pretrained_loaded: # callers of create_model_from_pretrained always expect pretrained weights raise RuntimeError( f'Pretrained weights were required for (model: {model_name}, pretrained: {pretrained}) but not loaded.') model.to(device=device) if precision in ("fp16", "bf16"): convert_weights_to_lp(model, dtype=torch.bfloat16 if precision == 'bf16' else torch.float16) # 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 # to always output dict even if it is clip if output_dict and hasattr(model, "output_dict"): model.output_dict = True if jit: model = torch.jit.script(model) return model def create_loss(args):
return ClipLoss(
9
2023-12-09 05:43:08+00:00
16k
moonshot-admin/moonshot
third-party/tqdm-4.66.1/tqdm/tk.py
[ { "identifier": "TqdmExperimentalWarning", "path": "third-party/tqdm-4.66.1/tqdm/std.py", "snippet": "class TqdmExperimentalWarning(TqdmWarning, FutureWarning):\n \"\"\"beta feature, unstable API and behaviour\"\"\"\n pass" }, { "identifier": "TqdmWarning", "path": "third-party/tqdm-4....
import re import sys import tkinter import tkinter.ttk as ttk from warnings import warn from .std import TqdmExperimentalWarning, TqdmWarning from .std import tqdm as std_tqdm
13,102
""" Tkinter GUI progressbar decorator for iterators. Usage: >>> from tqdm.tk import trange, tqdm >>> for i in trange(10): ... ... """ __author__ = {"github.com/": ["richardsheridan", "casperdcl"]} __all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange'] class tqdm_tk(std_tqdm): # pragma: no cover """ Experimental Tkinter GUI version of tqdm! Note: Window interactivity suffers if `tqdm_tk` is not running within a Tkinter mainloop and values are generated infrequently. In this case, consider calling `tqdm_tk.refresh()` frequently in the Tk thread. """ # TODO: @classmethod: write()? def __init__(self, *args, **kwargs): """ This class accepts the following parameters *in addition* to the parameters accepted by `tqdm`. Parameters ---------- grab : bool, optional Grab the input across all windows of the process. tk_parent : `tkinter.Wm`, optional Parent Tk window. cancel_callback : Callable, optional Create a cancel button and set `cancel_callback` to be called when the cancel or window close button is clicked. """ kwargs = kwargs.copy() kwargs['gui'] = True # convert disable = None to False kwargs['disable'] = bool(kwargs.get('disable', False)) self._warn_leave = 'leave' in kwargs grab = kwargs.pop('grab', False) tk_parent = kwargs.pop('tk_parent', None) self._cancel_callback = kwargs.pop('cancel_callback', None) super(tqdm_tk, self).__init__(*args, **kwargs) if self.disable: return if tk_parent is None: # Discover parent widget try: tk_parent = tkinter._default_root except AttributeError: raise AttributeError( "`tk_parent` required when using `tkinter.NoDefaultRoot()`") if tk_parent is None: # use new default root window as display self._tk_window = tkinter.Tk() else: # some other windows already exist self._tk_window = tkinter.Toplevel() else: self._tk_window = tkinter.Toplevel(tk_parent)
""" Tkinter GUI progressbar decorator for iterators. Usage: >>> from tqdm.tk import trange, tqdm >>> for i in trange(10): ... ... """ __author__ = {"github.com/": ["richardsheridan", "casperdcl"]} __all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange'] class tqdm_tk(std_tqdm): # pragma: no cover """ Experimental Tkinter GUI version of tqdm! Note: Window interactivity suffers if `tqdm_tk` is not running within a Tkinter mainloop and values are generated infrequently. In this case, consider calling `tqdm_tk.refresh()` frequently in the Tk thread. """ # TODO: @classmethod: write()? def __init__(self, *args, **kwargs): """ This class accepts the following parameters *in addition* to the parameters accepted by `tqdm`. Parameters ---------- grab : bool, optional Grab the input across all windows of the process. tk_parent : `tkinter.Wm`, optional Parent Tk window. cancel_callback : Callable, optional Create a cancel button and set `cancel_callback` to be called when the cancel or window close button is clicked. """ kwargs = kwargs.copy() kwargs['gui'] = True # convert disable = None to False kwargs['disable'] = bool(kwargs.get('disable', False)) self._warn_leave = 'leave' in kwargs grab = kwargs.pop('grab', False) tk_parent = kwargs.pop('tk_parent', None) self._cancel_callback = kwargs.pop('cancel_callback', None) super(tqdm_tk, self).__init__(*args, **kwargs) if self.disable: return if tk_parent is None: # Discover parent widget try: tk_parent = tkinter._default_root except AttributeError: raise AttributeError( "`tk_parent` required when using `tkinter.NoDefaultRoot()`") if tk_parent is None: # use new default root window as display self._tk_window = tkinter.Tk() else: # some other windows already exist self._tk_window = tkinter.Toplevel() else: self._tk_window = tkinter.Toplevel(tk_parent)
warn("GUI is experimental/alpha", TqdmExperimentalWarning, stacklevel=2)
0
2023-12-14 07:43:03+00:00
16k
LkPrtctrd/BSL-V53
Heart/Logic/LogicLaserMessageFactory.py
[ { "identifier": "ClientHelloMessage", "path": "Heart/Packets/Client/Authentification/ClientHelloMessage.py", "snippet": "class ClientHelloMessage(PiranhaMessage):\n def __init__(self, messageData):\n super().__init__(messageData)\n self.messageVersion = 0\n\n def encode(self, fields)...
from Heart.Packets.Client.Authentification.ClientHelloMessage import ClientHelloMessage from Heart.Packets.Client.Authentification.LoginMessage import LoginMessage from Heart.Packets.Client.Battle.AskForBattleEndMessage import AskForBattleEndMessage from Heart.Packets.Client.Home.ChangeAvatarNameMessage import ChangeAvatarNameMessage from Heart.Packets.Client.Home.EndClientTurnMessage import EndClientTurnMessage from Heart.Packets.Client.Home.GoHomeFromOfflinePractiseMessage import GoHomeFromOfflinePractiseMessage from Heart.Packets.Client.Home.GoHomeMessage import GoHomeMessage from Heart.Packets.Client.Home.GetPlayerProfileMessage import GetPlayerProfileMessage from Heart.Packets.Client.Home.AskForAllianceDataMessage import AskForAllianceDataMessage from Heart.Packets.Client.Socket.KeepAliveMessage import KeepAliveMessage from Heart.Packets.Server.Authentification.LoginFailedMessage import LoginFailedMessage from Heart.Packets.Server.Authentification.LoginOkMessage import LoginOkMessage from Heart.Packets.Server.Authentification.OutOfSyncMessage import OutOfSyncMessage from Heart.Packets.Server.Authentification.ServerHelloMessage import ServerHelloMessage from Heart.Packets.Server.Battle.BattleEndMessage import BattleEndMessage from Heart.Packets.Server.Home.AvailableServerCommandMessage import AvailableServerCommandMessage from Heart.Packets.Server.Home.LobbyInfoMessage import LobbyInfoMessage from Heart.Packets.Server.Home.OwnHomeDataMessage import OwnHomeDataMessage from Heart.Packets.Server.Socket.KeepAliveServerMessage import KeepAliveServerMessage from Heart.Packets.Server.Home.PlayerProfileMessage import PlayerProfileMessage from Heart.Packets.Server.Home.MyAllianceMessage import MyAllianceMessage from Heart.Packets.Server.Home.AllianceDataMessage import AllianceDataMessage
14,187
class LogicLaserMessageFactory: messagesList = { 10055: 'AskPlayerJWTokenMessage', 10099: 'ClientCryptoErrorMessage', 10100: ClientHelloMessage, 10101: LoginMessage, 10102: 'LoginUsingSessionMessage', 10103: 'CreateAccountMessage', 10107: 'ClientCapabilitiesMessage', 10108: KeepAliveMessage, 10109: 'UdpCheckConnectionMessage', 10110: 'AnalyticEventMessage', 10111: 'AccountIdentifiersMessage', 10112: 'AuthenticationCheckMessage', 10113: 'SetDeviceTokenMessage', 10116: 'ResetAccountMessage', 10117: 'ReportUserMessage', 10118: 'AccountSwitchedMessage', 10119: 'ReportAllianceStreamMessage', 10121: 'UnlockAccountMessage', 10150: 'AppleBillingRequestMessage', 10151: 'GoogleBillingRequestMessage', 10152: 'TencentBillingRequestMessage', 10153: 'CafeBazaarBillingRequestMessage', 10159: 'KunlunBillingRequestMessage', 10160: 'BillingCancelledByClientMessage', 10177: 'ClientInfoMessage',
class LogicLaserMessageFactory: messagesList = { 10055: 'AskPlayerJWTokenMessage', 10099: 'ClientCryptoErrorMessage', 10100: ClientHelloMessage, 10101: LoginMessage, 10102: 'LoginUsingSessionMessage', 10103: 'CreateAccountMessage', 10107: 'ClientCapabilitiesMessage', 10108: KeepAliveMessage, 10109: 'UdpCheckConnectionMessage', 10110: 'AnalyticEventMessage', 10111: 'AccountIdentifiersMessage', 10112: 'AuthenticationCheckMessage', 10113: 'SetDeviceTokenMessage', 10116: 'ResetAccountMessage', 10117: 'ReportUserMessage', 10118: 'AccountSwitchedMessage', 10119: 'ReportAllianceStreamMessage', 10121: 'UnlockAccountMessage', 10150: 'AppleBillingRequestMessage', 10151: 'GoogleBillingRequestMessage', 10152: 'TencentBillingRequestMessage', 10153: 'CafeBazaarBillingRequestMessage', 10159: 'KunlunBillingRequestMessage', 10160: 'BillingCancelledByClientMessage', 10177: 'ClientInfoMessage',
10212: ChangeAvatarNameMessage,
3
2023-12-14 18:57:56+00:00
16k
pan-x-c/EE-LLM
megatron/core/models/gpt/gpt_layer_specs.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 megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add from megatron.core.fusions.fused_layer_norm import FusedLayerNorm from megatron.core.tensor_parallel.layers import ColumnParallelLinear, RowParallelLinear from megatron.core.transformer.attention import SelfAttention, SelfAttentionSubmodules from megatron.core.transformer.custom_layers.transformer_engine import ( TEDotProductAttention, TELayerNormColumnParallelLinear, TERowParallelLinear, ) from megatron.core.transformer.dot_product_attention import DotProductAttention from megatron.core.transformer.enums import AttnMaskType from megatron.core.transformer.mlp import MLP, MLPSubmodules from megatron.core.transformer.spec_utils import ModuleSpec from megatron.core.transformer.switch_mlp import SwitchMLP from megatron.core.transformer.transformer_layer import TransformerLayer, TransformerLayerSubmodules
12,878
# Use this spec to use lower level Transformer Engine modules (required for fp8 training) gpt_layer_with_transformer_engine_spec = ModuleSpec( module=TransformerLayer, submodules=TransformerLayerSubmodules( self_attention=ModuleSpec(
# Use this spec to use lower level Transformer Engine modules (required for fp8 training) gpt_layer_with_transformer_engine_spec = ModuleSpec( module=TransformerLayer, submodules=TransformerLayerSubmodules( self_attention=ModuleSpec(
module=SelfAttention,
4
2023-12-07 08:29:38+00:00
16k
tommy-xq/SA2VP
vit_train_swin.py
[ { "identifier": "create_optimizer", "path": "optim_factory.py", "snippet": "def create_optimizer(args, model, get_num_layer=None, get_layer_scale=None, filter_bias_and_bn=True, skip_list=None):\n opt_lower = args.opt.lower()\n weight_decay = args.weight_decay\n if weight_decay and filter_bias_a...
import argparse import datetime import numpy as np import time import torch import torch.nn as nn import torch.backends.cudnn as cudnn import json import os import utils import random import deepspeed from pathlib import Path from time import sleep from timm.data.mixup import Mixup from timm.models import create_model from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.utils import ModelEma from optim_factory import create_optimizer, get_parameter_groups, LayerDecayValueAssigner from datasets import build_dataset from datasets import build_beit_pretraining_dataset, build_beit_pretraining_dataset_val from engine_for_train import train_one_epoch, evaluate # engine for vit from utils import NativeScalerWithGradNormCount as NativeScaler from scipy import interpolate from timm.models.layers import trunc_normal_ from functools import partial from vpt_main.src.models.build_swin_backbone import _build_swin_model # choose model from deepspeed import DeepSpeedConfig
11,737
utils.create_ds_config(args) print(args) device = torch.device(args.device) seed = 42 torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train, args.nb_classes = build_dataset(is_train=True, args=args) if args.disable_eval_during_finetuning: dataset_val = None else: dataset_val, _ = build_dataset(is_train=False, args=args) print("Calculation of training examples = %d" % len(dataset_train)) print("Calculation of other examples = %d" % len(dataset_val)) if True: # args.distributed: num_tasks = utils.get_world_size() global_rank = utils.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=False) else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None: os.makedirs(args.log_dir, exist_ok=True) log_writer = utils.TensorboardLogger(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) if dataset_val is not None: data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=int(4*args.batch_size), num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) else: data_loader_val = None mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) model = Dual_model(args) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) frozen_parameters = sum(p.numel() for p in model.parameters() if not p.requires_grad) total_parameters = sum(p.numel() for p in model.parameters()) print('------------------------------') for name, param in model.named_parameters(): print(name, param.requires_grad) print('------------------------------') model.to(device) model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume='') print("Using EMA with decay = %.8f" % args.model_ema_decay) model_without_ddp = model # print("Model = %s" % str(model_without_ddp)) total_batch_size = args.batch_size * args.update_freq * utils.get_world_size() num_training_steps_per_epoch = len(dataset_train) // total_batch_size print("LR = %.8f" % args.lr) print("Batch size = %d" % total_batch_size) print("Update frequent = %d" % args.update_freq) print("Number of training examples = %d" % len(dataset_train)) print("Number of training training per epoch = %d" % num_training_steps_per_epoch) assigner = None if assigner is not None: print("Assigned values = %s" % str(assigner.values)) skip_weight_decay_list = None if args.enable_deepspeed: loss_scaler = None
# -------------------------------------------------------- # SA2VP: Spatially Aligned-and-Adapted Visual Prompt code # reference: # BEIT: BERT Pre-Training of Image Transformers (https://arxiv.org/abs/2106.08254) # Github source: https://github.com/microsoft/unilm/tree/master/beit # Based on timm # https://github.com/rwightman/pytorch-image-models/tree/master/timm # --------------------------------------------------------' #os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID' #os.environ['CUDA_VISIBLE_DEVICES']='0' class Dual_model(nn.Module): def __init__(self, args): super(Dual_model, self).__init__() self.vit_base, feat_dim = _build_swin_model('swinb_imagenet22k_224', 224, './backbone_ckpt') # where to save pre-trained model ./backbone_ckpt for k, p in self.vit_base.named_parameters(): name_list = k.split('.') print(name_list) if name_list[1] == 'deep_ppt' or name_list[1] == 'proj_ppt': p.requires_grad = True elif name_list[1] == '2': if name_list[2] == 'cross_attn': if name_list[4] == 'ffn' or name_list[4] == 'ffn_norm': p.requires_grad = True else: p.requires_grad = False else: p.requires_grad = False else: p.requires_grad = False self.class_head = nn.Linear(1024, args.nb_classes, bias=True) trunc_normal_(self.class_head.weight, std=0.02) def forward(self, x): x, p = self.vit_base.forward_features(x) # B*768 return self.class_head(x), self.class_head(p) def get_args(): parser = argparse.ArgumentParser('SA2VP script for image classification', add_help=False) parser.add_argument('--batch_size', default=64, type=int) parser.add_argument('--epochs', default=30, type=int) parser.add_argument('--update_freq', default=1, type=int) parser.add_argument('--save_ckpt_freq', default=50, type=int) parser.add_argument("--discrete_vae_weight_path", type=str) parser.add_argument("--discrete_vae_type", type=str, default="dall-e") # Model parameters parser.add_argument('--model', default='beit_base_patch16_224', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--rel_pos_bias', action='store_true') parser.add_argument('--disable_rel_pos_bias', action='store_false', dest='rel_pos_bias') parser.set_defaults(rel_pos_bias=False) parser.add_argument('--abs_pos_emb', action='store_true') parser.set_defaults(abs_pos_emb=True) parser.add_argument('--layer_scale_init_value', default=0.1, type=float, help="0.1 for base, 1e-5 for large. set 0 to disable layer scale") parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--second_input_size', default=112, type=int, help='images input size for discrete vae') parser.add_argument('--drop', type=float, default=0.0, metavar='PCT', help='Dropout rate (default: 0.)') parser.add_argument('--attn_drop_rate', type=float, default=0.0, metavar='PCT', help='Attention dropout rate (default: 0.)') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') parser.add_argument('--disable_eval_during_finetuning', action='store_true', default=False) parser.add_argument('--model_ema', action='store_true', default=False) parser.add_argument('--model_ema_decay', type=float, default=0.9999, help='') parser.add_argument('--model_ema_force_cpu', action='store_true', default=False, help='') # Optimizer parameters parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_argument('--opt_eps', default=1e-8, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: 1e-8)') parser.add_argument('--opt_betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='SGD momentum (default: 0.9)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--weight_decay_end', type=float, default=None, help="""Final value of the weight decay. We use a cosine schedule for WD and using a larger decay by the end of training improves performance for ViTs.""") parser.add_argument('--lr', type=float, default=5e-4, metavar='LR', help='learning rate (default: 5e-4)') parser.add_argument('--layer_decay', type=float, default=0.9) parser.add_argument('--warmup_lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 1e-6)') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_argument('--warmup_steps', type=int, default=-1, metavar='N', help='num of steps to warmup LR, will overload warmup_epochs if set > 0') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0, help='Label smoothing (default: 0)') parser.add_argument('--train_interpolation', type=str, default='bicubic', help='Training interpolation (random, bilinear, bicubic default: "bicubic")') parser.add_argument('--second_interpolation', type=str, default='lanczos', help='Interpolation for discrete vae (random, bilinear, bicubic default: "lanczos")') # Evaluation parameters parser.add_argument('--crop_pct', type=float, default=None) # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='', help='finetune from checkpoint') parser.add_argument('--model_key', default='model|module', type=str) parser.add_argument('--model_prefix', default='', type=str) parser.add_argument('--init_scale', default=0.001, type=float) parser.add_argument('--use_mean_pooling', action='store_true') parser.set_defaults(use_mean_pooling=True) parser.add_argument('--use_cls', action='store_false', dest='use_mean_pooling') parser.add_argument('--disable_weight_decay_on_rel_pos_bias', action='store_true', default=False) # Dataset parameters parser.add_argument('--data_path', default='/datasets01/imagenet_full_size/061417/', type=str, help='dataset path') parser.add_argument('--my_mode', default='train_val', type=str, help='my mode to train or test') parser.add_argument('--eval_data_path', default=None, type=str, help='dataset path for evaluation') parser.add_argument('--nb_classes', default=0, type=int, help='number of the classification types') parser.add_argument('--imagenet_default_mean_and_std', default=False, action='store_true') parser.add_argument('--data_set', default='CUB', choices=['CIFAR', 'IMNET', 'image_folder', 'CUB', 'DOG', 'FLOWER', 'CAR', 'BIRD', 'CAL101', 'DMLAB','EUROSAT','PATCH_CAMELYON','CLEVR_COUNT','CIFAR100','FOOD101','SVHN','DTD','FLOWER_S','PET','SVHN_S','SUN','Resisc45','Retinopathy','CLEVR_DISTANCE','KITTI_DISTANCE','DS_LOC','DS_ORI','SN_AZI','SN_ELE', 'DTD_DAM', 'GTSRB_DAM', 'FOOD_DAM', 'CIFAR10_DAM', 'CIFAR100_DAM', 'SVHN_DAM'], type=str, help='ImageNet dataset path') parser.add_argument('--output_dir', default='', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default=None, help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default='', help='resume from checkpoint') parser.add_argument('--auto_resume', action='store_true') parser.add_argument('--no_auto_resume', action='store_false', dest='auto_resume') parser.set_defaults(auto_resume=True) parser.add_argument('--save_ckpt', action='store_true') parser.add_argument('--no_save_ckpt', action='store_false', dest='save_ckpt') parser.set_defaults(save_ckpt=True) parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval', action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') parser.add_argument('--enable_deepspeed', action='store_true', default=False) known_args, _ = parser.parse_known_args() if known_args.enable_deepspeed: try: parser = deepspeed.add_config_arguments(parser) ds_init = deepspeed.initialize except: print("Please 'pip install deepspeed==0.4.0'") exit(0) else: ds_init = None return parser.parse_args(), ds_init def main(args, ds_init): utils.init_distributed_mode(args) if ds_init is not None: utils.create_ds_config(args) print(args) device = torch.device(args.device) seed = 42 torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train, args.nb_classes = build_dataset(is_train=True, args=args) if args.disable_eval_during_finetuning: dataset_val = None else: dataset_val, _ = build_dataset(is_train=False, args=args) print("Calculation of training examples = %d" % len(dataset_train)) print("Calculation of other examples = %d" % len(dataset_val)) if True: # args.distributed: num_tasks = utils.get_world_size() global_rank = utils.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=False) else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None: os.makedirs(args.log_dir, exist_ok=True) log_writer = utils.TensorboardLogger(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) if dataset_val is not None: data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=int(4*args.batch_size), num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) else: data_loader_val = None mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) model = Dual_model(args) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) frozen_parameters = sum(p.numel() for p in model.parameters() if not p.requires_grad) total_parameters = sum(p.numel() for p in model.parameters()) print('------------------------------') for name, param in model.named_parameters(): print(name, param.requires_grad) print('------------------------------') model.to(device) model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume='') print("Using EMA with decay = %.8f" % args.model_ema_decay) model_without_ddp = model # print("Model = %s" % str(model_without_ddp)) total_batch_size = args.batch_size * args.update_freq * utils.get_world_size() num_training_steps_per_epoch = len(dataset_train) // total_batch_size print("LR = %.8f" % args.lr) print("Batch size = %d" % total_batch_size) print("Update frequent = %d" % args.update_freq) print("Number of training examples = %d" % len(dataset_train)) print("Number of training training per epoch = %d" % num_training_steps_per_epoch) assigner = None if assigner is not None: print("Assigned values = %s" % str(assigner.values)) skip_weight_decay_list = None if args.enable_deepspeed: loss_scaler = None
optimizer_params = get_parameter_groups(
1
2023-12-12 13:19:17+00:00
16k
lumina-test/lumina
lumina/e2e_test/test_gbn.py
[ { "identifier": "get_qp_info_list", "path": "lumina/analyzer/main.py", "snippet": "def get_qp_info_list(switch_msg_snapshot):\n \"\"\" Get the list of QP info from the switch message snapshot\n\n Args:\n switch_msg_snapshot (str): The path to the switch message snapshot\n\n Returns:\n ...
import argparse, os, math, 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.gbn_check as gbn_check import lumina.analyzer.checker.read_gbn_check as read_gbn_check import lumina.orchestrator.host as host import lumina.orchestrator.switch as switch from lumina.analyzer.main import get_qp_info_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.analyzer.measurer.latency_measure import LatencyMeasure from lumina.utils.config_loggers import config_stream_handler, config_file_handler from lumina.analyzer.packet_parser.roce_packet import TRIGGER_OOS, TRIGGER_TIMEOUT
13,636
## All logs will be logged into file LOG_FILENAME LOG_FILENAME = "test_gbn.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 for the test Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: N/A """ 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 the results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: bool: True if the experiment is 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 analyze_retrans_latency(pkt, latency_measurement, is_read, logger): """ Analyze the retransmission latency breakdown for an undelivered packet Args: pkt (Packet object): The undelivered packet latency_measurement (LatencyMeasure object): A LatencyMeasure object that can compute latency breakdown is_read (bool): If we use RDMA READ in this experiment logger (logging.Logger): A logger object Returns: N/A """ # All the undelivered packets should be retransmitted in our test cases if latency_measurement.get_retransmit_pkt(pkt) == None: logger.error("\t\t No retransmit packet found for this packet") logger.error("\t\t It is possible that this undelivered packet is a redundant transmission") return retrans_latency = latency_measurement.get_retransmit_latency(pkt) if is_read == True: # For RDMA READ, we should always find a NACK READ request that triggers retransmission nack = latency_measurement.get_nack(pkt) if nack is not None: trigger = nack.get_trigger()
## All logs will be logged into file LOG_FILENAME LOG_FILENAME = "test_gbn.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 for the test Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: N/A """ 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 the results Args: orchestrator (Orchestrator object): Orchestrator object that contains all the configurations Returns: bool: True if the experiment is 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 analyze_retrans_latency(pkt, latency_measurement, is_read, logger): """ Analyze the retransmission latency breakdown for an undelivered packet Args: pkt (Packet object): The undelivered packet latency_measurement (LatencyMeasure object): A LatencyMeasure object that can compute latency breakdown is_read (bool): If we use RDMA READ in this experiment logger (logging.Logger): A logger object Returns: N/A """ # All the undelivered packets should be retransmitted in our test cases if latency_measurement.get_retransmit_pkt(pkt) == None: logger.error("\t\t No retransmit packet found for this packet") logger.error("\t\t It is possible that this undelivered packet is a redundant transmission") return retrans_latency = latency_measurement.get_retransmit_latency(pkt) if is_read == True: # For RDMA READ, we should always find a NACK READ request that triggers retransmission nack = latency_measurement.get_nack(pkt) if nack is not None: trigger = nack.get_trigger()
if trigger == TRIGGER_OOS:
9
2023-12-09 08:21:14+00:00
16k
boweniac/autogan
autogan/agents/tool_agent_search.py
[ { "identifier": "CodeExecution", "path": "autogan/tools/code_execution_tool.py", "snippet": "class CodeExecution:\n def __init__(self, work_dir: Optional[str] = None):\n \"\"\"A class for code execution\n 用于代码执行的类\n\n Supports python, bash, shell, powershell code\n 支持 pyth...
import re from collections import defaultdict from typing import Optional, Dict from autogan.tools.code_execution_tool import CodeExecution from autogan.tools.wolfram_alpha_tool import WolframAlphaAPIWrapper from autogan.oai.count_tokens_utils import count_text_tokens from autogan.agents.universal_agent import UniversalAgent from autogan.utils.compressed_text_utils import compressed_text_universal from autogan.tools.web_search_tool import WebSearch
11,604
class ToolAgentSearch(UniversalAgent): def __init__( self, search_config: Dict, agent_config: Optional[Dict] = None, retry_times: Optional[int] = 10, name: Optional[str] = "WebSearchExp", duty: Optional[str] = 'Not only can I search for information on the internet, ' 'but I can also answer questions using the Wolfram engine.', work_flow: Optional[str] = """I hope you are an internet search expert. When you receive a search request, you have the following two tools to choose from: 1. web: You can search for information on the internet. When using it, please enclose the search keywords in your output with the ```web\n ``` symbol, for example: ```web Your search keywords ``` 2. wolfram: You can use the Wolfram engine to help you calculate or query data related to Mathematics, finance, unit conversion, data analysis, science, geography, history, culture, movies, music, etc. When using it, please enclose the English question that Wolfram can understand in your output with the ```wolfram\n ``` symbol, for example: ```wolfram one wolfram query ``` Note: When you decide to use a tool, please do not @ anyone.""", # duty: Optional[str] = '我不但可以从网络上搜索资料,还可以通过 wolfram 引擎来回答问题。', # work_flow: Optional[str] = """我希望你是一个网络搜索专家,当你收到搜索请求时,你有一下两种工具可供选择: # # 1. web: 可以在网络上查找资料。使用时请在你的输出内容中,将搜索关键词用```web\n ``` 符号封装,例如: # ```web # Your search keywords # ``` # # 2.wolfram: 可以使用wolfram引擎,帮你计算或查询数学、金融、单位转换、数据分析、科学、地理、历史、文化、电影、音乐等相关数据。使用时请在你的输出内容中,将 wolfram 可以理解的英文问题用```wolfram\n ``` 符号封装,例如: # ```wolfram # one wolfram query # ``` # # 注意:当你决定使用工具时,请不要@任何人""", ): """WebSearchExpert 1.Receive the user's question and convert it into search keywords. 2.Call the Google Search API to obtain a result and extract the webpage content. 3.If no content related to the user's question is extracted, call the Google Search API again to obtain the next result. 4.Repeat operations 2 and 3 until reaching retry_times. Within the same task session domain, if the search keywords are the same, the offset of the search results will accumulate and move backwards. :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 search_config: JSON format of email_config {"cx": "", "key": ""} :param retry_times: Represent the maximum number of attempts for each search, the default is 10. :param name: The agent name should be unique in the organizational structure. :param duty: Used to explain one's job responsibilities to other agents. :param work_flow: Defines the workflow of the agent. 定义 agent 的工作流程。 """ super().__init__( name, agent_config=agent_config, duty=duty, work_flow=work_flow, use_tool="join" ) self._web_search = WebSearch(search_config["google_search"]) if "google_search" in search_config else None
class ToolAgentSearch(UniversalAgent): def __init__( self, search_config: Dict, agent_config: Optional[Dict] = None, retry_times: Optional[int] = 10, name: Optional[str] = "WebSearchExp", duty: Optional[str] = 'Not only can I search for information on the internet, ' 'but I can also answer questions using the Wolfram engine.', work_flow: Optional[str] = """I hope you are an internet search expert. When you receive a search request, you have the following two tools to choose from: 1. web: You can search for information on the internet. When using it, please enclose the search keywords in your output with the ```web\n ``` symbol, for example: ```web Your search keywords ``` 2. wolfram: You can use the Wolfram engine to help you calculate or query data related to Mathematics, finance, unit conversion, data analysis, science, geography, history, culture, movies, music, etc. When using it, please enclose the English question that Wolfram can understand in your output with the ```wolfram\n ``` symbol, for example: ```wolfram one wolfram query ``` Note: When you decide to use a tool, please do not @ anyone.""", # duty: Optional[str] = '我不但可以从网络上搜索资料,还可以通过 wolfram 引擎来回答问题。', # work_flow: Optional[str] = """我希望你是一个网络搜索专家,当你收到搜索请求时,你有一下两种工具可供选择: # # 1. web: 可以在网络上查找资料。使用时请在你的输出内容中,将搜索关键词用```web\n ``` 符号封装,例如: # ```web # Your search keywords # ``` # # 2.wolfram: 可以使用wolfram引擎,帮你计算或查询数学、金融、单位转换、数据分析、科学、地理、历史、文化、电影、音乐等相关数据。使用时请在你的输出内容中,将 wolfram 可以理解的英文问题用```wolfram\n ``` 符号封装,例如: # ```wolfram # one wolfram query # ``` # # 注意:当你决定使用工具时,请不要@任何人""", ): """WebSearchExpert 1.Receive the user's question and convert it into search keywords. 2.Call the Google Search API to obtain a result and extract the webpage content. 3.If no content related to the user's question is extracted, call the Google Search API again to obtain the next result. 4.Repeat operations 2 and 3 until reaching retry_times. Within the same task session domain, if the search keywords are the same, the offset of the search results will accumulate and move backwards. :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 search_config: JSON format of email_config {"cx": "", "key": ""} :param retry_times: Represent the maximum number of attempts for each search, the default is 10. :param name: The agent name should be unique in the organizational structure. :param duty: Used to explain one's job responsibilities to other agents. :param work_flow: Defines the workflow of the agent. 定义 agent 的工作流程。 """ super().__init__( name, agent_config=agent_config, duty=duty, work_flow=work_flow, use_tool="join" ) self._web_search = WebSearch(search_config["google_search"]) if "google_search" in search_config else None
self._wolfram_alpha = WolframAlphaAPIWrapper(
1
2023-12-06 03:24:34+00:00
16k
ebb-earl-co/tidal-wave
tidal_wave/playlist.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 types import SimpleNamespace from typing import Dict, List, Optional, Set, Tuple, Union from requests import HTTPError, Session from .media import AudioFormat from .models import ( PlaylistsEndpointResponseJSON, TracksEndpointResponseJSON, VideosEndpointResponseJSON, ) from .requesting import request_playlists from .track import Track from .utils import download_cover_image, temporary_file, TIDAL_API_URL from .video import Video import json import logging import math import shutil import sys import ffmpeg import mutagen
11,626
for subdir in subdirs: if subdir.exists(): shutil.rmtree(subdir) else: return self.playlist_dir def craft_m3u8_text(self): """This method creates a file called playlist.m3u8 in self.playlist_dir that is a standard M3U. Needs to be called after self.flatten_playlist_dir in order to be able to access self.files N.b. the already-written file is temporarily copied to a .mp4 version in a temporary directory because .m4a files cannot be read with mutagen.""" m3u_text: str = f"#EXTM3U\n#EXTENC:UTF-8\n#EXTIMG:{str(self.cover_path.absolute())}\n#PLAYLIST:{self.name}\n" logger.info( f"Creating .m3u8 playlist file for Playlist with ID '{self.playlist_id}'" ) for d in self.files: file: str = next(iter(d.values())) if file is None: continue elif file.endswith(".flac"): m = mutagen.File(file) artist: str = m.get("artist", [""])[0] title: str = m.get("title", [""])[0] extinf: str = ( f"#EXTINF:{math.ceil(m.info.length)}," f"{artist} - {title}\n{file}\n" ) m3u_text += extinf elif file.endswith(".mka"): m = mutagen.File(file) artist: str = m.get("ARTI", [""])[0] title: str = m.get("TITL", [""])[0] extinf: str = ( f"#EXTINF:{math.ceil(m.info.length)}," f"{artist} - {title}\n{file}\n" ) m3u_text += extinf elif file.endswith(".m4a"): # Mutagen cannot read .m4a files, so make a copy with all # of the metadata tags as a .mp4 in a temporary directory with temporary_file(suffix=".mp4") as tf: ffmpeg.input(file, hide_banner=None, y=None).output( tf.name, acodec="copy", vcodec="copy", loglevel="quiet", ).run() m = mutagen.File(tf.name) artist: str = m.get("\xa9ART", [""])[0] title: str = m.get("\xa9nam", [""])[0] extinf: str = ( f"#EXTINF:{math.ceil(m.info.length)}," f"{artist} - {title}\n{file}\n" ) m3u_text += extinf else: return m3u_text def dumps(self): return json.dumps(self.files) def dump(self, fp=sys.stdout): json.dump(self.files, fp) def get(self, session: Session, audio_format: AudioFormat, out_dir: Path): """The main method of this class, executing a number of other methods in a row: - self.get_metadata() - self.set_items() - self.set_dir() - self.save_cover_image() - self.save_description() - self.get_items() - self.flatten_playlist_dir() """ self.get_metadata(session) if self.metadata is None: self.files = {} return self.set_items(session) self.set_dir(out_dir) self.save_cover_image(session, out_dir) try: self.save_description() except Exception: pass _get_items = self.get_items(session, audio_format) if _get_items is None: logger.critical(f"Could not retrieve playlist with ID '{self.playlist_id}'") return self.flatten_playlist_dir() try: m3u8_text: str = self.craft_m3u8_text() except Exception as e: logger.warning( "Unable to create playlist.m3u8 file for " f"playlist with ID '{self.playlist_id}'" ) logger.debug(e) else: with open(self.playlist_dir / "playlist.m3u8", "w") as f: f.write(m3u8_text) logger.info(f"Playlist files written to '{self.playlist_dir}'") class TidalPlaylistException(Exception): pass def request_playlist_items(session: Session, playlist_id: str) -> Optional[dict]: """Request from TIDAL API /playlists/items endpoint."""
logger = logging.getLogger("__name__") @dataclass class Playlist: playlist_id: str # UUID4 def __post_init__(self): self.playlist_dir: Optional[Path] = None self.playlist_cover_saved: bool = False def get_metadata(self, session: Session): """Request from TIDAL API /playlists endpoint""" self.metadata: Optional[PlaylistsEndpointResponseJSON] = request_playlists( session=session, identifier=self.playlist_id ) if self.metadata is None: return self.name = ( self.metadata.title.replace("/", "_") .replace("|", "_") .replace(":", " -") .replace('"', "") .replace("..", "") ) def set_items(self, session: Session): """Uses data from TIDAL API /playlists/items endpoint to populate self.items""" playlist_items: Optional[PlaylistsItemsResponseJSON] = get_playlist( session=session, playlist_id=self.playlist_id ) if playlist_items is None: self.items = tuple() else: self.items: Tuple[Optional[PlaylistItem]] = tuple(playlist_items.items) def set_dir(self, out_dir: Path): """Populates self.playlist_dir based on self.name, self.playlist_id""" playlist_substring: str = f"{self.name} [{self.playlist_id}]" self.playlist_dir: Path = out_dir / "Playlists" / playlist_substring self.playlist_dir.mkdir(parents=True, exist_ok=True) def save_cover_image(self, session: Session, out_dir: Path): """Requests self.metadata.image and attempts to write it to disk""" if self.playlist_dir is None: self.set_dir(out_dir=out_dir) self.cover_path: Path = self.playlist_dir / "cover.jpg" if not self.cover_path.exists(): download_cover_image( session=session, cover_uuid=self.metadata.square_image, output_dir=self.playlist_dir, dimension=1080, ) else: self.playlist_cover_saved = True def save_description(self): """Requests self.metadata.description and attempts to write it to disk""" description_path: Path = self.playlist_dir / "PlaylistDescription.txt" if self.metadata.description is not None and len(self.metadata.description) > 0: if not description_path.exists(): description_path.write_text(f"{self.metadata.description}\n") def get_items(self, session: Session, audio_format: AudioFormat): """Using either Track.get() or Video.get(), attempt to request the data for each track or video in self.items""" if len(self.items) == 0: return tracks_videos: list = [None] * len(self.items) for i, item in enumerate(self.items): if item is None: tracks_videos[i] = None continue elif isinstance(item, TracksEndpointResponseJSON): track: Track = Track(track_id=item.id) track.get( session=session, audio_format=audio_format, out_dir=self.playlist_dir, metadata=item, ) tracks_videos[i] = track elif isinstance(item, VideosEndpointResponseJSON): video: Video = Video(video_id=item.id) video.get( session=session, out_dir=self.playlist_dir, metadata=item, ) tracks_videos[i] = video else: tracks_videos[i] = None continue else: self.tracks_videos: Tuple[ Tuple[int, Optional[Union[Track, Video]]] ] = tuple(tracks_videos) return tracks_videos def flatten_playlist_dir(self): """When self.get_items() is called, the tracks and/or videos in self.items are downloaded using their self-contained .get() logic; this means that they will be downloaded to albums. This function "flattens" self.playlist_dir, meaning that it moves all downloaded audio and video files to self.playlist_dir, and removes the various subdirectories created""" files: List[Dict[int, Optional[str]]] = [None] * len(self.tracks_videos) if len(self.tracks_videos) == 0: return subdirs: Set[Path] = set() for i, tv in enumerate(self.tracks_videos, 1): if getattr(tv, "outfile") is None: try: getattr(tv, "album_dir") except AttributeError: pass else: subdirs.add(tv.album_dir) subdirs.add(tv.album_dir.parent) files[i - 1] = {i: None} continue _path: Optional[Path] = Path(tv.outfile) if tv is not None else None # if the item never got turned into a track or video if _path is None: files[i - 1] = {i: None} continue # if the track or video didn't download if _path.exists(): if _path.stat().st_size == 0: files[i - 1] = {i: None} continue else: files[i - 1] = {i: None} continue # otherwise, move files and clean up if isinstance(tv, Track): new_path: Path = self.playlist_dir / f"{i:03d} - {tv.trackname}" new_path.write_bytes(_path.read_bytes()) _path.unlink() files[i - 1] = {i: str(new_path.absolute())} elif isinstance(tv, Video): new_path: Path = self.playlist_dir / f"{i:03d} - {_path.name}" new_path.write_bytes(_path.read_bytes()) _path.unlink() files[i - 1] = {i: str(new_path.absolute())} else: self.files: List[Dict[int, Optional[str]]] = files # Find all subdirectories written to subdirs: Set[Path] = set() for tv in self.tracks_videos: if isinstance(tv, Track): try: getattr(tv, "album_dir") except AttributeError: pass else: subdirs.add(tv.album_dir) subdirs.add(tv.album_dir.parent) elif isinstance(tv, Video): subdirs.add(tv.artist_dir) # Copy all artist images, artist bio JSON files out # of subdirs artist_images: Set[Path] = set() for subdir in subdirs: for p in subdir.glob("*.jpg"): if p.name == "cover.jpg": continue artist_images.add(p) else: for artist_image_path in artist_images: if artist_image_path.exists(): shutil.copyfile( artist_image_path.absolute(), self.playlist_dir / artist_image_path.name, ) artist_bios: Set[Path] = set() for subdir in subdirs: for p in subdir.glob("*bio.json"): artist_bios.add(p) else: for artist_bio_path in artist_bios: if artist_bio_path.exists(): shutil.copyfile( artist_bio_path.absolute(), self.playlist_dir / artist_bio_path.name, ) # Remove all subdirs for subdir in subdirs: if subdir.exists(): shutil.rmtree(subdir) else: return self.playlist_dir def craft_m3u8_text(self): """This method creates a file called playlist.m3u8 in self.playlist_dir that is a standard M3U. Needs to be called after self.flatten_playlist_dir in order to be able to access self.files N.b. the already-written file is temporarily copied to a .mp4 version in a temporary directory because .m4a files cannot be read with mutagen.""" m3u_text: str = f"#EXTM3U\n#EXTENC:UTF-8\n#EXTIMG:{str(self.cover_path.absolute())}\n#PLAYLIST:{self.name}\n" logger.info( f"Creating .m3u8 playlist file for Playlist with ID '{self.playlist_id}'" ) for d in self.files: file: str = next(iter(d.values())) if file is None: continue elif file.endswith(".flac"): m = mutagen.File(file) artist: str = m.get("artist", [""])[0] title: str = m.get("title", [""])[0] extinf: str = ( f"#EXTINF:{math.ceil(m.info.length)}," f"{artist} - {title}\n{file}\n" ) m3u_text += extinf elif file.endswith(".mka"): m = mutagen.File(file) artist: str = m.get("ARTI", [""])[0] title: str = m.get("TITL", [""])[0] extinf: str = ( f"#EXTINF:{math.ceil(m.info.length)}," f"{artist} - {title}\n{file}\n" ) m3u_text += extinf elif file.endswith(".m4a"): # Mutagen cannot read .m4a files, so make a copy with all # of the metadata tags as a .mp4 in a temporary directory with temporary_file(suffix=".mp4") as tf: ffmpeg.input(file, hide_banner=None, y=None).output( tf.name, acodec="copy", vcodec="copy", loglevel="quiet", ).run() m = mutagen.File(tf.name) artist: str = m.get("\xa9ART", [""])[0] title: str = m.get("\xa9nam", [""])[0] extinf: str = ( f"#EXTINF:{math.ceil(m.info.length)}," f"{artist} - {title}\n{file}\n" ) m3u_text += extinf else: return m3u_text def dumps(self): return json.dumps(self.files) def dump(self, fp=sys.stdout): json.dump(self.files, fp) def get(self, session: Session, audio_format: AudioFormat, out_dir: Path): """The main method of this class, executing a number of other methods in a row: - self.get_metadata() - self.set_items() - self.set_dir() - self.save_cover_image() - self.save_description() - self.get_items() - self.flatten_playlist_dir() """ self.get_metadata(session) if self.metadata is None: self.files = {} return self.set_items(session) self.set_dir(out_dir) self.save_cover_image(session, out_dir) try: self.save_description() except Exception: pass _get_items = self.get_items(session, audio_format) if _get_items is None: logger.critical(f"Could not retrieve playlist with ID '{self.playlist_id}'") return self.flatten_playlist_dir() try: m3u8_text: str = self.craft_m3u8_text() except Exception as e: logger.warning( "Unable to create playlist.m3u8 file for " f"playlist with ID '{self.playlist_id}'" ) logger.debug(e) else: with open(self.playlist_dir / "playlist.m3u8", "w") as f: f.write(m3u8_text) logger.info(f"Playlist files written to '{self.playlist_dir}'") class TidalPlaylistException(Exception): pass def request_playlist_items(session: Session, playlist_id: str) -> Optional[dict]: """Request from TIDAL API /playlists/items endpoint."""
url: str = f"{TIDAL_API_URL}/playlists/{playlist_id}/items"
8
2023-12-12 21:50:25+00:00
16k
Deltares/imod-python
imod/mf6/npf.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 warnings import numpy as np from imod.mf6.package import Package from imod.mf6.regridding_utils import RegridderType from imod.mf6.validation import PKG_DIMS_SCHEMA from imod.schemata import ( AllValueSchema, DTypeSchema, IdentityNoDataSchema, IndexesSchema, )
11,181
Default is False. save_saturation: ({True, False}, optional) keyword to indicate that cell saturation will be written to the budget file, which is specified with "BUDGET SAVE FILE" in Output Control. Saturation will be saved to the budget file as an auxiliary variable saved with the DATA-SAT text label. Saturation is a cell variable that ranges from zero to one and can be used by post processing programs to determine how much of a cell volume is saturated. If ICELLTYPE is 0, then saturation is always one. xt3d_option: ({True, False}, optional) If True, the XT3D formulation will be used. By default False. rhs_option: ({True, False}, optional) If True, then the XT3D additional terms will be added to the right-hand side. If False, then the XT3D terms will be put into the coefficient matrix. By default False. 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 = "npf" _init_schemata = { "icelltype": [ DTypeSchema(np.integer), IndexesSchema(), PKG_DIMS_SCHEMA, ], "k": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "rewet_layer": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "k22": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "k33": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "angle1": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "angle2": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "angle3": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "alternative_cell_averaging": [DTypeSchema(str)], "save_flows": [DTypeSchema(np.bool_)], "starting_head_as_confined_thickness": [DTypeSchema(np.bool_)], "variable_vertical_conductance": [DTypeSchema(np.bool_)], "dewatered": [DTypeSchema(np.bool_)], "perched": [DTypeSchema(np.bool_)], "save_specific_discharge": [DTypeSchema(np.bool_)], } _write_schemata = { "k": ( AllValueSchema(">", 0.0), IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), ), "rewet_layer": ( IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), ), "k22": ( AllValueSchema(">", 0.0), IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), # No need to check coords: dataset ensures they align with idomain. ), "k33": ( AllValueSchema(">", 0.0), IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), # No need to check coords: dataset ensures they align with idomain. ), "angle1": (IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)),), "angle2": (IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)),), "angle3": (IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)),), } _grid_data = { "icelltype": np.int32, "k": np.float64, "rewet_layer": np.float64, "k22": np.float64, "k33": np.float64, "angle1": np.float64, "angle2": np.float64, "angle3": np.float64, } _keyword_map = { "rewet": "rewet_record", "rewet_factor": "wetfct", "rewet_method": "ihdwet", "rewet_layer": "wetdry", "variable_vertical_conductance": "variablecv", "starting_head_as_confined_thickness": "thickstrt", "rewet_iterations": "iwetit", "xt3d_option": "xt3doptions", "rhs_option": "rhs", } _template = Package._initialize_template(_pkg_id) _regrid_method = {
class NodePropertyFlow(Package): """ Node Property Flow package. In this package the hydraulic conductivity and rewetting in the model is specified. A single NPF Package is required for each GWF model. https://water.usgs.gov/water-resources/software/MODFLOW-6/mf6io_6.0.4.pdf#page=51 A note about regridding: the fields k, k22, k33 define the principal components of an anisotropic conductivity tensor. By default, k and k22 are in the horizontal plane and k33 is vertical. Angle1, angle2 and angle3 define the rotation of this tensor. The regridding methods associated by default are chosen based on the assumption that k and k22 are horizontal and k33 is vertical. If this is not the case, it is up to the user to regrid the npf package using other regridding methods. This may be recommended if for example the rotation is such that k has become vertical and k33 horizontal. Parameters ---------- icelltype: array of int (xr.DataArray) flag for each cell that specifies how saturated thickness is treated. 0 means saturated thickness is held constant; >0 means saturated thickness varies with computed head when head is below the cell top; <0 means saturated thickness varies with computed head unless the starting_head_as_confined_thickness option is in effect. When starting_head_as_confined_thickness is in effect, a negative value of icelltype indicates that saturated thickness will be computed as strt-bot and held constant. k: array of floats (xr.DataArray) is the hydraulic conductivity. For the common case in which the user would like to specify the horizontal hydraulic conductivity and the vertical hydraulic conductivity, then K should be assigned as the horizontal hydraulic conductivity, K33 should be assigned as the vertical hydraulic conductivity, and K22 and the three rotation angles should not be specified. When more sophisticated anisotropy is required, then K corresponds to the K11 hydraulic conductivity axis. All included cells (idomain > 0) must have a K value greater than zero rewet: ({True, False}, optional) activates model rewetting. Default is False. rewet_layer: float is a combination of the wetting threshold and a flag to indicate which neighboring cells can cause a cell to become wet. If rewet_layer < 0, only a cell below a dry cell can cause the cell to become wet. If rewet_layer > 0, the cell below a dry cell and horizontally adjacent cells can cause a cell to become wet. If rewet_layer is 0, the cell cannot be wetted. The absolute value of rewet_layer is the wetting threshold. When the sum of BOT and the absolute value of rewet_layer at a dry cell is equaled or exceeded by the head at an adjacent cell, the cell is wetted. rewet_layer must be specified if "rewet" is specified in the OPTIONS block. If "rewet" is not specified in the options block, then rewet_layer can be entered, and memory will be allocated for it, even though it is not used. (WETDRY) Default is None. rewet_factor: is a keyword and factor that is included in the calculation of the head that is initially established at a cell when that cell is converted from dry to wet. (WETFCT) Default is None. rewet_iterations: is a keyword and iteration interval for attempting to wet cells. Wetting is attempted every rewet_iterations iteration. This applies to outer iterations and not inner iterations. If rewet_iterations is specified as zero or less, then the value is changed to 1. (IWETIT) Default is None. rewet_method: is a keyword and integer flag that determines which equation is used to define the initial head at cells that become wet. If rewet_method is 0, h = BOT + rewet_factor (hm - BOT). If rewet_method is not 0, h = BOT + rewet_factor (THRESH). (IHDWET) Default is None. k22: array of floats (xr.DataArray) is the hydraulic conductivity of the second ellipsoid axis; for an unrotated case this is the hydraulic conductivity in the y direction. If K22 is not included, then K22 is set equal to K. For a regular MODFLOW grid (DIS Package is used) in which no rotation angles are specified, K22 is the hydraulic conductivity along columns in the y direction. For an unstructured DISU grid, the user must assign principal x and y axes and provide the angle for each cell face relative to the assigned x direction. All included cells (idomain > 0) must have a K22 value greater than zero. Default is None. k33: array of floats (xr.DataArray) is the hydraulic conductivity of the third ellipsoid axis; for an unrotated case, this is the vertical hydraulic conductivity. When anisotropy is applied, K33 corresponds to the K33 tensor component. All included cells (idomain > 0) must have a K33 value greater than zero. Default is None. angle1: float is a rotation angle of the hydraulic conductivity tensor in degrees. The angle represents the first of three sequential rotations of the hydraulic conductivity ellipsoid. With the K11, K22, and K33 axes of the ellipsoid initially aligned with the x, y, and z coordinate axes, respectively, angle1 rotates the ellipsoid about its K33 axis (within the x - y plane). A positive value represents counter-clockwise rotation when viewed from any point on the positive K33 axis, looking toward the center of the ellipsoid. A value of zero indicates that the K11 axis lies within the x - z plane. If angle1 is not specified, default values of zero are assigned to angle1, angle2, and angle3, in which case the K11, K22, and K33 axes are aligned with the x, y, and z axes, respectively. Default is None. angle2: float is a rotation angle of the hydraulic conductivity tensor in degrees. The angle represents the second of three sequential rotations of the hydraulic conductivity ellipsoid. Following the rotation by angle1 described above, angle2 rotates the ellipsoid about its K22 axis (out of the x - y plane). An array can be specified for angle2 only if angle1 is also specified. A positive value of angle2 represents clockwise rotation when viewed from any point on the positive K22 axis, looking toward the center of the ellipsoid. A value of zero indicates that the K11 axis lies within the x - y plane. If angle2 is not specified, default values of zero are assigned to angle2 and angle3; connections that are not user-designated as vertical are assumed to be strictly horizontal (that is, to have no z component to their orientation); and connection lengths are based on horizontal distances. Default is None. angle3: float is a rotation angle of the hydraulic conductivity tensor in degrees. The angle represents the third of three sequential rotations of the hydraulic conductivity ellipsoid. Following the rotations by angle1 and angle2 described above, angle3 rotates the ellipsoid about its K11 axis. An array can be specified for angle3 only if angle1 and angle2 are also specified. An array must be specified for angle3 if angle2 is specified. A positive value of angle3 represents clockwise rotation when viewed from any point on the positive K11 axis, looking toward the center of the ellipsoid. A value of zero indicates that the K22 axis lies within the x - y plane. Default is None. alternative_cell_averaging : str Method calculating horizontal cell connection conductance. Options: {"LOGARITHMIC", "AMT-LMK", or "AMT-HMK"} Default: uses harmonic mean for averaging save_flows: ({True, False}, optional) keyword to indicate that cell-by-cell flow terms will be written to the file specified with "budget save file" in Output Control. Default is False. starting_head_as_confined_thickness: ({True, False}, optional) indicates that cells having a negative icelltype are confined, and their cell thickness for conductance calculations will be computed as strt-bot rather than top-bot. (THICKSTRT) Default is False. variable_vertical_conductance: ({True, False}, optional) keyword to indicate that the vertical conductance will be calculated using the saturated thickness and properties of the overlying cell and the thickness and properties of the underlying cell. if the dewatered keyword is also specified, then the vertical conductance is calculated using only the saturated thickness and properties of the overlying cell if the head in the underlying cell is below its top. if these keywords are not specified, then the default condition is to calculate the vertical conductance at the start of the simulation using the initial head and the cell properties. the vertical conductance remains constant for the entire simulation. (VARIABLECV) Default is False. dewatered: ({True, False}, optional) If the dewatered keyword is specified, then the vertical conductance is calculated using only the saturated thickness and properties of the overlying cell if the head in the underlying cell is below its top. Default is False. perched: ({True, False}, optional) keyword to indicate that when a cell is overlying a dewatered convertible cell, the head difference used in Darcy’s Law is equal to the head in the overlying cell minus the bottom elevation of the overlying cell. If not specified, then the default is to use the head difference between the two cells. Default is False. save_specific_discharge: ({True, False}, optional) keyword to indicate that x, y, and z components of specific discharge will be calculated at cell centers and written to the cell-by-cell flow file, which is specified with"budget save file" in Output Control. If this option is activated, then additional information may be required in the discretization packages and the GWF Exchange package (if GWF models are coupled). Specifically, angldegx must be specified in the connectiondata block of the disu package; angldegx must also be specified for the GWF Exchange as an auxiliary variable. disu package has not been implemented yet. Default is False. save_saturation: ({True, False}, optional) keyword to indicate that cell saturation will be written to the budget file, which is specified with "BUDGET SAVE FILE" in Output Control. Saturation will be saved to the budget file as an auxiliary variable saved with the DATA-SAT text label. Saturation is a cell variable that ranges from zero to one and can be used by post processing programs to determine how much of a cell volume is saturated. If ICELLTYPE is 0, then saturation is always one. xt3d_option: ({True, False}, optional) If True, the XT3D formulation will be used. By default False. rhs_option: ({True, False}, optional) If True, then the XT3D additional terms will be added to the right-hand side. If False, then the XT3D terms will be put into the coefficient matrix. By default False. 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 = "npf" _init_schemata = { "icelltype": [ DTypeSchema(np.integer), IndexesSchema(), PKG_DIMS_SCHEMA, ], "k": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "rewet_layer": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "k22": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "k33": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "angle1": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "angle2": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "angle3": [ DTypeSchema(np.floating), IndexesSchema(), PKG_DIMS_SCHEMA, ], "alternative_cell_averaging": [DTypeSchema(str)], "save_flows": [DTypeSchema(np.bool_)], "starting_head_as_confined_thickness": [DTypeSchema(np.bool_)], "variable_vertical_conductance": [DTypeSchema(np.bool_)], "dewatered": [DTypeSchema(np.bool_)], "perched": [DTypeSchema(np.bool_)], "save_specific_discharge": [DTypeSchema(np.bool_)], } _write_schemata = { "k": ( AllValueSchema(">", 0.0), IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), ), "rewet_layer": ( IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), ), "k22": ( AllValueSchema(">", 0.0), IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), # No need to check coords: dataset ensures they align with idomain. ), "k33": ( AllValueSchema(">", 0.0), IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)), # No need to check coords: dataset ensures they align with idomain. ), "angle1": (IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)),), "angle2": (IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)),), "angle3": (IdentityNoDataSchema(other="idomain", is_other_notnull=(">", 0)),), } _grid_data = { "icelltype": np.int32, "k": np.float64, "rewet_layer": np.float64, "k22": np.float64, "k33": np.float64, "angle1": np.float64, "angle2": np.float64, "angle3": np.float64, } _keyword_map = { "rewet": "rewet_record", "rewet_factor": "wetfct", "rewet_method": "ihdwet", "rewet_layer": "wetdry", "variable_vertical_conductance": "variablecv", "starting_head_as_confined_thickness": "thickstrt", "rewet_iterations": "iwetit", "xt3d_option": "xt3doptions", "rhs_option": "rhs", } _template = Package._initialize_template(_pkg_id) _regrid_method = {
"icelltype": (RegridderType.OVERLAP, "mean"),
1
2023-12-08 13:57:59+00:00
16k
camenduru/MotionDirector-hf
MotionDirector_train.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 argparse import datetime import logging import inspect import math import os import random import gc import copy import torch import torch.nn.functional as F import torch.utils.checkpoint import diffusers import transformers import imageio import numpy as np import itertools import bitsandbytes as bnb from typing import Dict, Optional, Tuple from omegaconf import OmegaConf from torchvision import transforms from tqdm.auto import tqdm from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed from models.unet_3d_condition import UNet3DConditionModel from diffusers.models import AutoencoderKL from diffusers import DDIMScheduler, TextToVideoSDPipeline from diffusers.optimization import get_scheduler from diffusers.utils.import_utils import is_xformers_available from diffusers.models.attention_processor import AttnProcessor2_0, Attention from diffusers.models.attention import BasicTransformerBlock from transformers import CLIPTextModel, CLIPTokenizer from transformers.models.clip.modeling_clip import CLIPEncoder from utils.dataset import VideoJsonDataset, SingleVideoDataset, \ ImageDataset, VideoFolderDataset, CachedDataset from einops import rearrange, repeat from utils.lora_handler import LoraHandler from utils.lora import extract_lora_child_module from utils.ddim_utils import ddim_inversion from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
11,373
already_printed_trainables = False logger = get_logger(__name__, log_level="INFO") def create_logging(logging, logger, accelerator): 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) def accelerate_set_verbose(accelerator): if accelerator.is_local_main_process: transformers.utils.logging.set_verbosity_warning() diffusers.utils.logging.set_verbosity_info() else: transformers.utils.logging.set_verbosity_error() diffusers.utils.logging.set_verbosity_error() def get_train_dataset(dataset_types, train_data, tokenizer): train_datasets = [] # Loop through all available datasets, get the name, then add to list of data to process.
already_printed_trainables = False logger = get_logger(__name__, log_level="INFO") def create_logging(logging, logger, accelerator): 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) def accelerate_set_verbose(accelerator): if accelerator.is_local_main_process: transformers.utils.logging.set_verbosity_warning() diffusers.utils.logging.set_verbosity_info() else: transformers.utils.logging.set_verbosity_error() diffusers.utils.logging.set_verbosity_error() def get_train_dataset(dataset_types, train_data, tokenizer): train_datasets = [] # Loop through all available datasets, get the name, then add to list of data to process.
for DataSet in [VideoJsonDataset, SingleVideoDataset, ImageDataset, VideoFolderDataset]:
1
2023-12-11 04:51:39+00:00
16k
ZS-YANG/FemtoDet-v3
projects/Detic_new/detic/detic_roi_head.py
[ { "identifier": "CascadeRoIHead", "path": "mmdet/models/roi_heads/cascade_roi_head.py", "snippet": "class CascadeRoIHead(BaseRoIHead):\n \"\"\"Cascade roi head including one bbox head and one mask head.\n\n https://arxiv.org/abs/1712.00726\n \"\"\"\n\n def __init__(self,\n nu...
from typing import List, Sequence, Tuple from mmengine.structures import InstanceData from torch import Tensor from mmdet.models.roi_heads import CascadeRoIHead from mmdet.models.task_modules.samplers import SamplingResult from mmdet.models.test_time_augs import merge_aug_masks from mmdet.models.utils import empty_instances, unpack_gt_instances from mmdet.registry import MODELS from mmdet.structures import SampleList from mmdet.structures.bbox import bbox2roi, get_box_tensor from mmdet.utils import ConfigType, InstanceList, MultiConfig import torch
10,806
# Copyright (c) OpenMMLab. All rights reserved. @MODELS.register_module() class DeticRoIHead(CascadeRoIHead): def __init__( self, *, mult_proposal_score: bool = False, with_image_labels: bool = False, add_image_box: bool = False, image_box_size: float = 1.0, ws_num_props: int = 128, add_feature_to_prop: bool = False, mask_weight: float = 1.0, one_class_per_proposal: bool = False, **kwargs, ): super().__init__(**kwargs) self.mult_proposal_score = mult_proposal_score self.with_image_labels = with_image_labels self.add_image_box = add_image_box self.image_box_size = image_box_size self.ws_num_props = ws_num_props self.add_feature_to_prop = add_feature_to_prop self.mask_weight = mask_weight self.one_class_per_proposal = one_class_per_proposal def init_mask_head(self, mask_roi_extractor: MultiConfig, mask_head: MultiConfig) -> None: """Initialize mask head and mask roi extractor. Args: mask_head (dict): Config of mask in mask head. mask_roi_extractor (:obj:`ConfigDict`, dict or list): Config of mask roi extractor. """ self.mask_head = MODELS.build(mask_head) if mask_roi_extractor is not None: self.share_roi_extractor = False self.mask_roi_extractor = MODELS.build(mask_roi_extractor) else: self.share_roi_extractor = True self.mask_roi_extractor = self.bbox_roi_extractor def _refine_roi(self, x: Tuple[Tensor], rois: Tensor, batch_img_metas: List[dict], num_proposals_per_img: Sequence[int], **kwargs) -> tuple: """Multi-stage refinement of RoI. Args: x (tuple[Tensor]): List of multi-level img features. rois (Tensor): shape (n, 5), [batch_ind, x1, y1, x2, y2] batch_img_metas (list[dict]): List of image information. num_proposals_per_img (sequence[int]): number of proposals in each image. Returns: tuple: - rois (Tensor): Refined RoI. - cls_scores (list[Tensor]): Average predicted cls score per image. - bbox_preds (list[Tensor]): Bbox branch predictions for the last stage of per image. """ # "ms" in variable names means multi-stage ms_scores = [] for stage in range(self.num_stages): bbox_results = self._bbox_forward( stage=stage, x=x, rois=rois, **kwargs) # split batch bbox prediction back to each image cls_scores = bbox_results['cls_score'].sigmoid() bbox_preds = bbox_results['bbox_pred'] rois = rois.split(num_proposals_per_img, 0) cls_scores = cls_scores.split(num_proposals_per_img, 0) ms_scores.append(cls_scores) bbox_preds = bbox_preds.split(num_proposals_per_img, 0) if stage < self.num_stages - 1: bbox_head = self.bbox_head[stage] refine_rois_list = [] for i in range(len(batch_img_metas)): if rois[i].shape[0] > 0: bbox_label = cls_scores[i][:, :-1].argmax(dim=1) # Refactor `bbox_head.regress_by_class` to only accept # box tensor without img_idx concatenated. refined_bboxes = bbox_head.regress_by_class( rois[i][:, 1:], bbox_label, bbox_preds[i], batch_img_metas[i]) refined_bboxes = get_box_tensor(refined_bboxes) refined_rois = torch.cat( [rois[i][:, [0]], refined_bboxes], dim=1) refine_rois_list.append(refined_rois) rois = torch.cat(refine_rois_list) # ms_scores aligned # average scores of each image by stages cls_scores = [ sum([score[i] for score in ms_scores]) / float(len(ms_scores)) for i in range(len(batch_img_metas)) ] # aligned return rois, cls_scores, bbox_preds def predict_bbox(self, x: Tuple[Tensor], batch_img_metas: List[dict],
# Copyright (c) OpenMMLab. All rights reserved. @MODELS.register_module() class DeticRoIHead(CascadeRoIHead): def __init__( self, *, mult_proposal_score: bool = False, with_image_labels: bool = False, add_image_box: bool = False, image_box_size: float = 1.0, ws_num_props: int = 128, add_feature_to_prop: bool = False, mask_weight: float = 1.0, one_class_per_proposal: bool = False, **kwargs, ): super().__init__(**kwargs) self.mult_proposal_score = mult_proposal_score self.with_image_labels = with_image_labels self.add_image_box = add_image_box self.image_box_size = image_box_size self.ws_num_props = ws_num_props self.add_feature_to_prop = add_feature_to_prop self.mask_weight = mask_weight self.one_class_per_proposal = one_class_per_proposal def init_mask_head(self, mask_roi_extractor: MultiConfig, mask_head: MultiConfig) -> None: """Initialize mask head and mask roi extractor. Args: mask_head (dict): Config of mask in mask head. mask_roi_extractor (:obj:`ConfigDict`, dict or list): Config of mask roi extractor. """ self.mask_head = MODELS.build(mask_head) if mask_roi_extractor is not None: self.share_roi_extractor = False self.mask_roi_extractor = MODELS.build(mask_roi_extractor) else: self.share_roi_extractor = True self.mask_roi_extractor = self.bbox_roi_extractor def _refine_roi(self, x: Tuple[Tensor], rois: Tensor, batch_img_metas: List[dict], num_proposals_per_img: Sequence[int], **kwargs) -> tuple: """Multi-stage refinement of RoI. Args: x (tuple[Tensor]): List of multi-level img features. rois (Tensor): shape (n, 5), [batch_ind, x1, y1, x2, y2] batch_img_metas (list[dict]): List of image information. num_proposals_per_img (sequence[int]): number of proposals in each image. Returns: tuple: - rois (Tensor): Refined RoI. - cls_scores (list[Tensor]): Average predicted cls score per image. - bbox_preds (list[Tensor]): Bbox branch predictions for the last stage of per image. """ # "ms" in variable names means multi-stage ms_scores = [] for stage in range(self.num_stages): bbox_results = self._bbox_forward( stage=stage, x=x, rois=rois, **kwargs) # split batch bbox prediction back to each image cls_scores = bbox_results['cls_score'].sigmoid() bbox_preds = bbox_results['bbox_pred'] rois = rois.split(num_proposals_per_img, 0) cls_scores = cls_scores.split(num_proposals_per_img, 0) ms_scores.append(cls_scores) bbox_preds = bbox_preds.split(num_proposals_per_img, 0) if stage < self.num_stages - 1: bbox_head = self.bbox_head[stage] refine_rois_list = [] for i in range(len(batch_img_metas)): if rois[i].shape[0] > 0: bbox_label = cls_scores[i][:, :-1].argmax(dim=1) # Refactor `bbox_head.regress_by_class` to only accept # box tensor without img_idx concatenated. refined_bboxes = bbox_head.regress_by_class( rois[i][:, 1:], bbox_label, bbox_preds[i], batch_img_metas[i]) refined_bboxes = get_box_tensor(refined_bboxes) refined_rois = torch.cat( [rois[i][:, [0]], refined_bboxes], dim=1) refine_rois_list.append(refined_rois) rois = torch.cat(refine_rois_list) # ms_scores aligned # average scores of each image by stages cls_scores = [ sum([score[i] for score in ms_scores]) / float(len(ms_scores)) for i in range(len(batch_img_metas)) ] # aligned return rois, cls_scores, bbox_preds def predict_bbox(self, x: Tuple[Tensor], batch_img_metas: List[dict],
rpn_results_list: InstanceList,
9
2023-12-11 15:23:03+00:00
16k
merlresearch/PixPNet
pixpnet/protonets/lit_model.py
[ { "identifier": "get_metadata", "path": "pixpnet/data.py", "snippet": "def get_metadata(config):\n dataset = config.dataset.name.upper().replace(\"-\", \"\")\n metadata = DatasetMeta(\n output_size=DATA_NUM_OUTPUTS[dataset],\n input_channels=DATA_CHANNELS[dataset],\n input_siz...
import argparse import torch from typing import Tuple from torch import nn from torchmetrics import Accuracy from pytorch_lightning.loops import FitLoop from pytorch_lightning.loops.fit_loop import _FitLoop as FitLoop from pytorch_lightning import LightningModule, Trainer from pytorch_lightning.loggers import TensorBoardLogger from pixpnet.data import get_metadata from pixpnet.lightning.lightning_data import LitData from pixpnet.lightning.lit_module import BaseLitModel from pixpnet.optim import get_optimizer_cls, get_scheduler from pixpnet.protonets.loss import ClusterLoss, L1ReadoutLoss, SeparationLoss from pixpnet.protonets.models.protonet import ProtoNet, protonet from pixpnet.protonets.push import push_prototypes from pixpnet.utils import get_logger, intersect_func_and_kwargs
11,497
# Copyright (c) 2022-2023 Mitsubishi Electric Research Laboratories (MERL) # # SPDX-License-Identifier: AGPL-3.0-or-later try: except ImportError: logger = get_logger(__name__) def params_with_grad(parameters): return filter(lambda p: p.requires_grad, parameters) def make_optimizers_proto( model: ProtoNet, config: argparse.Namespace, ) -> Tuple[torch.optim.Optimizer, ...]: """""" optimizer_cls, hparams = get_optimizer_cls(config, ignore={"fine_tune_lr", "readout_lr"}) readout_params = None if model.last_layer is not None: readout_params = [ { "params": params_with_grad(model.last_layer.parameters()), "lr": config.optimizer.readout_lr, "weight_decay": 0, }, ] all_params = [ # feature extractor {"params": params_with_grad(model.features.parameters()), "lr": config.optimizer.fine_tune_lr}, # add on layers {"params": params_with_grad(model.add_on_layers.parameters())}, # prototype layers {"params": params_with_grad([model.prototype_vectors]), "weight_decay": 0}, ] readout_optimizer = None if readout_params is not None: all_params += readout_params readout_optimizer = optimizer_cls(params=readout_params, **hparams) optimizer = optimizer_cls(params=all_params, **hparams) return optimizer, readout_optimizer def _set_grad(model, features=True, add_on_layers=True, prototype_vectors=True, last_layer=True): for p in model.features.parameters(): p.requires_grad = features for p in model.add_on_layers.parameters(): p.requires_grad = add_on_layers model.prototype_vectors.requires_grad = prototype_vectors if model.last_layer is not None: for p in model.last_layer.parameters(): p.requires_grad = last_layer def last_only(model): _set_grad(model, features=False, add_on_layers=False, prototype_vectors=False) def warm_only(model): _set_grad(model, features=False) def joint(model): _set_grad(model) class ProtoLitModel(BaseLitModel): def __init__(self, config, feature_extractor=None): super().__init__(config) metadata = get_metadata(config) self.num_classes = metadata.output_size self.input_size = metadata.input_size hparams, invalid_keys = intersect_func_and_kwargs( protonet, config.model, exclude_func_args={"num_classes"}, exclude_kwargs={"name"}, ) if invalid_keys: logger.warning( f"Will not pass the following invalid model " f"hyperparameters to {protonet.__name__}: " f'{", ".join(invalid_keys)}' ) logger.info(f"Model hyperparameters for {protonet.__name__}: " f"{hparams}") if feature_extractor is not None: logger.info( f"feature_extractor is not None, ignoring config " f'option of {hparams.get("feature_extractor")}' ) hparams["feature_extractor"] = feature_extractor self.model = protonet(num_classes=self.num_classes, input_size=self.input_size, **hparams) self.lr_scheduler = None self.readout_optimizer = self.lr_scheduler_configs = None # losses self.xent = self._metric_per_split(nn.CrossEntropyLoss) class_specific = self.config.model.class_specific
# Copyright (c) 2022-2023 Mitsubishi Electric Research Laboratories (MERL) # # SPDX-License-Identifier: AGPL-3.0-or-later try: except ImportError: logger = get_logger(__name__) def params_with_grad(parameters): return filter(lambda p: p.requires_grad, parameters) def make_optimizers_proto( model: ProtoNet, config: argparse.Namespace, ) -> Tuple[torch.optim.Optimizer, ...]: """""" optimizer_cls, hparams = get_optimizer_cls(config, ignore={"fine_tune_lr", "readout_lr"}) readout_params = None if model.last_layer is not None: readout_params = [ { "params": params_with_grad(model.last_layer.parameters()), "lr": config.optimizer.readout_lr, "weight_decay": 0, }, ] all_params = [ # feature extractor {"params": params_with_grad(model.features.parameters()), "lr": config.optimizer.fine_tune_lr}, # add on layers {"params": params_with_grad(model.add_on_layers.parameters())}, # prototype layers {"params": params_with_grad([model.prototype_vectors]), "weight_decay": 0}, ] readout_optimizer = None if readout_params is not None: all_params += readout_params readout_optimizer = optimizer_cls(params=readout_params, **hparams) optimizer = optimizer_cls(params=all_params, **hparams) return optimizer, readout_optimizer def _set_grad(model, features=True, add_on_layers=True, prototype_vectors=True, last_layer=True): for p in model.features.parameters(): p.requires_grad = features for p in model.add_on_layers.parameters(): p.requires_grad = add_on_layers model.prototype_vectors.requires_grad = prototype_vectors if model.last_layer is not None: for p in model.last_layer.parameters(): p.requires_grad = last_layer def last_only(model): _set_grad(model, features=False, add_on_layers=False, prototype_vectors=False) def warm_only(model): _set_grad(model, features=False) def joint(model): _set_grad(model) class ProtoLitModel(BaseLitModel): def __init__(self, config, feature_extractor=None): super().__init__(config) metadata = get_metadata(config) self.num_classes = metadata.output_size self.input_size = metadata.input_size hparams, invalid_keys = intersect_func_and_kwargs( protonet, config.model, exclude_func_args={"num_classes"}, exclude_kwargs={"name"}, ) if invalid_keys: logger.warning( f"Will not pass the following invalid model " f"hyperparameters to {protonet.__name__}: " f'{", ".join(invalid_keys)}' ) logger.info(f"Model hyperparameters for {protonet.__name__}: " f"{hparams}") if feature_extractor is not None: logger.info( f"feature_extractor is not None, ignoring config " f'option of {hparams.get("feature_extractor")}' ) hparams["feature_extractor"] = feature_extractor self.model = protonet(num_classes=self.num_classes, input_size=self.input_size, **hparams) self.lr_scheduler = None self.readout_optimizer = self.lr_scheduler_configs = None # losses self.xent = self._metric_per_split(nn.CrossEntropyLoss) class_specific = self.config.model.class_specific
self.l1 = self._metric_per_split(L1ReadoutLoss, class_specific=class_specific)
6
2023-12-06 23:49:31+00:00
16k
open-mmlab/PIA
animatediff/pipelines/i2v_pipeline.py
[ { "identifier": "InflatedConv3d", "path": "animatediff/models/resnet.py", "snippet": "class InflatedConv3d(nn.Conv2d):\n def forward(self, x):\n video_length = x.shape[2]\n\n x = rearrange(x, \"b c f h w -> (b f) c h w\")\n x = super().forward(x)\n x = rearrange(x, \"(b f)...
import inspect import os.path as osp import numpy as np import torch from dataclasses import dataclass from typing import Callable, List, Optional, Union from diffusers.configuration_utils import FrozenDict from diffusers.loaders import IPAdapterMixin, TextualInversionLoaderMixin from diffusers.models import AutoencoderKL from diffusers.pipelines import DiffusionPipeline from diffusers.schedulers import (DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler) from diffusers.utils import (BaseOutput, deprecate, is_accelerate_available, logging) from diffusers.utils.import_utils import is_xformers_available from einops import rearrange from omegaconf import OmegaConf from packaging import version from safetensors import safe_open from tqdm import tqdm from transformers import (CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection) from animatediff.models.resnet import InflatedConv3d from animatediff.models.unet import UNet3DConditionModel from animatediff.utils.convert_from_ckpt import (convert_ldm_clip_checkpoint, convert_ldm_unet_checkpoint, convert_ldm_vae_checkpoint) from animatediff.utils.convert_lora_safetensor_to_diffusers import \ convert_lora_model_level from animatediff.utils.util import prepare_mask_coef_by_statistics from accelerate import cpu_offload
13,276
class I2VPipeline(DiffusionPipeline, IPAdapterMixin, TextualInversionLoaderMixin): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet3DConditionModel, scheduler: Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ], # memory_format: torch.memory_format, feature_extractor: CLIPImageProcessor = None, image_encoder: CLIPVisionModelWithProjection = None, ): super().__init__() if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["steps_offset"] = 1 scheduler._internal_dict = FrozenDict(new_config) if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." " `clip_sample` should be set to False in the configuration file. Please make sure to update the" " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" ) deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["clip_sample"] = False scheduler._internal_dict = FrozenDict(new_config) is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( version.parse(unet.config._diffusers_version).base_version ) < version.parse("0.9.0.dev0") is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: deprecation_message = ( "The configuration file of the unet has set the default `sample_size` to smaller than" " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" " in the config might lead to incorrect results in future versions. If you have downloaded this" " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" " the `unet/config.json` file" ) deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(unet.config) new_config["sample_size"] = 64 unet._internal_dict = FrozenDict(new_config) self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, image_encoder=image_encoder, feature_extractor=feature_extractor, scheduler=scheduler, ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) # self.memory_format = memory_format self.use_ip_adapter = False @classmethod def build_pipeline(cls, base_cfg, base_model: str, unet_path: str, dreambooth_path: Optional[str] = None, lora_path: Optional[str] = None, lora_alpha: float = 0, vae_path: Optional[str] = None, ip_adapter_path: Optional[str] = None, ip_adapter_scale: float = 0.0, only_load_vae_decoder: bool = False, only_load_vae_encoder: bool = False) -> 'I2VPipeline': """Method to build pipeline in a faster way~ Args: base_cfg: The config to build model base_mode: The model id to initialize StableDiffusion unet_path: Path for i2v unet dreambooth_path: path for dreambooth model lora_path: path for lora model lora_alpha: value for lora scale only_load_vae_decoder: Only load VAE decoder from dreambooth / VAE ckpt and maitain encoder as original. """ # build unet unet = UNet3DConditionModel.from_pretrained_2d( base_model, subfolder="unet", unet_additional_kwargs=OmegaConf.to_container( base_cfg.unet_additional_kwargs)) old_weights = unet.conv_in.weight old_bias = unet.conv_in.bias
# Adapted from https://github.com/showlab/Tune-A-Video/blob/main/tuneavideo/pipelines/pipeline_tuneavideo.py logger = logging.get_logger(__name__) # pylint: disable=invalid-name DEFAULT_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') @dataclass class AnimationPipelineOutput(BaseOutput): videos: Union[torch.Tensor, np.ndarray] class I2VPipeline(DiffusionPipeline, IPAdapterMixin, TextualInversionLoaderMixin): _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNet3DConditionModel, scheduler: Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ], # memory_format: torch.memory_format, feature_extractor: CLIPImageProcessor = None, image_encoder: CLIPVisionModelWithProjection = None, ): super().__init__() if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["steps_offset"] = 1 scheduler._internal_dict = FrozenDict(new_config) if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: deprecation_message = ( f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." " `clip_sample` should be set to False in the configuration file. Please make sure to update the" " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" ) deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(scheduler.config) new_config["clip_sample"] = False scheduler._internal_dict = FrozenDict(new_config) is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse( version.parse(unet.config._diffusers_version).base_version ) < version.parse("0.9.0.dev0") is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: deprecation_message = ( "The configuration file of the unet has set the default `sample_size` to smaller than" " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the" " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" " in the config might lead to incorrect results in future versions. If you have downloaded this" " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" " the `unet/config.json` file" ) deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False) new_config = dict(unet.config) new_config["sample_size"] = 64 unet._internal_dict = FrozenDict(new_config) self.register_modules( vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, image_encoder=image_encoder, feature_extractor=feature_extractor, scheduler=scheduler, ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) # self.memory_format = memory_format self.use_ip_adapter = False @classmethod def build_pipeline(cls, base_cfg, base_model: str, unet_path: str, dreambooth_path: Optional[str] = None, lora_path: Optional[str] = None, lora_alpha: float = 0, vae_path: Optional[str] = None, ip_adapter_path: Optional[str] = None, ip_adapter_scale: float = 0.0, only_load_vae_decoder: bool = False, only_load_vae_encoder: bool = False) -> 'I2VPipeline': """Method to build pipeline in a faster way~ Args: base_cfg: The config to build model base_mode: The model id to initialize StableDiffusion unet_path: Path for i2v unet dreambooth_path: path for dreambooth model lora_path: path for lora model lora_alpha: value for lora scale only_load_vae_decoder: Only load VAE decoder from dreambooth / VAE ckpt and maitain encoder as original. """ # build unet unet = UNet3DConditionModel.from_pretrained_2d( base_model, subfolder="unet", unet_additional_kwargs=OmegaConf.to_container( base_cfg.unet_additional_kwargs)) old_weights = unet.conv_in.weight old_bias = unet.conv_in.bias
new_conv1 = InflatedConv3d(
0
2023-12-21 03:29:34+00:00
16k
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
11,166
# 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( batch_data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset ) if self.stability_score_thresh > 0.0: keep_mask = batch_data["stability_score"] >= self.stability_score_thresh batch_data.filter(keep_mask) if need_high: batch_data["high_masks"] = batch_data["masks"] > self.high_score_thresh batch_data["masks"] = batch_data["masks"] > self.predictor.model.mask_threshold batch_data["boxes"] = batched_mask_to_box(batch_data["masks"]) keep_mask = ~is_box_near_crop_edge(batch_data["boxes"], [0, 0, orig_w, orig_h], [0, 0, orig_w, orig_h]) if not torch.all(keep_mask): batch_data.filter(keep_mask) # Compress to RLE batch_data["rles"] = mask_to_rle_pytorch(batch_data["masks"]) data.cat(batch_data) del batch_data if need_high: high_masks = data["high_masks"] or_results = torch.zeros([high_masks.shape[1], high_masks.shape[2]]).to(high_masks.device) for mask in high_masks: or_results = torch.logical_or(or_results, mask) del data["high_masks"] or_results = or_results.permute(1, 0) del data['masks'] return data, or_results else: del data['masks'] return data @torch.no_grad() def reset_image(self): self.predictor.reset_image() @torch.no_grad() def post_process(self, image: np.ndarray, data: MaskData) -> List[Dict[str, Any]]: orig_size = image.shape[:2] orig_h, orig_w = orig_size keep_by_nms = batched_nms( data["boxes"].float(), data["iou_preds"], torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: data = self.postprocess_small_regions( data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": data["segmentations"] = [coco_encode_rle(rle) for rle in data["rles"]] elif self.output_mode == "binary_mask": data["segmentations"] = [rle_to_mask(rle) for rle in data["rles"]] else: data["segmentations"] = data["rles"] # Write mask records curr_anns = [] for idx in range(len(data["segmentations"])): ann = { "segmentation": data["segmentations"][idx], "area": area_from_rle(data["rles"][idx]), "bbox": box_xyxy_to_xywh(data["boxes"][idx]).tolist(), "predicted_iou": data["iou_preds"][idx].item(), "point_coords": [data["points"][idx].tolist()], "stability_score": data["stability_score"][idx].item(), } curr_anns.append(ann) # print("post use time: {}".format(time.time() - st)) return curr_anns @staticmethod def postprocess_small_regions( mask_data: MaskData, min_area: int, nms_thresh: float ) -> MaskData: """ Removes small disconnected regions and holes in masks, then reruns box NMS to remove any new duplicates. Edits mask_data in place. Requires open-cv as a dependency. """ if len(mask_data["rles"]) == 0: return mask_data # Filter small disconnected regions and holes new_masks = [] scores = [] for rle in mask_data["rles"]: mask = rle_to_mask(rle)
# 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( batch_data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset ) if self.stability_score_thresh > 0.0: keep_mask = batch_data["stability_score"] >= self.stability_score_thresh batch_data.filter(keep_mask) if need_high: batch_data["high_masks"] = batch_data["masks"] > self.high_score_thresh batch_data["masks"] = batch_data["masks"] > self.predictor.model.mask_threshold batch_data["boxes"] = batched_mask_to_box(batch_data["masks"]) keep_mask = ~is_box_near_crop_edge(batch_data["boxes"], [0, 0, orig_w, orig_h], [0, 0, orig_w, orig_h]) if not torch.all(keep_mask): batch_data.filter(keep_mask) # Compress to RLE batch_data["rles"] = mask_to_rle_pytorch(batch_data["masks"]) data.cat(batch_data) del batch_data if need_high: high_masks = data["high_masks"] or_results = torch.zeros([high_masks.shape[1], high_masks.shape[2]]).to(high_masks.device) for mask in high_masks: or_results = torch.logical_or(or_results, mask) del data["high_masks"] or_results = or_results.permute(1, 0) del data['masks'] return data, or_results else: del data['masks'] return data @torch.no_grad() def reset_image(self): self.predictor.reset_image() @torch.no_grad() def post_process(self, image: np.ndarray, data: MaskData) -> List[Dict[str, Any]]: orig_size = image.shape[:2] orig_h, orig_w = orig_size keep_by_nms = batched_nms( data["boxes"].float(), data["iou_preds"], torch.zeros_like(data["boxes"][:, 0]), # categories iou_threshold=self.box_nms_thresh, ) data.filter(keep_by_nms) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: data = self.postprocess_small_regions( data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": data["segmentations"] = [coco_encode_rle(rle) for rle in data["rles"]] elif self.output_mode == "binary_mask": data["segmentations"] = [rle_to_mask(rle) for rle in data["rles"]] else: data["segmentations"] = data["rles"] # Write mask records curr_anns = [] for idx in range(len(data["segmentations"])): ann = { "segmentation": data["segmentations"][idx], "area": area_from_rle(data["rles"][idx]), "bbox": box_xyxy_to_xywh(data["boxes"][idx]).tolist(), "predicted_iou": data["iou_preds"][idx].item(), "point_coords": [data["points"][idx].tolist()], "stability_score": data["stability_score"][idx].item(), } curr_anns.append(ann) # print("post use time: {}".format(time.time() - st)) return curr_anns @staticmethod def postprocess_small_regions( mask_data: MaskData, min_area: int, nms_thresh: float ) -> MaskData: """ Removes small disconnected regions and holes in masks, then reruns box NMS to remove any new duplicates. Edits mask_data in place. Requires open-cv as a dependency. """ if len(mask_data["rles"]) == 0: return mask_data # Filter small disconnected regions and holes new_masks = [] scores = [] for rle in mask_data["rles"]: mask = rle_to_mask(rle)
mask, changed = remove_small_regions(mask, min_area, mode="holes")
13
2023-12-19 11:25:54+00:00
16k
DeepWok/mase
machop/chop/passes/graph/transforms/verilog/emit_tb.py
[ { "identifier": "emit_data_in_tb_sv", "path": "machop/chop/passes/graph/transforms/verilog/emit_tb_data_in.py", "snippet": "def emit_data_in_tb_sv(data_width, load_path, out_file):\n buff = f\"\"\"\n`timescale 1 ns / 1 ps\n\nmodule AESL_autofifo_data_in_V (\n clk,\n reset,\n if_empty_n,\n ...
import math, time, os, logging, torch, glob, shutil from chop.passes.graph.utils import vf, v2p, init_project from chop.passes.graph.transforms.quantize.quantizers import integer_quantizer_for_hw from .emit_tb_data_in import emit_data_in_tb_sv, emit_data_in_tb_dat from .emit_tb_data_out import emit_data_out_tb_sv, emit_data_out_tb_dat from .emit_tb_testbench import emit_top_tb from pathlib import Path
12,382
logger = logging.getLogger(__name__) def emit_tb_verilog(graph, trans_num=1, project_dir="top"): sim_dir = os.path.join(project_dir, "hardware", "sim") tv_dir = os.path.join(sim_dir, "tv") if not os.path.exists(tv_dir): os.mkdir(tv_dir) v_dir = os.path.join(sim_dir, "verilog") if not os.path.exists(v_dir): os.mkdir(v_dir) # TODO : need to emit all the inputs v_in_param = graph.nodes_in[0].meta["mase"].parameters["hardware"]["verilog_param"] w_in_param = graph.nodes_in[0].meta["mase"].parameters["common"]["args"] in_width = w_in_param["data_in_0"]["precision"][0] in_size = v_in_param["DATA_IN_0_TENSOR_SIZE_DIM_0"] data_width = in_width * in_size # TODO : need to check addr_width = 1 depth = 1 load_path = os.path.join(tv_dir, f"sw_data_in.dat") out_file = os.path.join(v_dir, f"top_data_in_fifo.sv") emit_data_in_tb_sv(data_width, load_path, out_file) v_out_param = ( graph.nodes_out[0].meta["mase"].parameters["hardware"]["verilog_param"] ) w_out_param = graph.nodes_in[0].meta["mase"].parameters["common"]["results"] out_width = w_out_param["data_out_0"]["precision"][0] out_size = v_out_param["DATA_OUT_0_TENSOR_SIZE_0_DIM_0"] data_width = out_width * out_size # TODO : need to check addr_width = 1 depth = 1 load_path = os.path.join(tv_dir, f"sw_data_out.dat") store_path = os.path.join(tv_dir, f"hw_data_out.dat") out_file = os.path.join(v_dir, f"top_data_out_fifo.sv")
logger = logging.getLogger(__name__) def emit_tb_verilog(graph, trans_num=1, project_dir="top"): sim_dir = os.path.join(project_dir, "hardware", "sim") tv_dir = os.path.join(sim_dir, "tv") if not os.path.exists(tv_dir): os.mkdir(tv_dir) v_dir = os.path.join(sim_dir, "verilog") if not os.path.exists(v_dir): os.mkdir(v_dir) # TODO : need to emit all the inputs v_in_param = graph.nodes_in[0].meta["mase"].parameters["hardware"]["verilog_param"] w_in_param = graph.nodes_in[0].meta["mase"].parameters["common"]["args"] in_width = w_in_param["data_in_0"]["precision"][0] in_size = v_in_param["DATA_IN_0_TENSOR_SIZE_DIM_0"] data_width = in_width * in_size # TODO : need to check addr_width = 1 depth = 1 load_path = os.path.join(tv_dir, f"sw_data_in.dat") out_file = os.path.join(v_dir, f"top_data_in_fifo.sv") emit_data_in_tb_sv(data_width, load_path, out_file) v_out_param = ( graph.nodes_out[0].meta["mase"].parameters["hardware"]["verilog_param"] ) w_out_param = graph.nodes_in[0].meta["mase"].parameters["common"]["results"] out_width = w_out_param["data_out_0"]["precision"][0] out_size = v_out_param["DATA_OUT_0_TENSOR_SIZE_0_DIM_0"] data_width = out_width * out_size # TODO : need to check addr_width = 1 depth = 1 load_path = os.path.join(tv_dir, f"sw_data_out.dat") store_path = os.path.join(tv_dir, f"hw_data_out.dat") out_file = os.path.join(v_dir, f"top_data_out_fifo.sv")
emit_data_out_tb_sv(data_width, load_path, store_path, out_file)
2
2023-12-18 12:50:53+00:00
16k
OPPOMKLab/u-LLaVA
models/GroundingDINO/groundingdino/models/GroundingDINO/groundingdino.py
[ { "identifier": "box_ops", "path": "models/GroundingDINO/groundingdino/util/box_ops.py", "snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef box_iou_pairwise(boxes1, boxes2):\ndef generalized_box_iou_pairwise(box...
import copy import torch import torch.nn.functional as F from typing import List from torch import nn from torchvision.ops.boxes import nms from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast from models.GroundingDINO.groundingdino.util import box_ops, get_tokenlizer from models.GroundingDINO.groundingdino.util.misc import ( NestedTensor, accuracy, get_world_size, interpolate, inverse_sigmoid, is_dist_avail_and_initialized, nested_tensor_from_tensor_list, ) from models.GroundingDINO.groundingdino.util.utils import get_phrases_from_posmap from models.GroundingDINO.groundingdino.util.visualizer import COCOVisualizer from models.GroundingDINO.groundingdino.util.vl_utils import create_positive_map_from_span from ..registry import MODULE_BUILD_FUNCS from .backbone import build_backbone from .bertwarper import ( BertModelWarper, generate_masks_with_special_tokens, generate_masks_with_special_tokens_and_transfer_map, ) from .transformer import build_transformer from .utils import MLP, ContrastiveEmbed, sigmoid_focal_loss
10,986
# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ class GroundingDINO(nn.Module): """This is the Cross-Attention Detector module that performs object detection""" def __init__( self, backbone, transformer, num_queries, aux_loss=False, iter_update=False, query_dim=2, num_feature_levels=1, nheads=8, # two stage two_stage_type="no", # ['no', 'standard'] dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, num_patterns=0, dn_number=100, dn_box_noise_scale=0.4, dn_label_noise_ratio=0.5, dn_labelbook_size=100, text_encoder_type="bert-base-uncased", sub_sentence_present=True, max_text_len=256, ): """Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_queries: number of object queries, ie detection slot. This is the maximal number of objects Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.hidden_dim = hidden_dim = transformer.d_model self.num_feature_levels = num_feature_levels self.nheads = nheads self.max_text_len = 256 self.sub_sentence_present = sub_sentence_present # setting query dim self.query_dim = query_dim assert query_dim == 4 # for dn training self.num_patterns = num_patterns self.dn_number = dn_number self.dn_box_noise_scale = dn_box_noise_scale self.dn_label_noise_ratio = dn_label_noise_ratio self.dn_labelbook_size = dn_labelbook_size # bert self.tokenizer = get_tokenlizer.get_tokenlizer(text_encoder_type) self.bert = get_tokenlizer.get_pretrained_language_model(text_encoder_type) self.bert.pooler.dense.weight.requires_grad_(False) self.bert.pooler.dense.bias.requires_grad_(False) self.bert = BertModelWarper(bert_model=self.bert) self.feat_map = nn.Linear(self.bert.config.hidden_size, self.hidden_dim, bias=True) nn.init.constant_(self.feat_map.bias.data, 0) nn.init.xavier_uniform_(self.feat_map.weight.data) # freeze # special tokens self.specical_tokens = self.tokenizer.convert_tokens_to_ids(["[CLS]", "[SEP]", ".", "?"]) # prepare input projection layers if num_feature_levels > 1: num_backbone_outs = len(backbone.num_channels) input_proj_list = [] for _ in range(num_backbone_outs): in_channels = backbone.num_channels[_] input_proj_list.append( nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), ) ) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append( nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, hidden_dim), ) ) in_channels = hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: assert two_stage_type == "no", "two_stage_type should be no if num_feature_levels=1 !!!" self.input_proj = nn.ModuleList( [ nn.Sequential( nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), ) ] ) self.backbone = backbone self.aux_loss = aux_loss self.box_pred_damping = box_pred_damping = None self.iter_update = iter_update assert iter_update, "Why not iter_update?" # prepare pred layers self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share # prepare class & box embed
# ------------------------------------------------------------------------ # Grounding DINO # url: https://github.com/IDEA-Research/GroundingDINO # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR model and criterion classes. # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ class GroundingDINO(nn.Module): """This is the Cross-Attention Detector module that performs object detection""" def __init__( self, backbone, transformer, num_queries, aux_loss=False, iter_update=False, query_dim=2, num_feature_levels=1, nheads=8, # two stage two_stage_type="no", # ['no', 'standard'] dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, num_patterns=0, dn_number=100, dn_box_noise_scale=0.4, dn_label_noise_ratio=0.5, dn_labelbook_size=100, text_encoder_type="bert-base-uncased", sub_sentence_present=True, max_text_len=256, ): """Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_queries: number of object queries, ie detection slot. This is the maximal number of objects Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.hidden_dim = hidden_dim = transformer.d_model self.num_feature_levels = num_feature_levels self.nheads = nheads self.max_text_len = 256 self.sub_sentence_present = sub_sentence_present # setting query dim self.query_dim = query_dim assert query_dim == 4 # for dn training self.num_patterns = num_patterns self.dn_number = dn_number self.dn_box_noise_scale = dn_box_noise_scale self.dn_label_noise_ratio = dn_label_noise_ratio self.dn_labelbook_size = dn_labelbook_size # bert self.tokenizer = get_tokenlizer.get_tokenlizer(text_encoder_type) self.bert = get_tokenlizer.get_pretrained_language_model(text_encoder_type) self.bert.pooler.dense.weight.requires_grad_(False) self.bert.pooler.dense.bias.requires_grad_(False) self.bert = BertModelWarper(bert_model=self.bert) self.feat_map = nn.Linear(self.bert.config.hidden_size, self.hidden_dim, bias=True) nn.init.constant_(self.feat_map.bias.data, 0) nn.init.xavier_uniform_(self.feat_map.weight.data) # freeze # special tokens self.specical_tokens = self.tokenizer.convert_tokens_to_ids(["[CLS]", "[SEP]", ".", "?"]) # prepare input projection layers if num_feature_levels > 1: num_backbone_outs = len(backbone.num_channels) input_proj_list = [] for _ in range(num_backbone_outs): in_channels = backbone.num_channels[_] input_proj_list.append( nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), ) ) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append( nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, hidden_dim), ) ) in_channels = hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: assert two_stage_type == "no", "two_stage_type should be no if num_feature_levels=1 !!!" self.input_proj = nn.ModuleList( [ nn.Sequential( nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), ) ] ) self.backbone = backbone self.aux_loss = aux_loss self.box_pred_damping = box_pred_damping = None self.iter_update = iter_update assert iter_update, "Why not iter_update?" # prepare pred layers self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share # prepare class & box embed
_class_embed = ContrastiveEmbed()
19
2023-12-21 08:10:23+00:00
16k
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
12,105
log["diffusion_row"] = diffusion_grid if sample: # get denoise row with ema_scope("Sampling"): samples, z_denoise_row = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, ) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if ( quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(self.first_stage_model, IdentityFirstStage) ): # also display when quantizing x0 while sampling with ema_scope("Plotting Quantized Denoised"): samples, z_denoise_row = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, quantize_denoised=True, ) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True, # quantize_denoised=True) x_samples = self.decode_first_stage(samples.to(self.device)) log["samples_x0_quantized"] = x_samples if unconditional_guidance_scale > 1.0: uc = self.get_unconditional_conditioning( N, unconditional_guidance_label, image_size=x.shape[-1] ) # uc = torch.zeros_like(c) with ema_scope("Sampling with classifier-free guidance"): samples_cfg, _ = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, unconditional_guidance_scale=unconditional_guidance_scale, unconditional_conditioning=uc, ) x_samples_cfg = self.decode_first_stage(samples_cfg) log[ f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" ] = x_samples_cfg if inpaint: # make a simple center square b, h, w = z.shape[0], z.shape[2], z.shape[3] mask = torch.ones(N, h, w).to(self.device) # zeros will be filled in mask[:, h // 4 : 3 * h // 4, w // 4 : 3 * w // 4] = 0.0 mask = mask[:, None, ...] with ema_scope("Plotting Inpaint"): samples, _ = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta, ddim_steps=ddim_steps, x0=z[:N], mask=mask, ) x_samples = self.decode_first_stage(samples.to(self.device)) log["samples_inpainting"] = x_samples log["mask"] = mask # outpaint mask = 1.0 - mask with ema_scope("Plotting Outpaint"): samples, _ = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta, ddim_steps=ddim_steps, x0=z[:N], mask=mask, ) x_samples = self.decode_first_stage(samples.to(self.device)) log["samples_outpainting"] = x_samples if plot_progressive_rows: with ema_scope("Plotting Progressives"): img, progressives = self.progressive_denoising( c, shape=(self.channels, self.image_size, self.image_size), batch_size=N, ) prog_row = self._get_denoise_row_from_list( progressives, desc="Progressive Generation" ) log["progressive_row"] = prog_row if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = [] if self.unet_trainable == "attn": print("Training only unet attention layers") for n, m in self.model.named_modules():
""" 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) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if ckpt_path is not None: self.init_from_ckpt( ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet ) self.register_schedule( given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s, ) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule( self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, ): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule( beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s, ) alphas = 1.0 - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1]) (timesteps,) = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert ( alphas_cumprod.shape[0] == self.num_timesteps ), "alphas have to be defined for each timestep" to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer("betas", to_torch(betas)) self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) self.register_buffer("alphas_cumprod_prev", to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer("sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod))) self.register_buffer( "sqrt_one_minus_alphas_cumprod", to_torch(np.sqrt(1.0 - alphas_cumprod)) ) self.register_buffer( "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod)) ) self.register_buffer( "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod)) ) self.register_buffer( "sqrt_recipm1_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod - 1)) ) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * ( 1.0 - alphas_cumprod_prev ) / (1.0 - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer("posterior_variance", to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer( "posterior_log_variance_clipped", to_torch(np.log(np.maximum(posterior_variance, 1e-20))), ) self.register_buffer( "posterior_mean_coef1", to_torch(betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)), ) self.register_buffer( "posterior_mean_coef2", to_torch( (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod) ), ) if self.parameterization == "eps": lvlb_weights = self.betas**2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod) ) elif self.parameterization == "x0": lvlb_weights = ( 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2.0 * 1 - torch.Tensor(alphas_cumprod)) ) else: raise NotImplementedError("mu not supported") # TODO how to choose this term lvlb_weights[0] = lvlb_weights[1] self.register_buffer("lvlb_weights", lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") @torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) if self.make_it_fit: n_params = len( [ name for name, _ in itertools.chain( self.named_parameters(), self.named_buffers() ) ] ) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params, ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[ i % old_shape[0], j % old_shape[1] ] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = ( self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(sd, strict=False) ) print( f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys" ) if len(missing) > 0: print(f"Missing Keys: {missing}") if len(unexpected) > 0: print(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor( self.log_one_minus_alphas_cumprod, t, x_start.shape ) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor( self.posterior_log_variance_clipped, t, x_t.shape ) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1.0, 1.0) model_mean, posterior_variance, posterior_log_variance = self.q_posterior( x_start=x_recon, x_t=x, t=t ) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance( x=x, t=t, clip_denoised=clip_denoised ) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm( reversed(range(0, self.num_timesteps)), desc="Sampling t", total=self.num_timesteps, ): img = self.p_sample( img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised, ) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop( (batch_size, channels, image_size, image_size), return_intermediates=return_intermediates, ) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise ) def get_loss(self, pred, target, mean=True): if self.loss_type == "l1": loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == "l2": if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction="none") elif self.loss_type == "smooth_l1": if mean: loss = torch.nn.functional.smooth_l1_loss(target, pred) else: loss = torch.nn.functional.smooth_l1_loss( target, pred, reduction="none" ) else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start else: raise NotImplementedError( f"Paramterization {self.parameterization} not yet supported" ) loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = "train" if self.training else "val" loss_dict.update({f"{log_prefix}/loss_simple": loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f"{log_prefix}/loss_vlb": loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f"{log_prefix}/loss": loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint( 0, self.num_timesteps, (x.shape[0],), device=self.device ).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, "b h w c -> b c h w") x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): for k in self.ucg_training: p = self.ucg_training[k]["p"] val = self.ucg_training[k]["val"] if val is None: val = "" for i in range(len(batch[k])): if self.ucg_prng.choice(2, p=[1 - p, p]): batch[k][i] = val loss, loss_dict = self.shared_step(batch) self.log_dict( loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True ) self.log( "global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False, ) if self.use_scheduler: lr = self.optimizers().param_groups[0]["lr"] self.log( "lr_abs", lr, prog_bar=True, logger=True, on_step=True, on_epoch=False ) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + "_ema": loss_dict_ema[key] for key in loss_dict_ema} self.log_dict( loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True ) self.log_dict( loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True ) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, "n b c h w -> b n c h w") denoise_grid = rearrange(denoise_grid, "b n c h w -> (b n) c h w") denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), "1 -> b", b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample( batch_size=N, return_intermediates=True ) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__( self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image_cond", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, unet_trainable=True, *args, **kwargs, ): self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs["timesteps"] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = "concat" if concat_mode else "crossattn" if cond_stage_config == "__is_unconditional__": conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.unet_trainable = unet_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer("scale_factor", torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward # construct linear projection layer for concatenating image CLIP embedding and RT 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) self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True def make_cond_schedule( self, ): self.cond_ids = torch.full( size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long, ) ids = torch.round( torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond) ).long() self.cond_ids[: self.num_timesteps_cond] = ids @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx, dataloader_idx): # only for very first batch if ( self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt ): assert ( self.scale_factor == 1.0 ), "rather not use custom rescaling and std-rescaling simultaneously" # set rescale weight to 1./std of encodings print("### USING STD-RESCALING ###") x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer("scale_factor", 1.0 / z.flatten().std()) print(f"setting self.scale_factor to {self.scale_factor}") print("### USING STD-RESCALING ###") def register_schedule( self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, ): super().register_schedule( given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s ) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != "__is_first_stage__" assert config != "__is_unconditional__" model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list( self, samples, desc="", force_no_decoder_quantization=False ): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append( self.decode_first_stage( zd.to(self.device), force_not_quantize=force_no_decoder_quantization ) ) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, "n b c h w -> b n c h w") denoise_grid = rearrange(denoise_grid, "b n c h w -> (b n) c h w") denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError( f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented" ) return self.scale_factor * z def get_learned_conditioning(self, c): if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, "encode") and callable( self.cond_stage_model.encode ): c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min( torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1 )[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip( weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip( L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"], ) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold( self, x, kernel_size, stride, uf=1, df=1 ): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict( kernel_size=kernel_size, dilation=1, padding=0, stride=stride ) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting( kernel_size[0], kernel_size[1], Ly, Lx, x.device ).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict( kernel_size=kernel_size, dilation=1, padding=0, stride=stride ) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict( kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf), ) fold = torch.nn.Fold( output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2 ) weighting = self.get_weighting( kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device ).to(x.dtype) normalization = fold(weighting).view( 1, 1, h * uf, w * uf ) # normalizes the overlap weighting = weighting.view( (1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx) ) elif df > 1 and uf == 1: fold_params = dict( kernel_size=kernel_size, dilation=1, padding=0, stride=stride ) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict( kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df), ) fold = torch.nn.Fold( output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2 ) weighting = self.get_weighting( kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device ).to(x.dtype) normalization = fold(weighting).view( 1, 1, h // df, w // df ) # normalizes the overlap weighting = weighting.view( (1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx) ) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input( self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, uncond=0.05, ): x = super().get_input(batch, k) T = batch["T"].to(memory_format=torch.contiguous_format).float() if bs is not None: x = x[:bs] T = T[:bs].to(self.device) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() cond_key = cond_key or self.cond_stage_key xc = super().get_input(batch, cond_key).to(self.device) if bs is not None: xc = xc[:bs] cond = {} # To support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%. random = torch.rand(x.size(0), device=x.device) prompt_mask = rearrange(random < 2 * uncond, "n -> n 1 1") input_mask = 1 - rearrange( (random >= uncond).float() * (random < 3 * uncond).float(), "n -> n 1 1 1" ) null_prompt = self.get_learned_conditioning([""]) # z.shape: [8, 4, 64, 64]; c.shape: [8, 1, 768] # print('=========== xc shape ===========', xc.shape) with torch.enable_grad(): clip_emb = self.get_learned_conditioning(xc).detach() null_prompt = self.get_learned_conditioning([""]).detach() cond["c_crossattn"] = [ self.cc_projection( torch.cat( [ torch.where(prompt_mask, null_prompt, clip_emb), T[:, None, :], ], dim=-1, ) ) ] cond["c_concat"] = [ input_mask * self.encode_first_stage((xc.to(self.device))).mode().detach() ] out = [z, cond] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out # @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, "b h w c -> b c h w").contiguous() z = 1.0 / self.scale_factor * z if hasattr(self, "split_input_params"): if self.split_input_params["patch_distributed_vq"]: ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) uf = self.split_input_params["vqf"] bs, nc, h, w = z.shape if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print("reducing stride") fold, unfold, normalization, weighting = self.get_fold_unfold( z, ks, stride, uf=uf ) z = unfold(z) # (bn, nc * prod(**ks), L) # 1. Reshape to img shape z = z.view( (z.shape[0], -1, ks[0], ks[1], z.shape[-1]) ) # (bn, nc, ks[0], ks[1], L ) # 2. apply model loop over last dim if isinstance(self.first_stage_model, VQModelInterface): output_list = [ self.first_stage_model.decode( z[:, :, :, :, i], force_not_quantize=predict_cids or force_not_quantize, ) for i in range(z.shape[-1]) ] else: output_list = [ self.first_stage_model.decode(z[:, :, :, :, i]) for i in range(z.shape[-1]) ] o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L) o = o * weighting # Reverse 1. reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together decoded = fold(o) decoded = decoded / normalization # norm is shape (1, 1, h, w) return decoded else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode( z, force_not_quantize=predict_cids or force_not_quantize ) else: return self.first_stage_model.decode(z) else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode( z, force_not_quantize=predict_cids or force_not_quantize ) else: return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): if hasattr(self, "split_input_params"): if self.split_input_params["patch_distributed_vq"]: ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) df = self.split_input_params["vqf"] self.split_input_params["original_image_size"] = x.shape[-2:] bs, nc, h, w = x.shape if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print("reducing stride") fold, unfold, normalization, weighting = self.get_fold_unfold( x, ks, stride, df=df ) z = unfold(x) # (bn, nc * prod(**ks), L) # Reshape to img shape z = z.view( (z.shape[0], -1, ks[0], ks[1], z.shape[-1]) ) # (bn, nc, ks[0], ks[1], L ) output_list = [ self.first_stage_model.encode(z[:, :, :, :, i]) for i in range(z.shape[-1]) ] o = torch.stack(output_list, axis=-1) o = o * weighting # Reverse reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together decoded = fold(o) decoded = decoded / normalization return decoded else: return self.first_stage_model.encode(x) else: return self.first_stage_model.encode(x) def shared_step(self, batch, step_ratio=None, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c, step_ratio=step_ratio) return loss def forward(self, x, c, step_ratio=None, *args, **kwargs): if step_ratio is not None: t = np.round((1 - step_ratio) * self.num_timesteps).clip(0, self.num_timesteps - 1) t = torch.full((x.shape[0],), t, dtype=torch.long, device=self.device) else: t = torch.randint( 0, self.num_timesteps, (x.shape[0],), device=self.device ).long() if self.model.conditioning_key is not None: assert c is not None # if self.cond_stage_trainable: # c = self.get_learned_conditioning(c) if self.shorten_cond_schedule: # TODO: drop this option tc = self.cond_ids[t].to(self.device) c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) return self.p_losses(x, c, t, *args, **kwargs) def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset def rescale_bbox(bbox): x0 = clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2]) y0 = clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3]) w = min(bbox[2] / crop_coordinates[2], 1 - x0) h = min(bbox[3] / crop_coordinates[3], 1 - y0) return x0, y0, w, h return [rescale_bbox(b) for b in bboxes] def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is exptected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = ( "c_concat" if self.model.conditioning_key == "concat" else "c_crossattn" ) cond = {key: cond} if hasattr(self, "split_input_params"): assert len(cond) == 1 # todo can only deal with one conditioning atm assert not return_ids ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) h, w = x_noisy.shape[-2:] fold, unfold, normalization, weighting = self.get_fold_unfold( x_noisy, ks, stride ) z = unfold(x_noisy) # (bn, nc * prod(**ks), L) # Reshape to img shape z = z.view( (z.shape[0], -1, ks[0], ks[1], z.shape[-1]) ) # (bn, nc, ks[0], ks[1], L ) z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])] if ( self.cond_stage_key in ["image", "LR_image", "segmentation", "bbox_img"] and self.model.conditioning_key ): # todo check for completeness c_key = next(iter(cond.keys())) # get key c = next(iter(cond.values())) # get value assert len(c) == 1 # todo extend to list with more than one elem c = c[0] # get element c = unfold(c) c = c.view( (c.shape[0], -1, ks[0], ks[1], c.shape[-1]) ) # (bn, nc, ks[0], ks[1], L ) cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])] elif self.cond_stage_key == "coordinates_bbox": assert ( "original_image_size" in self.split_input_params ), "BoudingBoxRescaling is missing original_image_size" # assuming padding of unfold is always 0 and its dilation is always 1 n_patches_per_row = int((w - ks[0]) / stride[0] + 1) full_img_h, full_img_w = self.split_input_params["original_image_size"] # as we are operating on latents, we need the factor from the original image size to the # spatial latent size to properly rescale the crops for regenerating the bbox annotations num_downs = self.first_stage_model.encoder.num_resolutions - 1 rescale_latent = 2 ** (num_downs) # get top left postions of patches as conforming for the bbbox tokenizer, therefore we # need to rescale the tl patch coordinates to be in between (0,1) tl_patch_coordinates = [ ( rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w, rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h, ) for patch_nr in range(z.shape[-1]) ] # patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w) patch_limits = [ ( x_tl, y_tl, rescale_latent * ks[0] / full_img_w, rescale_latent * ks[1] / full_img_h, ) for x_tl, y_tl in tl_patch_coordinates ] # patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates] # tokenize crop coordinates for the bounding boxes of the respective patches patch_limits_tknzd = [ torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to( self.device ) for bbox in patch_limits ] # list of length l with tensors of shape (1, 2) # cut tknzd crop position from conditioning assert isinstance(cond, dict), "cond must be dict to be fed into model" cut_cond = cond["c_crossattn"][0][..., :-2].to(self.device) adapted_cond = torch.stack( [torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd] ) adapted_cond = rearrange(adapted_cond, "l b n -> (l b) n") adapted_cond = self.get_learned_conditioning(adapted_cond) adapted_cond = rearrange( adapted_cond, "(l b) n d -> l b n d", l=z.shape[-1] ) cond_list = [{"c_crossattn": [e]} for e in adapted_cond] else: cond_list = [ cond for i in range(z.shape[-1]) ] # Todo make this more efficient # apply model by loop over crops output_list = [ self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1]) ] assert not isinstance( output_list[0], tuple ) # todo cant deal with multiple model outputs check this never happens o = torch.stack(output_list, axis=-1) o = o * weighting # Reverse reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together x_recon = fold(o) / normalization else: x_recon = self.model(x_noisy, t, **cond) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart ) / extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl( mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 ) return mean_flat(kl_prior) / np.log(2.0) def p_losses(self, x_start, cond, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_output = self.apply_model(x_noisy, t, cond) loss_dict = {} prefix = "train" if self.training else "val" if self.parameterization == "x0": target = x_start elif self.parameterization == "eps": target = noise else: raise NotImplementedError() loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3]) loss_dict.update({f"{prefix}/loss_simple": loss_simple.mean()}) if self.logvar.device != self.device: self.logvar = self.logvar.to(self.device) logvar_t = self.logvar[t].to(self.device) loss = loss_simple / torch.exp(logvar_t) + logvar_t # loss = loss_simple / torch.exp(self.logvar) + self.logvar if self.learn_logvar: loss_dict.update({f"{prefix}/loss_gamma": loss.mean()}) loss_dict.update({"logvar": self.logvar.data.mean()}) loss = self.l_simple_weight * loss.mean() loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3)) loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean() loss_dict.update({f"{prefix}/loss_vlb": loss_vlb}) loss += self.original_elbo_weight * loss_vlb loss_dict.update({f"{prefix}/loss": loss}) return loss, loss_dict def p_mean_variance( self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False, return_x0=False, score_corrector=None, corrector_kwargs=None, ): t_in = t model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) if score_corrector is not None: assert self.parameterization == "eps" model_out = score_corrector.modify_score( self, model_out, x, t, c, **corrector_kwargs ) if return_codebook_ids: model_out, logits = model_out if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out else: raise NotImplementedError() if clip_denoised: x_recon.clamp_(-1.0, 1.0) if quantize_denoised: x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) model_mean, posterior_variance, posterior_log_variance = self.q_posterior( x_start=x_recon, x_t=x, t=t ) if return_codebook_ids: return model_mean, posterior_variance, posterior_log_variance, logits elif return_x0: return model_mean, posterior_variance, posterior_log_variance, x_recon else: return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample( self, x, c, t, clip_denoised=False, repeat_noise=False, return_codebook_ids=False, quantize_denoised=False, return_x0=False, temperature=1.0, noise_dropout=0.0, score_corrector=None, corrector_kwargs=None, ): b, *_, device = *x.shape, x.device outputs = self.p_mean_variance( x=x, c=c, t=t, clip_denoised=clip_denoised, return_codebook_ids=return_codebook_ids, quantize_denoised=quantize_denoised, return_x0=return_x0, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, ) if return_codebook_ids: raise DeprecationWarning("Support dropped.") model_mean, _, model_log_variance, logits = outputs elif return_x0: model_mean, _, model_log_variance, x0 = outputs else: model_mean, _, model_log_variance = outputs noise = noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.0: noise = torch.nn.functional.dropout(noise, p=noise_dropout) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) if return_codebook_ids: return model_mean + nonzero_mask * ( 0.5 * model_log_variance ).exp() * noise, logits.argmax(dim=1) if return_x0: return ( model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0, ) else: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def progressive_denoising( self, cond, shape, verbose=True, callback=None, quantize_denoised=False, img_callback=None, mask=None, x0=None, temperature=1.0, noise_dropout=0.0, score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None, log_every_t=None, ): if not log_every_t: log_every_t = self.log_every_t timesteps = self.num_timesteps if batch_size is not None: b = batch_size if batch_size is not None else shape[0] shape = [batch_size] + list(shape) else: b = batch_size = shape[0] if x_T is None: img = torch.randn(shape, device=self.device) else: img = x_T intermediates = [] if cond is not None: if isinstance(cond, dict): cond = { key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond } else: cond = ( [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] ) if start_T is not None: timesteps = min(timesteps, start_T) iterator = ( tqdm( reversed(range(0, timesteps)), desc="Progressive Generation", total=timesteps, ) if verbose else reversed(range(0, timesteps)) ) if type(temperature) == float: temperature = [temperature] * timesteps for i in iterator: ts = torch.full((b,), i, device=self.device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != "hybrid" tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img, x0_partial = self.p_sample( img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, return_x0=True, temperature=temperature[i], noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, ) if mask is not None: assert x0 is not None img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1.0 - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(x0_partial) if callback: callback(i) if img_callback: img_callback(img, i) return img, intermediates @torch.no_grad() def p_sample_loop( self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None, ): if not log_every_t: log_every_t = self.log_every_t device = self.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = ( tqdm(reversed(range(0, timesteps)), desc="Sampling t", total=timesteps) if verbose else reversed(range(0, timesteps)) ) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != "hybrid" tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample( img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, ) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1.0 - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample( self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs, ): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = { key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond } else: cond = ( [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] ) return self.p_sample_loop( cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0, ) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim: ddim_sampler = DDIMSampler(self) shape = (self.channels, self.image_size, self.image_size) samples, intermediates = ddim_sampler.sample( ddim_steps, batch_size, shape, cond, verbose=False, **kwargs ) else: samples, intermediates = self.sample( cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs ) return samples, intermediates @torch.no_grad() def get_unconditional_conditioning( self, batch_size, null_label=None, image_size=512 ): if null_label is not None: xc = null_label if isinstance(xc, ListConfig): xc = list(xc) if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: if hasattr(xc, "to"): xc = xc.to(self.device) c = self.get_learned_conditioning(xc) else: # todo: get null label from cond_stage_model raise NotImplementedError() c = repeat(c, "1 ... -> b ...", b=batch_size).to(self.device) cond = {} cond["c_crossattn"] = [c] cond["c_concat"] = [ torch.zeros([batch_size, 4, image_size // 8, image_size // 8]).to( self.device ) ] return cond @torch.no_grad() def log_images( self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1.0, return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, unconditional_guidance_scale=1.0, unconditional_guidance_label=None, use_ema_scope=True, **kwargs, ): ema_scope = self.ema_scope if use_ema_scope else nullcontext use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input( batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N, ) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption", "txt"]: xc = log_txt_as_img( (x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25, ) log["conditioning"] = xc elif self.cond_stage_key == "class_label": xc = log_txt_as_img( (x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25, ) log["conditioning"] = xc elif isimage(xc): log["conditioning"] = xc if ismap(xc): log["original_conditioning"] = self.to_rgb(xc) if plot_diffusion_rows: # get diffusion row diffusion_row = list() z_start = z[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), "1 -> b", b=n_row) t = t.to(self.device).long() noise = torch.randn_like(z_start) z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) diffusion_row.append(self.decode_first_stage(z_noisy)) diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W diffusion_grid = rearrange(diffusion_row, "n b c h w -> b n c h w") diffusion_grid = rearrange(diffusion_grid, "b n c h w -> (b n) c h w") diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) log["diffusion_row"] = diffusion_grid if sample: # get denoise row with ema_scope("Sampling"): samples, z_denoise_row = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, ) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if ( quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(self.first_stage_model, IdentityFirstStage) ): # also display when quantizing x0 while sampling with ema_scope("Plotting Quantized Denoised"): samples, z_denoise_row = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, quantize_denoised=True, ) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True, # quantize_denoised=True) x_samples = self.decode_first_stage(samples.to(self.device)) log["samples_x0_quantized"] = x_samples if unconditional_guidance_scale > 1.0: uc = self.get_unconditional_conditioning( N, unconditional_guidance_label, image_size=x.shape[-1] ) # uc = torch.zeros_like(c) with ema_scope("Sampling with classifier-free guidance"): samples_cfg, _ = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, ddim_steps=ddim_steps, eta=ddim_eta, unconditional_guidance_scale=unconditional_guidance_scale, unconditional_conditioning=uc, ) x_samples_cfg = self.decode_first_stage(samples_cfg) log[ f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" ] = x_samples_cfg if inpaint: # make a simple center square b, h, w = z.shape[0], z.shape[2], z.shape[3] mask = torch.ones(N, h, w).to(self.device) # zeros will be filled in mask[:, h // 4 : 3 * h // 4, w // 4 : 3 * w // 4] = 0.0 mask = mask[:, None, ...] with ema_scope("Plotting Inpaint"): samples, _ = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta, ddim_steps=ddim_steps, x0=z[:N], mask=mask, ) x_samples = self.decode_first_stage(samples.to(self.device)) log["samples_inpainting"] = x_samples log["mask"] = mask # outpaint mask = 1.0 - mask with ema_scope("Plotting Outpaint"): samples, _ = self.sample_log( cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta, ddim_steps=ddim_steps, x0=z[:N], mask=mask, ) x_samples = self.decode_first_stage(samples.to(self.device)) log["samples_outpainting"] = x_samples if plot_progressive_rows: with ema_scope("Plotting Progressives"): img, progressives = self.progressive_denoising( c, shape=(self.channels, self.image_size, self.image_size), batch_size=N, ) prog_row = self._get_denoise_row_from_list( progressives, desc="Progressive Generation" ) log["progressive_row"] = prog_row if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = [] if self.unet_trainable == "attn": print("Training only unet attention layers") for n, m in self.model.named_modules():
if isinstance(m, CrossAttention) and n.endswith("attn2"):
18
2023-12-17 12:45:38+00:00
16k
wangzhecheng/SkyScript
customized_train_and_test.py
[ { "identifier": "create_model_and_transforms", "path": "src/open_clip/factory.py", "snippet": "def create_model_and_transforms(\n model_name: str,\n pretrained: Optional[str] = None,\n precision: str = 'fp32',\n device: Union[str, torch.device] = 'cpu',\n jit: bool = F...
import glob import json import logging import os import re import subprocess import sys import random import numpy as np import torch import wandb import torch.utils.tensorboard as tensorboard import horovod.torch as hvd from datetime import datetime from torch import optim from torch.cuda.amp import GradScaler from torchvision import transforms from src.open_clip.factory import create_model_and_transforms, get_tokenizer, create_loss from src.open_clip.model import trace_model from src.training.data import get_data from src.training.distributed import is_master, init_distributed_device, broadcast_object from src.training.logger import setup_logging from src.training.scheduler import cosine_lr, const_lr, const_lr_cooldown from src.training.train import train_one_epoch, evaluate from src.training.file_utils import pt_load, check_exists, start_sync_process, remote_sync from src.training.main import natural_key, get_latest_checkpoint, copy_codebase from test_zero_shot_classification import * from params import parse_args
13,187
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) ddp_args = {} if args.ddp_static_graph: # this doesn't exist in older PyTorch, arg only added if enabled ddp_args['static_graph'] = True model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[device], **ddp_args) if args.distill: dist_model = torch.nn.parallel.DistributedDataParallel(dist_model, device_ids=[device], **ddp_args) # create optimizer and scaler optimizer = None scaler = None if args.train_data or args.dataset_type == "synthetic": assert not args.trace, 'Cannot train with traced model' exclude = lambda n, p: p.ndim < 2 or "bn" in n or "ln" in n or "bias" in n or 'logit_scale' in n include = lambda n, p: not exclude(n, p) named_parameters = list(model.named_parameters()) gain_or_bias_params = [p for n, p in named_parameters if exclude(n, p) and p.requires_grad] rest_params = [p for n, p in named_parameters if include(n, p) and p.requires_grad] optimizer = optim.AdamW( [ {"params": gain_or_bias_params, "weight_decay": 0.}, {"params": rest_params, "weight_decay": args.wd}, ], lr=args.lr, betas=(args.beta1, args.beta2), eps=args.eps, ) if args.horovod: optimizer = hvd.DistributedOptimizer(optimizer, named_parameters=model.named_parameters()) hvd.broadcast_parameters(model.state_dict(), root_rank=0) hvd.broadcast_optimizer_state(optimizer, root_rank=0) scaler = GradScaler() if args.precision == "amp" else None # optionally resume from a checkpoint start_epoch = 0 if args.resume is not None: checkpoint = pt_load(args.resume, map_location='cpu') if 'epoch' in checkpoint: # resuming a train checkpoint w/ epoch and optimizer state start_epoch = checkpoint["epoch"] sd = checkpoint["state_dict"] if not args.distributed and next(iter(sd.items()))[0].startswith('module'): sd = {k[len('module.'):]: v for k, v in sd.items()} model.load_state_dict(sd) if optimizer is not None: optimizer.load_state_dict(checkpoint["optimizer"]) if scaler is not None and 'scaler' in checkpoint: scaler.load_state_dict(checkpoint['scaler']) logging.info(f"=> resuming checkpoint '{args.resume}' (epoch {start_epoch})") else: # loading a bare (model only) checkpoint for fine-tune or evaluation model.load_state_dict(checkpoint) logging.info(f"=> loaded checkpoint '{args.resume}' (epoch {start_epoch})") # initialize datasets data = get_data(args, (preprocess_train, preprocess_val), epoch=start_epoch, tokenizer=get_tokenizer(args.model)) assert len(data), 'At least one train or eval dataset must be specified.' # initialize benchmark dataloaders for testing zero-shot classification if args.datasets_for_testing is not None or args.test_data_name is not None: test_dataloaders = get_test_dataloaders(args, preprocess_val) else: test_dataloaders = None # create scheduler if train scheduler = None if 'train' in data and optimizer is not None: total_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs if args.lr_scheduler == "cosine": scheduler = cosine_lr(optimizer, args.lr, args.warmup, total_steps) elif args.lr_scheduler == "const": scheduler = const_lr(optimizer, args.lr, args.warmup, total_steps) elif args.lr_scheduler == "const-cooldown": assert args.epochs_cooldown is not None,\ "Please specify the number of cooldown epochs for this lr schedule." cooldown_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs_cooldown scheduler = const_lr_cooldown( optimizer, args.lr, args.warmup, total_steps, cooldown_steps, args.lr_cooldown_power, args.lr_cooldown_end) else: logging.error( f'Unknown scheduler, {args.lr_scheduler}. Available options are: cosine, const, const-cooldown.') exit(1) # determine if this worker should save logs and checkpoints. only do so if it is rank == 0 args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) writer = None if args.save_logs and args.tensorboard: assert tensorboard is not None, "Please install tensorboard." writer = tensorboard.SummaryWriter(args.tensorboard_path) if args.wandb and is_master(args): assert wandb is not None, 'Please install wandb.' logging.debug('Starting wandb.') args.train_sz = data["train"].dataloader.num_samples if args.val_data is not None: args.val_sz = data["val"].dataloader.num_samples # you will have to configure this for your project! wandb.init( project=args.wandb_project_name, name=args.name, id=args.name, notes=args.wandb_notes, tags=[], resume='auto' if args.resume == "latest" else None, config=vars(args), ) if args.debug: wandb.watch(model, log='all') wandb.save(params_file) logging.debug('Finished loading wandb.') if 'train' not in data:
""" Adapted from https://github.com/mlfoundations/open_clip. Copyright (c) 2012-2021 Gabriel Ilharco, Mitchell Wortsman, Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar, John Miller, Hongseok Namkoong, Hannaneh Hajishirzi, Ali Farhadi, Ludwig Schmidt """ try: except ImportError: wandb = None try: except ImportError: tensorboard = None try: except ImportError: hvd = None # from src.open_clip import create_model_and_transforms, trace_model, get_tokenizer, create_loss LATEST_CHECKPOINT_NAME = "epoch_latest.pt" def RandomRotationNew(image): angle = random.choice([0, 90, 180, 270]) image = transforms.functional.rotate(image, angle) return image def zero_shot_eval_during_training(model, test_dataloaders, epoch, args, tb_writer=None): logging.info('Starting zero-shot evaluation.') zero_shot_metrics = {} for dataset_name in test_dataloaders: logging.info(f'Evaluating zero-shot classification for dataset {dataset_name}') results = test_zero_shot_classification(model, test_dataloaders[dataset_name]['dataloader'], test_dataloaders[dataset_name]['labels'], test_dataloaders[dataset_name]['is_binary'], args, dataset_name=dataset_name, debugging=args.debugging) for k, v in results.items(): if type(v) in [float, int, np.float16, np.float32, np.float64, np.int8, np.int16, np.int32, np.int64]: zero_shot_metrics[k] = v logging.info( f"Zero-Shot Eval Epoch: {epoch} " + "\t".join([f"{k}: {round(v, 4):.4f}" for k, v in zero_shot_metrics.items()]) ) if args.save_logs: for name, val in zero_shot_metrics.items(): if tb_writer is not None: tb_writer.add_scalar(f"val/{name}", val, epoch) with open(os.path.join(args.checkpoint_path, "results.jsonl"), "a+") as f: f.write(json.dumps(zero_shot_metrics)) f.write("\n") # if args.wandb: # assert wandb is not None, 'Please install wandb.' # for name, val in zero_shot_metrics.items(): # wandb.log({f"val/{name}": val, 'epoch': epoch}) logging.info('Finished zero-shot evaluation.') return zero_shot_metrics def train_and_test(args): args = parse_args(args) if torch.cuda.is_available(): # This enables tf32 on Ampere GPUs which is only 8% slower than # float16 and almost as accurate as float32 # This was a default in pytorch until 1.12 torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = False # fully initialize distributed device environment device = init_distributed_device(args) # get the name of the experiments if args.name is None: # sanitize model name for filesystem / uri use, easier if we don't use / in name as a rule? model_name_safe = args.model.replace('/', '-') date_str = datetime.now().strftime("%Y_%m_%d-%H_%M_%S") if args.distributed: # sync date_str from master to all ranks date_str = broadcast_object(args, date_str) args.name = '-'.join([ date_str, f"model_{model_name_safe}", f"lr_{args.lr}", f"b_{args.batch_size}", f"j_{args.workers}", f"p_{args.precision}", ]) resume_latest = args.resume == 'latest' log_base_path = os.path.join(args.logs, args.name) args.log_path = None if is_master(args, local=args.log_local): os.makedirs(log_base_path, exist_ok=True) log_filename = f'out-{args.rank}' if args.log_local else 'out.log' args.log_path = os.path.join(log_base_path, log_filename) if os.path.exists(args.log_path) and not resume_latest: print( "Error. Experiment already exists. Use --name {} to specify a new experiment." ) return -1 # Setup text logger args.log_level = logging.DEBUG if args.debug else logging.INFO setup_logging(args.log_path, args.log_level) # Setup wandb, tensorboard, checkpoint logging args.wandb = 'wandb' in args.report_to or 'all' in args.report_to args.tensorboard = 'tensorboard' in args.report_to or 'all' in args.report_to args.checkpoint_path = os.path.join(log_base_path, "checkpoints") if is_master(args): args.tensorboard_path = os.path.join(log_base_path, "tensorboard") if args.tensorboard else '' for dirname in [args.tensorboard_path, args.checkpoint_path]: if dirname: os.makedirs(dirname, exist_ok=True) else: args.tensorboard_path = '' if resume_latest: resume_from = None checkpoint_path = args.checkpoint_path # If using remote_sync, need to check the remote instead of the local checkpoints folder. if args.remote_sync is not None: checkpoint_path = os.path.join(args.remote_sync, args.name, "checkpoints") if args.save_most_recent: print('Error. Cannot use save-most-recent with remote_sync and resume latest.') return -1 if args.remote_sync_protocol != 's3': print('Error. Sync protocol not supported when using resume latest.') return -1 if is_master(args): # Checking for existing checkpoint via master rank only. It is possible for # different rank processes to see different files if a shared file-system is under # stress, however it's very difficult to fully work around such situations. if args.save_most_recent: # if --save-most-recent flag is set, look for latest at a fixed filename resume_from = os.path.join(checkpoint_path, LATEST_CHECKPOINT_NAME) if not os.path.exists(resume_from): # If no latest checkpoint has been saved yet, don't try to resume resume_from = None else: # otherwise, list checkpoint dir contents and pick the newest checkpoint resume_from = get_latest_checkpoint(checkpoint_path, remote=args.remote_sync is not None) if resume_from: logging.info(f'Found latest resume checkpoint at {resume_from}.') else: logging.info(f'No latest resume checkpoint found in {checkpoint_path}.') if args.distributed: # sync found checkpoint path to all ranks resume_from = broadcast_object(args, resume_from) args.resume = resume_from if args.copy_codebase: copy_codebase(args) # start the sync proces if remote-sync is not None remote_sync_process = None if is_master(args) and args.remote_sync is not None: # first make sure it works result = remote_sync( os.path.join(args.logs, args.name), os.path.join(args.remote_sync, args.name), args.remote_sync_protocol ) if result: logging.info('remote sync successful.') else: logging.info('Error: remote sync failed. Exiting.') return -1 # if all looks good, start a process to do this every args.remote_sync_frequency seconds remote_sync_process = start_sync_process( args.remote_sync_frequency, os.path.join(args.logs, args.name), os.path.join(args.remote_sync, args.name), args.remote_sync_protocol ) remote_sync_process.start() if args.precision == 'fp16': logging.warning( 'It is recommended to use AMP mixed-precision instead of FP16. ' 'FP16 support needs further verification and tuning, especially for train.') if args.horovod: logging.info( f'Running in horovod mode with multiple processes / nodes. Device: {args.device}.' f'Process (global: {args.rank}, local {args.local_rank}), total {args.world_size}.') elif args.distributed: logging.info( f'Running in distributed mode with multiple processes. Device: {args.device}.' f'Process (global: {args.rank}, local {args.local_rank}), total {args.world_size}.') else: logging.info(f'Running with a single process. Device {args.device}.') dist_model = None args.distill = args.distill_model is not None and args.distill_pretrained is not None if args.distill: #FIXME: support distillation with grad accum. assert args.accum_freq == 1 #FIXME: support distillation with coca. assert 'coca' not in args.model.lower() if isinstance(args.force_image_size, (tuple, list)) and len(args.force_image_size) == 1: # arg is nargs, single (square) image size list -> int args.force_image_size = args.force_image_size[0] random_seed(args.seed, 0) model, preprocess_train, preprocess_val = create_model_and_transforms( args.model, args.pretrained, precision=args.precision, device=device, jit=args.torchscript, force_quick_gelu=args.force_quick_gelu, force_custom_text=args.force_custom_text, force_patch_dropout=args.force_patch_dropout, force_image_size=args.force_image_size, pretrained_image=args.pretrained_image, image_mean=args.image_mean, image_std=args.image_std, aug_cfg=args.aug_cfg, output_dict=True, ) if args.random_rotation: # add random rotation step into preprocess_train for i, trans in enumerate(preprocess_train.transforms): if type(trans) == transforms.transforms.ToTensor: # insert random rotation right before ToTensor preprocess_train.transforms.insert(i, transforms.Lambda(RandomRotationNew)) break if args.distill: # FIXME: currenlty assumes the model your distilling from has the same tokenizer & transforms. dist_model, _, _ = create_model_and_transforms( args.distill_model, args.distill_pretrained, device=device, precision=args.precision, output_dict=True, ) random_seed(args.seed, args.rank) if args.trace: model = trace_model(model, batch_size=args.batch_size, device=device) if args.lock_image: # lock image tower as per LiT - https://arxiv.org/abs/2111.07991 model.lock_image_tower( unlocked_groups=args.lock_image_unlocked_groups, freeze_bn_stats=args.lock_image_freeze_bn_stats) if args.lock_text: model.lock_text_tower( unlocked_layers=args.lock_text_unlocked_layers, freeze_layer_norm=args.lock_text_freeze_layer_norm) if args.grad_checkpointing: model.set_grad_checkpointing() if is_master(args): logging.info("Model:") logging.info(f"{str(model)}") logging.info("Params:") params_file = os.path.join(args.logs, args.name, "params.txt") with open(params_file, "w") as f: for name in sorted(vars(args)): val = getattr(args, name) logging.info(f" {name}: {val}") f.write(f"{name}: {val}\n") if args.distributed and not args.horovod: if args.use_bn_sync: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) ddp_args = {} if args.ddp_static_graph: # this doesn't exist in older PyTorch, arg only added if enabled ddp_args['static_graph'] = True model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[device], **ddp_args) if args.distill: dist_model = torch.nn.parallel.DistributedDataParallel(dist_model, device_ids=[device], **ddp_args) # create optimizer and scaler optimizer = None scaler = None if args.train_data or args.dataset_type == "synthetic": assert not args.trace, 'Cannot train with traced model' exclude = lambda n, p: p.ndim < 2 or "bn" in n or "ln" in n or "bias" in n or 'logit_scale' in n include = lambda n, p: not exclude(n, p) named_parameters = list(model.named_parameters()) gain_or_bias_params = [p for n, p in named_parameters if exclude(n, p) and p.requires_grad] rest_params = [p for n, p in named_parameters if include(n, p) and p.requires_grad] optimizer = optim.AdamW( [ {"params": gain_or_bias_params, "weight_decay": 0.}, {"params": rest_params, "weight_decay": args.wd}, ], lr=args.lr, betas=(args.beta1, args.beta2), eps=args.eps, ) if args.horovod: optimizer = hvd.DistributedOptimizer(optimizer, named_parameters=model.named_parameters()) hvd.broadcast_parameters(model.state_dict(), root_rank=0) hvd.broadcast_optimizer_state(optimizer, root_rank=0) scaler = GradScaler() if args.precision == "amp" else None # optionally resume from a checkpoint start_epoch = 0 if args.resume is not None: checkpoint = pt_load(args.resume, map_location='cpu') if 'epoch' in checkpoint: # resuming a train checkpoint w/ epoch and optimizer state start_epoch = checkpoint["epoch"] sd = checkpoint["state_dict"] if not args.distributed and next(iter(sd.items()))[0].startswith('module'): sd = {k[len('module.'):]: v for k, v in sd.items()} model.load_state_dict(sd) if optimizer is not None: optimizer.load_state_dict(checkpoint["optimizer"]) if scaler is not None and 'scaler' in checkpoint: scaler.load_state_dict(checkpoint['scaler']) logging.info(f"=> resuming checkpoint '{args.resume}' (epoch {start_epoch})") else: # loading a bare (model only) checkpoint for fine-tune or evaluation model.load_state_dict(checkpoint) logging.info(f"=> loaded checkpoint '{args.resume}' (epoch {start_epoch})") # initialize datasets data = get_data(args, (preprocess_train, preprocess_val), epoch=start_epoch, tokenizer=get_tokenizer(args.model)) assert len(data), 'At least one train or eval dataset must be specified.' # initialize benchmark dataloaders for testing zero-shot classification if args.datasets_for_testing is not None or args.test_data_name is not None: test_dataloaders = get_test_dataloaders(args, preprocess_val) else: test_dataloaders = None # create scheduler if train scheduler = None if 'train' in data and optimizer is not None: total_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs if args.lr_scheduler == "cosine": scheduler = cosine_lr(optimizer, args.lr, args.warmup, total_steps) elif args.lr_scheduler == "const": scheduler = const_lr(optimizer, args.lr, args.warmup, total_steps) elif args.lr_scheduler == "const-cooldown": assert args.epochs_cooldown is not None,\ "Please specify the number of cooldown epochs for this lr schedule." cooldown_steps = (data["train"].dataloader.num_batches // args.accum_freq) * args.epochs_cooldown scheduler = const_lr_cooldown( optimizer, args.lr, args.warmup, total_steps, cooldown_steps, args.lr_cooldown_power, args.lr_cooldown_end) else: logging.error( f'Unknown scheduler, {args.lr_scheduler}. Available options are: cosine, const, const-cooldown.') exit(1) # determine if this worker should save logs and checkpoints. only do so if it is rank == 0 args.save_logs = args.logs and args.logs.lower() != 'none' and is_master(args) writer = None if args.save_logs and args.tensorboard: assert tensorboard is not None, "Please install tensorboard." writer = tensorboard.SummaryWriter(args.tensorboard_path) if args.wandb and is_master(args): assert wandb is not None, 'Please install wandb.' logging.debug('Starting wandb.') args.train_sz = data["train"].dataloader.num_samples if args.val_data is not None: args.val_sz = data["val"].dataloader.num_samples # you will have to configure this for your project! wandb.init( project=args.wandb_project_name, name=args.name, id=args.name, notes=args.wandb_notes, tags=[], resume='auto' if args.resume == "latest" else None, config=vars(args), ) if args.debug: wandb.watch(model, log='all') wandb.save(params_file) logging.debug('Finished loading wandb.') if 'train' not in data:
evaluate(model, data, start_epoch, args, writer)
13
2023-12-19 11:50:56+00:00
16k
penghao-wu/vstar
VisualSearch/train.py
[ { "identifier": "VSMForCausalLM", "path": "VisualSearch/model/VSM.py", "snippet": "class VSMForCausalLM(LlavaLlamaForCausalLM):\n\tdef __init__(\n\t\tself,\n\t\tconfig,\n\t\t**kwargs,\n\t):\n\t\tif not hasattr(config, \"train_mask_decoder\"):\n\t\t\tconfig.mm_use_im_start_end = kwargs.pop(\"use_mm_start...
import argparse import os import shutil import sys import time import deepspeed import torch import tqdm import transformers from functools import partial from peft import LoraConfig, get_peft_model from torch.utils.tensorboard import SummaryWriter from VisualSearch.model.VSM import VSMForCausalLM from VisualSearch.model.llava import conversation as conversation_lib from VisualSearch.utils.dataset import HybridDataset, ValDataset, collate_fn from VisualSearch.utils.utils import (DEFAULT_IM_END_TOKEN, DEFAULT_IM_START_TOKEN, AverageMeter, ProgressMeter, Summary, dict_to_cuda, intersectionAndUnionGPU)
11,396
"--version", default="LLaVA-7B-v1.1" ) parser.add_argument( "--precision", default="bf16", type=str, choices=["fp32", "bf16", "fp16"], help="precision for training", ) parser.add_argument("--model_max_length", default=512, type=int) parser.add_argument("--lora_r", default=8, type=int) parser.add_argument( "--vision-tower", default="openai/clip-vit-large-patch14", type=str ) parser.add_argument("--load_in_8bit", action="store_true", default=False) parser.add_argument("--load_in_4bit", action="store_true", default=False) parser.add_argument( "--dataset", default="general_segdet||refer_seg||mixed_grounding||vqa", type=str ) parser.add_argument("--sample_rates", default="15,4,4,15", type=str) parser.add_argument( "--general_segdet_data", default="objects365||cocostuff||paco_lvis", type=str, ) parser.add_argument("--general_segdet_sample_rates", default="2,1,1", type=str) parser.add_argument( "--refer_seg_data", default="refclef||refcoco||refcoco+||refcocog", type=str ) parser.add_argument("--vqa_data", default="possible_locations_conv_86k||llava_instruct_80k", type=str) parser.add_argument("--vqa_sample_rates", default="2,1", type=str) parser.add_argument("--val_dataset", default="refcoco|unc|val", type=str) parser.add_argument("--dataset_dir", default="data", type=str) parser.add_argument("--log_base_dir", default="./runs", type=str) parser.add_argument("--exp_name", default="vsm", type=str) parser.add_argument("--epochs", default=40, type=int) parser.add_argument("--steps_per_epoch", default=2500, type=int) parser.add_argument( "--batch_size", default=4, type=int, help="batch size per device per step" ) parser.add_argument( "--grad_accumulation_steps", default=2, type=int, ) parser.add_argument("--val_batch_size", default=1, type=int) parser.add_argument("--workers", default=2, type=int) parser.add_argument("--lr", default=0.0001, type=float) parser.add_argument("--ce_loss_weight", default=1.0, type=float) parser.add_argument("--dice_loss_weight", default=0.5, type=float) parser.add_argument("--bce_loss_weight", default=2.0, type=float) parser.add_argument("--det_loss_weight", default=0.1, type=float) parser.add_argument("--lora_alpha", default=16, type=int) parser.add_argument("--lora_dropout", default=0.05, type=float) parser.add_argument("--lora_target_modules", default="q_proj,v_proj", type=str) parser.add_argument("--explanatory", default=0.1, type=float) parser.add_argument("--beta1", default=0.9, type=float) parser.add_argument("--beta2", default=0.95, type=float) parser.add_argument("--num_classes_per_sample", default=3, type=int) parser.add_argument("--exclude_val", action="store_true", default=False) parser.add_argument("--no_eval", action="store_true", default=False) parser.add_argument("--out_dim", default=512, type=int) parser.add_argument("--weight", type=str) parser.add_argument("--resume", default="", type=str) parser.add_argument("--print_freq", default=1, type=int) parser.add_argument("--start_epoch", default=0, type=int) parser.add_argument("--gradient_checkpointing", action="store_true", default=True) parser.add_argument("--train_mask_decoder", action="store_true", default=True) parser.add_argument("--use_mm_start_end", action="store_true", default=True) parser.add_argument("--auto_resume", action="store_true", default=False) parser.add_argument( "--conv_type", default="llava_v1", type=str, choices=["llava_v1", "llava_llama_2"], ) return parser.parse_args(args) def box_cxcywh_to_xyxy(x): x_c, y_c, w, h = x.unbind(1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch.stack(b, dim=1) def iou(bbox1, bbox2): x1 = max(bbox1[0], bbox2[0]) y1 = max(bbox1[1], bbox2[1]) x2 = min(bbox1[2], bbox2[2]) y2 = min(bbox1[3], bbox2[3]) w1 = bbox1[2] - bbox1[0] h1 = bbox1[3] - bbox1[1] w2 = bbox2[2] - bbox2[0] h2 = bbox2[3] - bbox2[1] inter_area = max(0, x2 - x1) * max(0, y2 - y1) return inter_area/(w1*h1+w2*h2-inter_area) def main(args): args = parse_args(args) args.log_dir = os.path.join(args.log_base_dir, args.exp_name) if args.local_rank == 0: os.makedirs(args.log_dir, exist_ok=True) writer = SummaryWriter(args.log_dir) else: writer = None # Create model tokenizer = transformers.AutoTokenizer.from_pretrained( args.version, cache_dir=None, model_max_length=args.model_max_length, padding_side="right", use_fast=False, ) tokenizer.pad_token = tokenizer.unk_token num_added_tokens = tokenizer.add_tokens("[LOC]") args.loc_token_idx = tokenizer("[LOC]", add_special_tokens=False).input_ids[0] if args.use_mm_start_end: tokenizer.add_tokens(
def parse_args(args): parser = argparse.ArgumentParser(description="VisualSearch Model Training") parser.add_argument("--local_rank", default=0, type=int, help="node rank") parser.add_argument( "--version", default="LLaVA-7B-v1.1" ) parser.add_argument( "--precision", default="bf16", type=str, choices=["fp32", "bf16", "fp16"], help="precision for training", ) parser.add_argument("--model_max_length", default=512, type=int) parser.add_argument("--lora_r", default=8, type=int) parser.add_argument( "--vision-tower", default="openai/clip-vit-large-patch14", type=str ) parser.add_argument("--load_in_8bit", action="store_true", default=False) parser.add_argument("--load_in_4bit", action="store_true", default=False) parser.add_argument( "--dataset", default="general_segdet||refer_seg||mixed_grounding||vqa", type=str ) parser.add_argument("--sample_rates", default="15,4,4,15", type=str) parser.add_argument( "--general_segdet_data", default="objects365||cocostuff||paco_lvis", type=str, ) parser.add_argument("--general_segdet_sample_rates", default="2,1,1", type=str) parser.add_argument( "--refer_seg_data", default="refclef||refcoco||refcoco+||refcocog", type=str ) parser.add_argument("--vqa_data", default="possible_locations_conv_86k||llava_instruct_80k", type=str) parser.add_argument("--vqa_sample_rates", default="2,1", type=str) parser.add_argument("--val_dataset", default="refcoco|unc|val", type=str) parser.add_argument("--dataset_dir", default="data", type=str) parser.add_argument("--log_base_dir", default="./runs", type=str) parser.add_argument("--exp_name", default="vsm", type=str) parser.add_argument("--epochs", default=40, type=int) parser.add_argument("--steps_per_epoch", default=2500, type=int) parser.add_argument( "--batch_size", default=4, type=int, help="batch size per device per step" ) parser.add_argument( "--grad_accumulation_steps", default=2, type=int, ) parser.add_argument("--val_batch_size", default=1, type=int) parser.add_argument("--workers", default=2, type=int) parser.add_argument("--lr", default=0.0001, type=float) parser.add_argument("--ce_loss_weight", default=1.0, type=float) parser.add_argument("--dice_loss_weight", default=0.5, type=float) parser.add_argument("--bce_loss_weight", default=2.0, type=float) parser.add_argument("--det_loss_weight", default=0.1, type=float) parser.add_argument("--lora_alpha", default=16, type=int) parser.add_argument("--lora_dropout", default=0.05, type=float) parser.add_argument("--lora_target_modules", default="q_proj,v_proj", type=str) parser.add_argument("--explanatory", default=0.1, type=float) parser.add_argument("--beta1", default=0.9, type=float) parser.add_argument("--beta2", default=0.95, type=float) parser.add_argument("--num_classes_per_sample", default=3, type=int) parser.add_argument("--exclude_val", action="store_true", default=False) parser.add_argument("--no_eval", action="store_true", default=False) parser.add_argument("--out_dim", default=512, type=int) parser.add_argument("--weight", type=str) parser.add_argument("--resume", default="", type=str) parser.add_argument("--print_freq", default=1, type=int) parser.add_argument("--start_epoch", default=0, type=int) parser.add_argument("--gradient_checkpointing", action="store_true", default=True) parser.add_argument("--train_mask_decoder", action="store_true", default=True) parser.add_argument("--use_mm_start_end", action="store_true", default=True) parser.add_argument("--auto_resume", action="store_true", default=False) parser.add_argument( "--conv_type", default="llava_v1", type=str, choices=["llava_v1", "llava_llama_2"], ) return parser.parse_args(args) def box_cxcywh_to_xyxy(x): x_c, y_c, w, h = x.unbind(1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch.stack(b, dim=1) def iou(bbox1, bbox2): x1 = max(bbox1[0], bbox2[0]) y1 = max(bbox1[1], bbox2[1]) x2 = min(bbox1[2], bbox2[2]) y2 = min(bbox1[3], bbox2[3]) w1 = bbox1[2] - bbox1[0] h1 = bbox1[3] - bbox1[1] w2 = bbox2[2] - bbox2[0] h2 = bbox2[3] - bbox2[1] inter_area = max(0, x2 - x1) * max(0, y2 - y1) return inter_area/(w1*h1+w2*h2-inter_area) def main(args): args = parse_args(args) args.log_dir = os.path.join(args.log_base_dir, args.exp_name) if args.local_rank == 0: os.makedirs(args.log_dir, exist_ok=True) writer = SummaryWriter(args.log_dir) else: writer = None # Create model tokenizer = transformers.AutoTokenizer.from_pretrained( args.version, cache_dir=None, model_max_length=args.model_max_length, padding_side="right", use_fast=False, ) tokenizer.pad_token = tokenizer.unk_token num_added_tokens = tokenizer.add_tokens("[LOC]") args.loc_token_idx = tokenizer("[LOC]", add_special_tokens=False).input_ids[0] if args.use_mm_start_end: tokenizer.add_tokens(
[DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
5
2023-12-15 14:58:24+00:00
16k
foocker/Bert-VITS2-Faster
train_ms.py
[ { "identifier": "config", "path": "config.py", "snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, ...
import platform import os import torch import torch.distributed as dist import logging import argparse import commons import utils from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from config import config from data_utils import ( TextAudioSpeakerLoader, TextAudioSpeakerCollate, DistributedBucketSampler, ) from models import ( SynthesizerTrn, MultiPeriodDiscriminator, DurationDiscriminator, ) from losses import generator_loss, discriminator_loss, feature_loss, kl_loss from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols
13,311
y, y_lengths, speakers, tone, language, bert, ja_bert, en_bert, ) in tqdm(enumerate(train_loader)): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = ( net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step ) net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(local_rank, non_blocking=True), x_lengths.cuda( local_rank, non_blocking=True ) spec, spec_lengths = spec.cuda( local_rank, non_blocking=True ), spec_lengths.cuda(local_rank, non_blocking=True) y, y_lengths = y.cuda(local_rank, non_blocking=True), y_lengths.cuda( local_rank, non_blocking=True ) speakers = speakers.cuda(local_rank, non_blocking=True) tone = tone.cuda(local_rank, non_blocking=True) language = language.cuda(local_rank, non_blocking=True) bert = bert.cuda(local_rank, non_blocking=True) ja_bert = ja_bert.cuda(local_rank, non_blocking=True) en_bert = en_bert.cuda(local_rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): ( y_hat, l_length, attn, ids_slice, x_mask, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_), ) = net_g( x, x_lengths, spec, spec_lengths, speakers, tone, language, bert, ja_bert, en_bert, ) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax, ) y_mel = commons.slice_segments( mel, ids_slice, hps.train.segment_size // hps.data.hop_length ) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax, ) y = commons.slice_segments( y, ids_slice * hps.data.hop_length, hps.train.segment_size ) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( y_d_hat_r, y_d_hat_g ) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc( hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach() ) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all ( loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g, ) = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cudnn.benchmark = True torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 torch.backends.cuda.enable_math_sdp(True) global_step = 0 def run(): # 环境变量解析 envs = config.train_ms_config.env for env_name, env_value in envs.items(): if env_name not in os.environ.keys(): print("加载config中的配置{}".format(str(env_value))) os.environ[env_name] = str(env_value) print( "加载环境变量 \nMASTER_ADDR: {},\nMASTER_PORT: {},\nWORLD_SIZE: {},\nRANK: {},\nLOCAL_RANK: {}".format( os.environ["MASTER_ADDR"], os.environ["MASTER_PORT"], os.environ["WORLD_SIZE"], os.environ["RANK"], os.environ["LOCAL_RANK"], ) ) # 多卡训练设置 backend = "nccl" if platform.system() == "Windows": backend = "gloo" dist.init_process_group( backend=backend, init_method="env://", # If Windows,switch to gloo backend. ) # Use torchrun instead of mp.spawn rank = dist.get_rank() local_rank = int(os.environ["LOCAL_RANK"]) n_gpus = dist.get_world_size() # 命令行/config.yml配置解析 # hps = utils.get_hparams() parser = argparse.ArgumentParser() # 非必要不建议使用命令行配置,请使用config.yml文件 parser.add_argument( "-c", "--config", type=str, default=config.train_ms_config.config_path, help="JSON file for configuration", ) parser.add_argument( "-m", "--model", type=str, help="数据集文件夹路径,请注意,数据不再默认放在/logs文件夹下。如果需要用命令行配置,请声明相对于根目录的路径", default=config.dataset_path, ) args = parser.parse_args() model_dir = os.path.join(args.model, config.train_ms_config.model) if not os.path.exists(model_dir): os.makedirs(model_dir) hps = utils.get_hparams_from_file(args.config) hps.model_dir = model_dir # 比较路径是否相同 if os.path.realpath(args.config) != os.path.realpath( config.train_ms_config.config_path ): with open(args.config, "r", encoding="utf-8") as f: data = f.read() with open(config.train_ms_config.config_path, "w", encoding="utf-8") as f: f.write(data) torch.manual_seed(hps.train.seed) torch.cuda.set_device(local_rank) 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")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, ) collate_fn = TextAudioSpeakerCollate() train_loader = DataLoader( train_dataset, num_workers=16, shuffle=False, pin_memory=True, collate_fn=collate_fn, batch_sampler=train_sampler, persistent_workers=True, prefetch_factor=4, ) # DataLoader config could be adjusted. if rank == 0: eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) eval_loader = DataLoader( eval_dataset, num_workers=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False, collate_fn=collate_fn, ) if ( "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas is True ): print("Using noise scaled MAS for VITS2") mas_noise_scale_initial = 0.01 noise_scale_delta = 2e-6 else: print("Using normal MAS for VITS1") 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 is True ): print("Using duration discriminator for VITS2") net_dur_disc = DurationDiscriminator( hps.model.hidden_channels, hps.model.hidden_channels, 3, 0.1, gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, ).cuda(local_rank) if ( "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder is True ): if hps.data.n_speakers == 0: raise ValueError( "n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model" ) else: print("Using normal encoder for VITS1") net_g = SynthesizerTrn( len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, mas_noise_scale_initial=mas_noise_scale_initial, noise_scale_delta=noise_scale_delta, **hps.model, ).cuda(local_rank) net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(local_rank) optim_g = torch.optim.AdamW( filter(lambda p: p.requires_grad, net_g.parameters()), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) optim_d = torch.optim.AdamW( net_d.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) if net_dur_disc is not None: optim_dur_disc = torch.optim.AdamW( net_dur_disc.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) else: optim_dur_disc = None net_g = DDP(net_g, device_ids=[local_rank]) net_d = DDP(net_d, device_ids=[local_rank]) dur_resume_lr = None if net_dur_disc is not None: net_dur_disc = DDP( net_dur_disc, device_ids=[local_rank], find_unused_parameters=True ) # 下载底模 if config.train_ms_config.base["use_base_model"]: utils.download_checkpoint( hps.model_dir, config.train_ms_config.base, token=config.openi_token, mirror=config.mirror, ) try: if net_dur_disc is not None: _, _, dur_resume_lr, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, skip_optimizer=hps.train.skip_optimizer if "skip_optimizer" in hps.train else True, ) _, optim_g, g_resume_lr, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g, skip_optimizer=hps.train.skip_optimizer if "skip_optimizer" in hps.train else True, ) _, optim_d, d_resume_lr, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d, skip_optimizer=hps.train.skip_optimizer if "skip_optimizer" in hps.train else True, ) if not optim_g.param_groups[0].get("initial_lr"): optim_g.param_groups[0]["initial_lr"] = g_resume_lr if not optim_d.param_groups[0].get("initial_lr"): optim_d.param_groups[0]["initial_lr"] = d_resume_lr if not optim_dur_disc.param_groups[0].get("initial_lr"): optim_dur_disc.param_groups[0]["initial_lr"] = dur_resume_lr epoch_str = max(epoch_str, 1) global_step = (epoch_str - 1) * len(train_loader) print( f"******************检测到模型存在,epoch为 {epoch_str},gloabl step为 {global_step}*********************" ) except Exception as e: print(e) epoch_str = 1 global_step = 0 scheduler_g = torch.optim.lr_scheduler.ExponentialLR( optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) scheduler_d = torch.optim.lr_scheduler.ExponentialLR( optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) if net_dur_disc is not None: if not optim_dur_disc.param_groups[0].get("initial_lr"): optim_dur_disc.param_groups[0]["initial_lr"] = dur_resume_lr scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR( optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) else: scheduler_dur_disc = None scaler = GradScaler(enabled=hps.train.fp16_run) for epoch in range(epoch_str, hps.train.epochs + 1): if rank == 0: train_and_evaluate( rank, local_rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval], ) else: train_and_evaluate( rank, local_rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None, ) scheduler_g.step() scheduler_d.step() if net_dur_disc is not None: scheduler_dur_disc.step() def train_and_evaluate( rank, local_rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers, ): net_g, net_d, net_dur_disc = nets optim_g, optim_d, optim_dur_disc = optims scheduler_g, scheduler_d, scheduler_dur_disc = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() if net_dur_disc is not None: net_dur_disc.train() for batch_idx, ( x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert, ja_bert, en_bert, ) in tqdm(enumerate(train_loader)): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = ( net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step ) net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(local_rank, non_blocking=True), x_lengths.cuda( local_rank, non_blocking=True ) spec, spec_lengths = spec.cuda( local_rank, non_blocking=True ), spec_lengths.cuda(local_rank, non_blocking=True) y, y_lengths = y.cuda(local_rank, non_blocking=True), y_lengths.cuda( local_rank, non_blocking=True ) speakers = speakers.cuda(local_rank, non_blocking=True) tone = tone.cuda(local_rank, non_blocking=True) language = language.cuda(local_rank, non_blocking=True) bert = bert.cuda(local_rank, non_blocking=True) ja_bert = ja_bert.cuda(local_rank, non_blocking=True) en_bert = en_bert.cuda(local_rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): ( y_hat, l_length, attn, ids_slice, x_mask, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_), ) = net_g( x, x_lengths, spec, spec_lengths, speakers, tone, language, bert, ja_bert, en_bert, ) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax, ) y_mel = commons.slice_segments( mel, ids_slice, hps.train.segment_size // hps.data.hop_length ) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax, ) y = commons.slice_segments( y, ids_slice * hps.data.hop_length, hps.train.segment_size ) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( y_d_hat_r, y_d_hat_g ) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc( hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach() ) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all ( loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g, ) = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
loss_fm = feature_loss(fmap_r, fmap_g)
9
2023-12-18 09:53:41+00:00
16k
sinoyou/nelf-pro
nerfstudio/cameras/camera_paths.py
[ { "identifier": "camera_utils", "path": "nerfstudio/cameras/camera_utils.py", "snippet": "_EPS = np.finfo(float).eps * 4.0\n M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]\n K = np.array(\n [\n [m00 - m11 - m22, 0.0, 0.0, 0.0],\n [m01 + m10,...
from typing import Any, Dict, Optional, Tuple from nerfstudio.cameras import camera_utils from nerfstudio.cameras.camera_utils import get_interpolated_poses_many from nerfstudio.cameras.cameras import Cameras from nerfstudio.viewer.server.utils import three_js_perspective_camera_focal_length import numpy as np import torch import nerfstudio.utils.poses as pose_utils
12,430
# 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 for camera paths. """ def get_interpolated_camera_path(cameras: Cameras, steps: int) -> Cameras: """Generate a camera path between two cameras. Args: cameras: Cameras object containing intrinsics of all cameras. steps: The number of steps to interpolate between the two cameras. Returns: A new set of cameras along a path. """ Ks = cameras.get_intrinsics_matrices().cpu().numpy() poses = cameras.camera_to_worlds().cpu().numpy() poses, Ks = get_interpolated_poses_many(poses, Ks, steps_per_transition=steps) cameras = Cameras(fx=Ks[:, 0, 0], fy=Ks[:, 1, 1], cx=Ks[0, 0, 2], cy=Ks[0, 1, 2], camera_to_worlds=poses) return cameras # def get_path_from_json(camera_path, probe_config) -> Cameras: # data = camera_path # fl_x = data["fx"] # fl_y = data["fy"] # cx = data["cx"] # cy = data["cy"] # width = data["w"] # height = data["h"] # transforms = [x['transform_matrix'] for x in data['frames']] # transforms = torch.tensor(transforms) # return Cameras(fx=fl_x, fy=fl_y, cx=cx, cy=cy, width=width, height=height, camera_to_worlds=transforms, probe_config=probe_config) def get_path_from_json(camera_path: Dict[str, Any], probe_config) -> Cameras: """Takes a camera path dictionary and returns a trajectory as a Camera instance. Args: camera_path: A dictionary of the camera path information coming from the viewer. Returns: A Cameras instance with the camera path. """ image_height = camera_path["render_height"] image_width = camera_path["render_width"] c2ws = [] fxs = [] fys = [] for camera in camera_path["camera_path"]: # pose c2w = torch.tensor(camera["camera_to_world"]).view(4, 4)[:3] c2ws.append(c2w) # field of view fov = camera["fov"]
# 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 for camera paths. """ def get_interpolated_camera_path(cameras: Cameras, steps: int) -> Cameras: """Generate a camera path between two cameras. Args: cameras: Cameras object containing intrinsics of all cameras. steps: The number of steps to interpolate between the two cameras. Returns: A new set of cameras along a path. """ Ks = cameras.get_intrinsics_matrices().cpu().numpy() poses = cameras.camera_to_worlds().cpu().numpy() poses, Ks = get_interpolated_poses_many(poses, Ks, steps_per_transition=steps) cameras = Cameras(fx=Ks[:, 0, 0], fy=Ks[:, 1, 1], cx=Ks[0, 0, 2], cy=Ks[0, 1, 2], camera_to_worlds=poses) return cameras # def get_path_from_json(camera_path, probe_config) -> Cameras: # data = camera_path # fl_x = data["fx"] # fl_y = data["fy"] # cx = data["cx"] # cy = data["cy"] # width = data["w"] # height = data["h"] # transforms = [x['transform_matrix'] for x in data['frames']] # transforms = torch.tensor(transforms) # return Cameras(fx=fl_x, fy=fl_y, cx=cx, cy=cy, width=width, height=height, camera_to_worlds=transforms, probe_config=probe_config) def get_path_from_json(camera_path: Dict[str, Any], probe_config) -> Cameras: """Takes a camera path dictionary and returns a trajectory as a Camera instance. Args: camera_path: A dictionary of the camera path information coming from the viewer. Returns: A Cameras instance with the camera path. """ image_height = camera_path["render_height"] image_width = camera_path["render_width"] c2ws = [] fxs = [] fys = [] for camera in camera_path["camera_path"]: # pose c2w = torch.tensor(camera["camera_to_world"]).view(4, 4)[:3] c2ws.append(c2w) # field of view fov = camera["fov"]
focal_length = three_js_perspective_camera_focal_length(fov, image_height)
3
2023-12-15 20:07:22+00:00
16k
amazon-science/c2f-seg
src/image_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 matplotlib.pyplot as plt 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.image_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 evaluation_image from utils.loss import CrossEntropyLoss from tqdm import tqdm
11,249
mask_out = [] for t in range(start_iter, T): logits = self.transformer(img_feat[-1], src_indices, cur_ids, mask=None) # [B, L, N] logits = logits[..., :-1] logits = self.top_k_logits(logits, k=3) probs = F.softmax(logits, dim=-1) # convert logits into probs [B, 256, vocab_size+1] sampled_ids = torch.distributions.categorical.Categorical(probs=probs).sample() # [B, L] unknown_map = (cur_ids == self.mask_token_idx) # which tokens need to be sampled -> bool [B, 256] sampled_ids = torch.where(unknown_map, sampled_ids, cur_ids) # replace all -1 with their samples and leave the others untouched [B, 256] seq_out.append(sampled_ids) mask_out.append(1. * unknown_map) ratio = 1. * (t + 1) / T # just a percentage e.g. 1 / 12 mask_ratio = gamma(ratio) selected_probs = probs.gather(dim=-1, index=sampled_ids.unsqueeze(-1)).squeeze(-1) selected_probs = torch.where(unknown_map, selected_probs, torch.Tensor([np.inf]).to(logits.device)) # ignore tokens which are already sampled [B, 256] mask_len = torch.unsqueeze(torch.floor(unknown_number_in_the_beginning * mask_ratio), 1) # floor(256 * 0.99) = 254 --> [254, 254, 254, 254, ....] (B x 1) mask_len = torch.maximum(torch.ones_like(mask_len), torch.minimum(torch.sum(unknown_map, dim=-1, keepdim=True) - 1, mask_len)) # Adds noise for randomness masking = self.mask_by_random_topk(mask_len, selected_probs, temperature=self.choice_temperature * (1. - ratio)) # Masks tokens with lower confidence. cur_ids = torch.where(masking, self.mask_token_idx, sampled_ids) # [B, L] seq_ids = torch.stack(seq_out, dim=1) # [B, T, L] quant_z = self.g_model.quantize.get_codebook_entry(seq_ids[:,-1,:].reshape(-1), shape=bhwc) pred_fm_crop = self.g_model.decode(quant_z) pred_fm_crop = pred_fm_crop.mean(dim=1, keepdim=True) pred_fm_crop_old = torch.clamp(pred_fm_crop, min=0, max=1) pred_vm_crop, pred_fm_crop = self.refine_module(img_feat, pred_fm_crop_old) pred_vm_crop = F.interpolate(pred_vm_crop, size=(256, 256), mode="nearest") pred_vm_crop = torch.sigmoid(pred_vm_crop) loss_vm = self.refine_criterion(pred_vm_crop, meta['vm_crop_gt']) # pred_vm_crop = (pred_vm_crop>=0.5).to(torch.float32) pred_fm_crop = F.interpolate(pred_fm_crop, size=(256, 256), mode="nearest") pred_fm_crop = torch.sigmoid(pred_fm_crop) loss_fm = self.refine_criterion(pred_fm_crop, meta['fm_crop']) # pred_fm_crop = (pred_fm_crop>=0.5).to(torch.float32) pred_vm = self.align_raw_size(pred_vm_crop, meta['obj_position'], meta["vm_pad"], meta) pred_fm = self.align_raw_size(pred_fm_crop, meta['obj_position'], meta["vm_pad"], meta) # visualization self.visualize(pred_vm, pred_fm, meta, mode, iter) loss_eval = self.loss_and_evaluation(pred_fm, meta, iter, mode, pred_vm=pred_vm) loss_eval["loss_fm"] = loss_fm loss_eval["loss_vm"] = loss_vm return loss_eval def visualize(self, pred_vm, pred_fm, meta, mode, iteration): pred_fm = pred_fm.squeeze() pred_vm = pred_vm.squeeze() gt_vm = meta["vm_no_crop"].squeeze() gt_fm = meta["fm_no_crop"].squeeze() to_plot = torch.cat((pred_vm, pred_fm, gt_vm, gt_fm)).cpu().numpy() save_dir = os.path.join(self.root_path, '{}_samples'.format(mode)) image_id, anno_id= meta["img_id"], meta["anno_id"] plt.imsave("{}/{}_{}_{}.png".format(save_dir, iteration, int(image_id.item()), int(anno_id.item())), to_plot) # def visualize_crop(self, pred_vm, pred_fm, meta, mode, count, pred_fm_crop_old): # pred_fm = pred_fm.squeeze() # pred_vm = pred_vm.squeeze() # pred_fm_crop_old = pred_fm_crop_old.squeeze() # gt_vm = meta["vm_crop"].squeeze() # gt_fm = meta["fm_crop"].squeeze() # to_plot = torch.cat((pred_vm, gt_vm, pred_fm_crop_old, pred_fm, gt_fm)).cpu().numpy() # save_dir = os.path.join(self.root_path, '{}_samples'.format(mode)) # image_id, anno_id= meta["img_id"], meta["anno_id"] # plt.imsave("{}/{}_{}_{}_{}.png".format(save_dir, count, int(image_id.item()), int(anno_id.item()), "crop"), to_plot) def create_inputs_tokens_normal(self, num, device): self.num_latent_size = self.config['resolution'] // self.config['patch_size'] blank_tokens = torch.ones((num, self.num_latent_size ** 2), device=device) masked_tokens = self.mask_token_idx * blank_tokens return masked_tokens.to(torch.int64) def gamma_func(self, mode="cosine"): if mode == "linear": return lambda r: 1 - r elif mode == "cosine": return lambda r: np.cos(r * np.pi / 2) elif mode == "square": return lambda r: 1 - r ** 2 elif mode == "cubic": return lambda r: 1 - r ** 3 elif mode == "log": return lambda r, total_unknown: - np.log2(r) / np.log2(total_unknown) else: raise NotImplementedError def mask_by_random_topk(self, mask_len, probs, temperature=1.0): confidence = torch.log(probs) + temperature * torch.distributions.gumbel.Gumbel(0, 1).sample(probs.shape).to(probs.device) sorted_confidence, _ = torch.sort(confidence, dim=-1) # from small to large # Obtains cut off threshold given the mask lengths. # cut_off = torch.take_along_dim(sorted_confidence, mask_len.to(torch.long), dim=-1) cut_off = sorted_confidence.gather(dim=-1, index=mask_len.to(torch.long)) # Masks tokens with lower confidence. masking = (confidence < cut_off) return masking def load(self, is_test=False, prefix=None): if prefix is not None: transformer_path = self.transformer_path + prefix + '.pth' else: transformer_path = self.transformer_path + '_last.pth' if self.config.restore or is_test: if os.path.exists(transformer_path): print('Rank {} is loading {} Transformer...'.format(self.rank, transformer_path)) data = torch.load(transformer_path, map_location="cpu")
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.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'] 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, num_training_steps=config.max_iters) self.rank = dist.get_rank() self.gamma = self.gamma_func(mode=config.gamma_mode) self.mask_token_idx = config.vocab_size self.choice_temperature = 4.5 self.Image_W = config.Image_W self.Image_H = config.Image_H self.patch_W = config.patch_W self.patch_H = config.patch_H @torch.no_grad() def encode_to_z(self, x, mask=None): if len(x.size())==5: x = x[0] quant_z, _, info = self.g_model.encode(x.float(), mask) # [B,D,H,W] indices = info[2].view(quant_z.shape[0], -1) # [B, L] return quant_z, indices def get_attn_map(self, feature, guidance): guidance = F.interpolate(guidance, scale_factor=(1/16)) b,c,h,w = guidance.shape q = torch.flatten(guidance, start_dim=2) v = torch.flatten(feature, start_dim=2) k = v * q k = k.sum(dim=-1, keepdim=True) / (q.sum(dim=-1, keepdim=True) + 1e-6) attn = (k.transpose(-2, -1) @ v) / 1 attn = F.softmax(attn, dim=-1) attn = attn.reshape(b, c, h, w) return attn def get_losses(self, meta): self.iteration += 1 z_loss = 0 img_feat = self.img_encoder(meta['img_crop'].permute((0,3,1,2)).to(torch.float32)) _, src_indices = self.encode_to_z(meta['vm_crop']) _, tgt_indices = self.encode_to_z(meta['fm_crop']) bhwc = (_.shape[0], _.shape[2], _.shape[3], _.shape[1]) r = np.maximum(self.gamma(np.random.uniform()), self.config.min_mask_rate) r = math.floor(r * tgt_indices.shape[1]) sample = torch.rand(tgt_indices.shape, device=tgt_indices.device).topk(r, dim=1).indices random_mask = torch.zeros(tgt_indices.shape, dtype=torch.bool, device=tgt_indices.device) random_mask.scatter_(dim=1, index=sample, value=True) # [B, L] # concat mask mask = random_mask masked_indices = self.mask_token_idx * torch.ones_like(tgt_indices, device=tgt_indices.device) # [B, L] z_indices = (~mask) * tgt_indices + mask * masked_indices # [B, L] logits_z = self.transformer(img_feat[-1], src_indices, z_indices, mask=None) target = tgt_indices z_loss = self.criterion(logits_z.view(-1, logits_z.size(-1)), target.view(-1)) with torch.no_grad(): logits_z = logits_z[..., :-1] logits_z = self.top_k_logits(logits_z, k=5) probs = F.softmax(logits_z, dim=-1) seq_ids = torch.distributions.categorical.Categorical(probs=probs).sample() # [B, L] quant_z = self.g_model.quantize.get_codebook_entry(seq_ids.reshape(-1), shape=bhwc) pred_fm_crop = self.g_model.decode(quant_z) pred_fm_crop = pred_fm_crop.mean(dim=1, keepdim=True) pred_fm_crop = torch.clamp(pred_fm_crop, min=0, max=1) pred_vm_crop, pred_fm_crop = self.refine_module(img_feat, pred_fm_crop.detach()) pred_vm_crop = F.interpolate(pred_vm_crop, size=(256, 256), mode="nearest") pred_vm_crop = torch.sigmoid(pred_vm_crop) loss_vm = self.refine_criterion(pred_vm_crop, meta['vm_crop_gt']) # pred_vm_crop = (pred_vm_crop>=0.5).to(torch.float32) pred_fm_crop = F.interpolate(pred_fm_crop, size=(256, 256), mode="nearest") pred_fm_crop = torch.sigmoid(pred_fm_crop) loss_fm = self.refine_criterion(pred_fm_crop, meta['fm_crop']) # pred_fm_crop = (pred_fm_crop>=0.5).to(torch.float32) logs = [ ("z_loss", z_loss.item()), ("loss_vm", loss_vm.item()), ("loss_fm", loss_fm.item()), ] return z_loss, loss_vm+loss_fm, logs def align_raw_size(self, full_mask, obj_position, vm_pad, meta): vm_np_crop = meta["vm_no_crop"].squeeze() H, W = vm_np_crop.shape[-2], vm_np_crop.shape[-1] bz, seq_len = full_mask.shape[:2] new_full_mask = torch.zeros((bz, seq_len, H, W)).to(torch.float32).cuda() if len(vm_pad.shape)==3: vm_pad = vm_pad[0] obj_position = obj_position[0] for b in range(bz): paddings = vm_pad[b] position = obj_position[b] new_fm = full_mask[ b, :, :-int(paddings[0]) if int(paddings[0]) !=0 else None, :-int(paddings[1]) if int(paddings[1]) !=0 else None ] vx_min = int(position[0]) vx_max = min(H, int(position[1])+1) vy_min = int(position[2]) vy_max = min(W, int(position[3])+1) resize = transforms.Resize([vx_max-vx_min, vy_max-vy_min]) try: new_fm = resize(new_fm) new_full_mask[b, :, vx_min:vx_max, vy_min:vy_max] = new_fm[0] except: new_fm = new_fm return new_full_mask def loss_and_evaluation(self, pred_fm, meta, iter, mode, pred_vm=None): loss_eval = {} pred_fm = pred_fm.squeeze() counts = meta["counts"].reshape(-1).to(pred_fm.device) fm_no_crop = meta["fm_no_crop"].squeeze() vm_no_crop = meta["vm_no_crop"].squeeze() pred_vm = pred_vm.squeeze() # post-process pred_fm = (pred_fm > 0.5).to(torch.int64) pred_vm = (pred_vm > 0.5).to(torch.int64) iou, invisible_iou_, iou_count = evaluation_image((pred_fm > 0.5).to(torch.int64), fm_no_crop, counts, meta, self.save_eval_dict) loss_eval["iou"] = iou loss_eval["invisible_iou_"] = invisible_iou_ loss_eval["occ_count"] = iou_count loss_eval["iou_count"] = torch.Tensor([1]).cuda() pred_fm_post = pred_fm + vm_no_crop pred_fm_post = (pred_fm_post>0.5).to(torch.int64) iou_post, invisible_iou_post, iou_count_post = evaluation_image(pred_fm_post, fm_no_crop, counts, meta, self.save_eval_dict) loss_eval["iou_post"] = iou_post loss_eval["invisible_iou_post"] = invisible_iou_post return loss_eval def backward(self, loss=None): self.opt.zero_grad() loss.backward() self.opt.step() self.sche.step() def top_k_logits(self, logits, k): v, ix = torch.topk(logits, k) out = logits.clone() out[out < v[..., [-1]]] = -float('Inf') return out @torch.no_grad() def batch_predict_maskgit(self, meta, iter, mode, T=3, start_iter=0): ''' :param x:[B,3,H,W] image :param c:[b,X,H,W] condition :param mask: [1,1,H,W] mask ''' self.sample_iter += 1 img_feat = self.img_encoder(meta['img_crop'].permute((0,3,1,2)).to(torch.float32)) _, src_indices = self.encode_to_z(meta['vm_crop']) # _, tgt_indices = self.encode_to_z(meta['fm_crop']) bhwc = (_.shape[0], _.shape[2], _.shape[3], _.shape[1]) masked_indices = self.mask_token_idx * torch.ones_like(src_indices, device=src_indices.device) # [B, L] unknown_number_in_the_beginning = torch.sum(masked_indices == self.mask_token_idx, dim=-1) # [B] gamma = self.gamma_func("cosine") cur_ids = masked_indices # [B, L] seq_out = [] mask_out = [] for t in range(start_iter, T): logits = self.transformer(img_feat[-1], src_indices, cur_ids, mask=None) # [B, L, N] logits = logits[..., :-1] logits = self.top_k_logits(logits, k=3) probs = F.softmax(logits, dim=-1) # convert logits into probs [B, 256, vocab_size+1] sampled_ids = torch.distributions.categorical.Categorical(probs=probs).sample() # [B, L] unknown_map = (cur_ids == self.mask_token_idx) # which tokens need to be sampled -> bool [B, 256] sampled_ids = torch.where(unknown_map, sampled_ids, cur_ids) # replace all -1 with their samples and leave the others untouched [B, 256] seq_out.append(sampled_ids) mask_out.append(1. * unknown_map) ratio = 1. * (t + 1) / T # just a percentage e.g. 1 / 12 mask_ratio = gamma(ratio) selected_probs = probs.gather(dim=-1, index=sampled_ids.unsqueeze(-1)).squeeze(-1) selected_probs = torch.where(unknown_map, selected_probs, torch.Tensor([np.inf]).to(logits.device)) # ignore tokens which are already sampled [B, 256] mask_len = torch.unsqueeze(torch.floor(unknown_number_in_the_beginning * mask_ratio), 1) # floor(256 * 0.99) = 254 --> [254, 254, 254, 254, ....] (B x 1) mask_len = torch.maximum(torch.ones_like(mask_len), torch.minimum(torch.sum(unknown_map, dim=-1, keepdim=True) - 1, mask_len)) # Adds noise for randomness masking = self.mask_by_random_topk(mask_len, selected_probs, temperature=self.choice_temperature * (1. - ratio)) # Masks tokens with lower confidence. cur_ids = torch.where(masking, self.mask_token_idx, sampled_ids) # [B, L] seq_ids = torch.stack(seq_out, dim=1) # [B, T, L] quant_z = self.g_model.quantize.get_codebook_entry(seq_ids[:,-1,:].reshape(-1), shape=bhwc) pred_fm_crop = self.g_model.decode(quant_z) pred_fm_crop = pred_fm_crop.mean(dim=1, keepdim=True) pred_fm_crop_old = torch.clamp(pred_fm_crop, min=0, max=1) pred_vm_crop, pred_fm_crop = self.refine_module(img_feat, pred_fm_crop_old) pred_vm_crop = F.interpolate(pred_vm_crop, size=(256, 256), mode="nearest") pred_vm_crop = torch.sigmoid(pred_vm_crop) loss_vm = self.refine_criterion(pred_vm_crop, meta['vm_crop_gt']) # pred_vm_crop = (pred_vm_crop>=0.5).to(torch.float32) pred_fm_crop = F.interpolate(pred_fm_crop, size=(256, 256), mode="nearest") pred_fm_crop = torch.sigmoid(pred_fm_crop) loss_fm = self.refine_criterion(pred_fm_crop, meta['fm_crop']) # pred_fm_crop = (pred_fm_crop>=0.5).to(torch.float32) pred_vm = self.align_raw_size(pred_vm_crop, meta['obj_position'], meta["vm_pad"], meta) pred_fm = self.align_raw_size(pred_fm_crop, meta['obj_position'], meta["vm_pad"], meta) # visualization self.visualize(pred_vm, pred_fm, meta, mode, iter) loss_eval = self.loss_and_evaluation(pred_fm, meta, iter, mode, pred_vm=pred_vm) loss_eval["loss_fm"] = loss_fm loss_eval["loss_vm"] = loss_vm return loss_eval def visualize(self, pred_vm, pred_fm, meta, mode, iteration): pred_fm = pred_fm.squeeze() pred_vm = pred_vm.squeeze() gt_vm = meta["vm_no_crop"].squeeze() gt_fm = meta["fm_no_crop"].squeeze() to_plot = torch.cat((pred_vm, pred_fm, gt_vm, gt_fm)).cpu().numpy() save_dir = os.path.join(self.root_path, '{}_samples'.format(mode)) image_id, anno_id= meta["img_id"], meta["anno_id"] plt.imsave("{}/{}_{}_{}.png".format(save_dir, iteration, int(image_id.item()), int(anno_id.item())), to_plot) # def visualize_crop(self, pred_vm, pred_fm, meta, mode, count, pred_fm_crop_old): # pred_fm = pred_fm.squeeze() # pred_vm = pred_vm.squeeze() # pred_fm_crop_old = pred_fm_crop_old.squeeze() # gt_vm = meta["vm_crop"].squeeze() # gt_fm = meta["fm_crop"].squeeze() # to_plot = torch.cat((pred_vm, gt_vm, pred_fm_crop_old, pred_fm, gt_fm)).cpu().numpy() # save_dir = os.path.join(self.root_path, '{}_samples'.format(mode)) # image_id, anno_id= meta["img_id"], meta["anno_id"] # plt.imsave("{}/{}_{}_{}_{}.png".format(save_dir, count, int(image_id.item()), int(anno_id.item()), "crop"), to_plot) def create_inputs_tokens_normal(self, num, device): self.num_latent_size = self.config['resolution'] // self.config['patch_size'] blank_tokens = torch.ones((num, self.num_latent_size ** 2), device=device) masked_tokens = self.mask_token_idx * blank_tokens return masked_tokens.to(torch.int64) def gamma_func(self, mode="cosine"): if mode == "linear": return lambda r: 1 - r elif mode == "cosine": return lambda r: np.cos(r * np.pi / 2) elif mode == "square": return lambda r: 1 - r ** 2 elif mode == "cubic": return lambda r: 1 - r ** 3 elif mode == "log": return lambda r, total_unknown: - np.log2(r) / np.log2(total_unknown) else: raise NotImplementedError def mask_by_random_topk(self, mask_len, probs, temperature=1.0): confidence = torch.log(probs) + temperature * torch.distributions.gumbel.Gumbel(0, 1).sample(probs.shape).to(probs.device) sorted_confidence, _ = torch.sort(confidence, dim=-1) # from small to large # Obtains cut off threshold given the mask lengths. # cut_off = torch.take_along_dim(sorted_confidence, mask_len.to(torch.long), dim=-1) cut_off = sorted_confidence.gather(dim=-1, index=mask_len.to(torch.long)) # Masks tokens with lower confidence. masking = (confidence < cut_off) return masking def load(self, is_test=False, prefix=None): if prefix is not None: transformer_path = self.transformer_path + prefix + '.pth' else: transformer_path = self.transformer_path + '_last.pth' if self.config.restore or is_test: if os.path.exists(transformer_path): print('Rank {} is loading {} Transformer...'.format(self.rank, transformer_path)) data = torch.load(transformer_path, map_location="cpu")
torch_init_model(self.transformer, transformer_path, 'model')
9
2023-12-21 04:25:47+00:00
16k
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
12,316
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim: ddim_sampler = DDIMSampler(self) shape = (self.channels, self.image_size, self.image_size) samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs) return samples, intermediates @torch.no_grad() def get_unconditional_conditioning(self, batch_size, null_label=None): if null_label is not None: xc = null_label if isinstance(xc, ListConfig): xc = list(xc) if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: if hasattr(xc, "to"): xc = xc.to(self.device) c = self.get_learned_conditioning(xc) else: if self.cond_stage_key in ["class_label", "cls"]: xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device) return self.get_learned_conditioning(xc) else: raise NotImplementedError("todo") if isinstance(c, list): # in case the encoder gives us a list for i in range(len(c)): c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device) else: c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device) return c @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True, **kwargs): ema_scope = self.ema_scope if use_ema_scope else nullcontext use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption", "txt"]: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25) log["conditioning"] = xc elif self.cond_stage_key in ['class_label', "cls"]: try: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25) log['conditioning'] = xc except KeyError: # probably no "human_label" in batch pass
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if reset_ema: assert exists(ckpt_path) if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) if reset_ema: assert self.use_ema print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) else: self.register_buffer('logvar', logvar) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) elif self.parameterization == "v": lvlb_weights = torch.ones_like(self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))) else: raise NotImplementedError("mu not supported") lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") @torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] if self.make_it_fit: n_params = len([name for name, _ in itertools.chain(self.named_parameters(), self.named_buffers())]) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys:\n {missing}") if len(unexpected) > 0: print(f"\nUnexpected Keys:\n {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def predict_start_from_z_and_v(self, x_t, t, v): # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def predict_eps_from_z_and_v(self, x_t, t, v): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_v(self, x, noise, t): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x ) def get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): for k in self.ucg_training: p = self.ucg_training[k]["p"] val = self.ucg_training[k]["val"] if val is None: val = "" for i in range(len(batch[k])): if self.ucg_prng.choice(2, p=[1 - p, p]): batch[k][i] = val loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True) self.log("global_step", self.global_step, prog_bar=True, logger=True, on_step=True, on_epoch=False) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False) return loss @torch.no_grad() def validation_step(self, batch, batch_idx): _, loss_dict_no_ema = self.shared_step(batch) with self.ema_scope(): _, loss_dict_ema = self.shared_step(batch) loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema} self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True) def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=False, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, force_null_conditioning=False, *args, **kwargs): self.force_null_conditioning = force_null_conditioning self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__' and not self.force_null_conditioning: conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) reset_ema = kwargs.pop("reset_ema", False) reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True if reset_ema: assert self.use_ema print( f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() def make_cond_schedule(self, ): self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx, dataloader_idx): # only for very first batch if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt: assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously' # set rescale weight to 1./std of encodings print("### USING STD-RESCALING ###") x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer('scale_factor', 1. / z.flatten().std()) print(f"setting self.scale_factor to {self.scale_factor}") print("### USING STD-RESCALING ###") def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() self.first_stage_model.train = disabled_train for param in self.first_stage_model.parameters(): param.requires_grad = False def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append(self.decode_first_stage(zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented") return self.scale_factor * z def get_learned_conditioning(self, c): if self.cond_stage_forward is None: if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): c = self.cond_stage_model.encode(c) if isinstance(c, DiagonalGaussianDistribution): c = c.mode() else: c = self.cond_stage_model(c) else: assert hasattr(self.cond_stage_model, self.cond_stage_forward) c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) return c def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip(L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"]) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None, return_x=False): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() if self.model.conditioning_key is not None and not self.force_null_conditioning: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox', 'txt', 'vision']: xc = batch[cond_key] xc = rearrange(xc, 'b h w c -> b c h w') elif cond_key in ['class_label', 'cls']: xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x if not self.cond_stage_trainable or force_c_encode: if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_x: out.extend([x]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): x, c = self.get_input(batch, self.first_stage_key) loss = self(x, c) return loss def forward(self, x, c, *args, **kwargs): t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() if self.model.conditioning_key is not None: assert c is not None if self.cond_stage_trainable: c = self.get_learned_conditioning(c) if self.shorten_cond_schedule: # TODO: drop this option tc = self.cond_ids[t].to(self.device) c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) return self.p_losses(x, c, t, *args, **kwargs) def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is expected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, t, **cond) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0) return mean_flat(kl_prior) / np.log(2.0) def p_losses(self, x_start, cond, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_output = self.apply_model(x_noisy, t, cond) loss_dict = {} prefix = 'train' if self.training else 'val' if self.parameterization == "x0": target = x_start elif self.parameterization == "eps": target = noise elif self.parameterization == "v": target = self.get_v(x_start, noise, t) else: raise NotImplementedError() loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3]) loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()}) logvar_t = self.logvar[t].to(self.device) loss = loss_simple / torch.exp(logvar_t) + logvar_t # loss = loss_simple / torch.exp(self.logvar) + self.logvar if self.learn_logvar: loss_dict.update({f'{prefix}/loss_gamma': loss.mean()}) loss_dict.update({'logvar': self.logvar.data.mean()}) loss = self.l_simple_weight * loss.mean() loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3)) loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean() loss_dict.update({f'{prefix}/loss_vlb': loss_vlb}) loss += (self.original_elbo_weight * loss_vlb) loss_dict.update({f'{prefix}/loss': loss}) return loss, loss_dict def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False, return_x0=False, score_corrector=None, corrector_kwargs=None): t_in = t model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) if score_corrector is not None: assert self.parameterization == "eps" model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs) if return_codebook_ids: model_out, logits = model_out if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out else: raise NotImplementedError() if clip_denoised: x_recon.clamp_(-1., 1.) if quantize_denoised: x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) if return_codebook_ids: return model_mean, posterior_variance, posterior_log_variance, logits elif return_x0: return model_mean, posterior_variance, posterior_log_variance, x_recon else: return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_codebook_ids=False, quantize_denoised=False, return_x0=False, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): b, *_, device = *x.shape, x.device outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_codebook_ids=return_codebook_ids, quantize_denoised=quantize_denoised, return_x0=return_x0, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if return_codebook_ids: raise DeprecationWarning("Support dropped.") model_mean, _, model_log_variance, logits = outputs elif return_x0: model_mean, _, model_log_variance, x0 = outputs else: model_mean, _, model_log_variance = outputs noise = noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) if return_codebook_ids: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1) if return_x0: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0 else: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False, img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t timesteps = self.num_timesteps if batch_size is not None: b = batch_size if batch_size is not None else shape[0] shape = [batch_size] + list(shape) else: b = batch_size = shape[0] if x_T is None: img = torch.randn(shape, device=self.device) else: img = x_T intermediates = [] if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation', total=timesteps) if verbose else reversed( range(0, timesteps)) if type(temperature) == float: temperature = [temperature] * timesteps for i in iterator: ts = torch.full((b,), i, device=self.device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img, x0_partial = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, return_x0=True, temperature=temperature[i], noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if mask is not None: assert x0 is not None img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(x0_partial) if callback: callback(i) if img_callback: img_callback(img, i) return img, intermediates @torch.no_grad() def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t device = self.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None, **kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): if ddim: ddim_sampler = DDIMSampler(self) shape = (self.channels, self.image_size, self.image_size) samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs) return samples, intermediates @torch.no_grad() def get_unconditional_conditioning(self, batch_size, null_label=None): if null_label is not None: xc = null_label if isinstance(xc, ListConfig): xc = list(xc) if isinstance(xc, dict) or isinstance(xc, list): c = self.get_learned_conditioning(xc) else: if hasattr(xc, "to"): xc = xc.to(self.device) c = self.get_learned_conditioning(xc) else: if self.cond_stage_key in ["class_label", "cls"]: xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device) return self.get_learned_conditioning(xc) else: raise NotImplementedError("todo") if isinstance(c, list): # in case the encoder gives us a list for i in range(len(c)): c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device) else: c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device) return c @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None, use_ema_scope=True, **kwargs): ema_scope = self.ema_scope if use_ema_scope else nullcontext use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption", "txt"]: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25) log["conditioning"] = xc elif self.cond_stage_key in ['class_label', "cls"]: try: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25) log['conditioning'] = xc except KeyError: # probably no "human_label" in batch pass
elif isimage(xc):
4
2023-12-16 03:31:33+00:00
16k
yasserben/CLOUDS
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "clouds/config.py", "snippet": "def add_maskformer2_config(cfg):\n \"\"\"\n Add config for MASK_FORMER.\n \"\"\"\n # NOTE: configs from original maskformer\n # data config\n # select the dataset mapper\n cfg.INPUT.DATASET_MAPPER_NAME...
from shapely.errors import ShapelyDeprecationWarning from collections import OrderedDict from typing import Any, Dict, List, Set from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.data import ( MetadataCatalog, build_detection_train_loader, build_detection_test_loader, ) from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.modeling import build_model from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, inference_on_dataset, print_csv_format, DatasetEvaluator, ) from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler from detectron2.solver.build import maybe_add_gradient_clipping from detectron2.utils.logger import setup_logger from detectron2.engine import hooks from fvcore.nn.precise_bn import get_bn_modules from clouds import ( CityscapesSemSegEvaluator, ClassicalSemSegEvaluator, MapperTrain, MapperTest, add_maskformer2_config, add_clouds_config, add_wandb_config, add_prerocessing_training_set_config, PersoEvalHook, add_repeat_factors, ) from clouds.utils import setup_wandb, WandbWriter import warnings import copy import itertools import logging import os import ast import torch import detectron2.utils.comm as comm
12,300
""" Copyright 2023 Telecom Paris, Yasser BENIGMIM. All rights reserved. Licensed under the Apache License, Version 2.0 Reference: https://github.com/facebookresearch/Mask2Former/blob/main/train_net.py CLOUDS Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings("ignore", category=ShapelyDeprecationWarning) except: pass class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to CLOUDS. """ def build_writers(self): writers = super().build_writers() # use wandb writer instead.
""" Copyright 2023 Telecom Paris, Yasser BENIGMIM. All rights reserved. Licensed under the Apache License, Version 2.0 Reference: https://github.com/facebookresearch/Mask2Former/blob/main/train_net.py CLOUDS Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings("ignore", category=ShapelyDeprecationWarning) except: pass class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to CLOUDS. """ def build_writers(self): writers = super().build_writers() # use wandb writer instead.
writers[-1] = WandbWriter()
10
2023-12-15 15:40:58+00:00
16k
modelscope/scepter
scepter/modules/inference/diffusion_inference.py
[ { "identifier": "GaussianDiffusion", "path": "scepter/modules/model/network/diffusion/diffusion.py", "snippet": "class GaussianDiffusion(object):\n def __init__(self, sigmas, prediction_type='eps'):\n assert prediction_type in {'x0', 'eps', 'v'}\n self.sigmas = sigmas # noise coefficie...
import copy import hashlib import json import os.path import random import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as TT from collections import OrderedDict from peft.utils import CONFIG_NAME, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME from PIL.Image import Image from swift import Swift, SwiftModel from scepter.modules.model.network.diffusion.diffusion import GaussianDiffusion from scepter.modules.model.network.diffusion.schedules import noise_schedule from scepter.modules.model.registry import (BACKBONES, EMBEDDERS, MODELS, TOKENIZERS, TUNERS) from scepter.modules.utils.config import Config from scepter.modules.utils.distribute import we from scepter.modules.utils.file_system import FS from safetensors.torch import \ load_file as safe_load_file from safetensors.torch import \ save_file as safe_save_file from safetensors.torch import load_file as load_safetensors from safetensors.torch import load_file as load_safetensors
12,587
cond_stage_model = OrderedDict() diffusion_model = OrderedDict() for k, v in sd.items(): if k.startswith('first_stage_model.'): first_stage_model[k.replace( 'first_stage_model.', '')] = v elif k.startswith('conditioner.'): cond_stage_model[k.replace('conditioner.', '')] = v elif k.startswith('cond_stage_model.'): if k.startswith('cond_stage_model.model.'): cond_stage_model[k.replace( 'cond_stage_model.model.', '')] = v else: cond_stage_model[k.replace( 'cond_stage_model.', '')] = v elif k.startswith('model.diffusion_model.'): diffusion_model[k.replace('model.diffusion_model.', '')] = v else: continue if cfg.have('FIRST_STAGE_MODEL'): with open(first_stage_model_path + 'cache', 'wb') as f: torch.save(first_stage_model, f) os.rename(first_stage_model_path + 'cache', first_stage_model_path) self.logger.info( 'First stage model has been processed.') if cfg.have('COND_STAGE_MODEL'): with open(cond_stage_model_path + 'cache', 'wb') as f: torch.save(cond_stage_model, f) os.rename(cond_stage_model_path + 'cache', cond_stage_model_path) self.logger.info( 'Cond stage model has been processed.') if cfg.have('DIFFUSION_MODEL'): with open(diffusion_model_path + 'cache', 'wb') as f: torch.save(diffusion_model, f) os.rename(diffusion_model_path + 'cache', diffusion_model_path) self.logger.info('Diffusion model has been processed.') if not cfg.FIRST_STAGE_MODEL.get('PRETRAINED_MODEL', None): cfg.FIRST_STAGE_MODEL.PRETRAINED_MODEL = first_stage_model_path else: cfg.FIRST_STAGE_MODEL.RELOAD_MODEL = first_stage_model_path if not cfg.COND_STAGE_MODEL.get('PRETRAINED_MODEL', None): cfg.COND_STAGE_MODEL.PRETRAINED_MODEL = cond_stage_model_path else: cfg.COND_STAGE_MODEL.RELOAD_MODEL = cond_stage_model_path if not cfg.DIFFUSION_MODEL.get('PRETRAINED_MODEL', None): cfg.DIFFUSION_MODEL.PRETRAINED_MODEL = diffusion_model_path else: cfg.DIFFUSION_MODEL.RELOAD_MODEL = diffusion_model_path return cfg def init_from_modules(self, modules): for k, v in modules.items(): self.__setattr__(k, v) def infer_model(self, cfg, module_paras=None): module = { 'model': None, 'cfg': cfg, 'device': 'offline', 'name': cfg.NAME, 'function_info': {}, 'paras': {} } if module_paras is None: return module function_info = {} paras = { k.lower(): v for k, v in module_paras.get('PARAS', {}).items() } for function in module_paras.get('FUNCTION', []): input_dict = {} for inp in function.get('INPUT', []): if inp.lower() in self.input: input_dict[inp.lower()] = self.input[inp.lower()] function_info[function.NAME] = { 'dtype': function.get('DTYPE', 'float32'), 'input': input_dict } module['paras'] = paras module['function_info'] = function_info return module def init_from_ckpt(self, path, model, ignore_keys=list()): if path.endswith('safetensors'): sd = load_safetensors(path) else: sd = torch.load(path, map_location='cpu') new_sd = OrderedDict() for k, v in sd.items(): ignored = False for ik in ignore_keys: if ik in k: if we.rank == 0: self.logger.info( 'Ignore key {} from state_dict.'.format(k)) ignored = True break if not ignored: new_sd[k] = v missing, unexpected = model.load_state_dict(new_sd, strict=False) if we.rank == 0: self.logger.info( f'Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys' ) if len(missing) > 0: self.logger.info(f'Missing Keys:\n {missing}') if len(unexpected) > 0: self.logger.info(f'\nUnexpected Keys:\n {unexpected}') def load(self, module): if module['device'] == 'offline': if module['cfg'].NAME in MODELS.class_map: model = MODELS.build(module['cfg'], logger=self.logger).eval()
# -*- coding: utf-8 -*- def get_model(model_tuple): assert 'model' in model_tuple return model_tuple['model'] class DiffusionInference(): ''' define vae, unet, text-encoder, tuner, refiner components support to load the components dynamicly. create and load model when run this model at the first time. ''' def __init__(self, logger=None): self.logger = logger def init_from_cfg(self, cfg): self.name = cfg.NAME self.is_default = cfg.get('IS_DEFAULT', False) module_paras = self.load_default(cfg.get('DEFAULT_PARAS', None)) assert cfg.have('MODEL') cfg.MODEL = self.redefine_paras(cfg.MODEL) self.diffusion = self.load_schedule(cfg.MODEL.SCHEDULE) self.diffusion_model = self.infer_model( cfg.MODEL.DIFFUSION_MODEL, module_paras.get( 'DIFFUSION_MODEL', None)) if cfg.MODEL.have('DIFFUSION_MODEL') else None self.first_stage_model = self.infer_model( cfg.MODEL.FIRST_STAGE_MODEL, module_paras.get( 'FIRST_STAGE_MODEL', None)) if cfg.MODEL.have('FIRST_STAGE_MODEL') else None self.cond_stage_model = self.infer_model( cfg.MODEL.COND_STAGE_MODEL, module_paras.get( 'COND_STAGE_MODEL', None)) if cfg.MODEL.have('COND_STAGE_MODEL') else None self.refiner_cond_model = self.infer_model( cfg.MODEL.REFINER_COND_MODEL, module_paras.get( 'REFINER_COND_MODEL', None)) if cfg.MODEL.have('REFINER_COND_MODEL') else None self.refiner_diffusion_model = self.infer_model( cfg.MODEL.REFINER_MODEL, module_paras.get( 'REFINER_MODEL', None)) if cfg.MODEL.have('REFINER_MODEL') else None self.tokenizer = TOKENIZERS.build( cfg.MODEL.TOKENIZER, logger=self.logger) if cfg.MODEL.have('TOKENIZER') else None if self.tokenizer is not None: self.cond_stage_model['cfg'].KWARGS = { 'vocab_size': self.tokenizer.vocab_size } def register_tuner(self, tuner_model_list): if len(tuner_model_list) < 1: if isinstance(self.diffusion_model['model'], SwiftModel): for adapter_name in self.diffusion_model['model'].adapters: self.diffusion_model['model'].deactivate_adapter( adapter_name, offload='cpu') if isinstance(self.cond_stage_model['model'], SwiftModel): for adapter_name in self.cond_stage_model['model'].adapters: self.cond_stage_model['model'].deactivate_adapter( adapter_name, offload='cpu') return all_diffusion_tuner = {} all_cond_tuner = {} save_root_dir = '.cache_tuner' for tuner_model in tuner_model_list: tunner_model_folder = tuner_model.MODEL_PATH local_tuner_model = FS.get_dir_to_local_dir(tunner_model_folder) all_tuner_datas = os.listdir(local_tuner_model) cur_tuner_md5 = hashlib.md5( tunner_model_folder.encode('utf-8')).hexdigest() local_diffusion_cache = os.path.join( save_root_dir, cur_tuner_md5 + '_' + 'diffusion') local_cond_cache = os.path.join(save_root_dir, cur_tuner_md5 + '_' + 'cond') meta_file = os.path.join(save_root_dir, cur_tuner_md5 + '_meta.json') if not os.path.exists(meta_file): diffusion_tuner = {} cond_tuner = {} for sub in all_tuner_datas: sub_file = os.path.join(local_tuner_model, sub) config_file = os.path.join(sub_file, CONFIG_NAME) safe_file = os.path.join(sub_file, SAFETENSORS_WEIGHTS_NAME) bin_file = os.path.join(sub_file, WEIGHTS_NAME) if os.path.isdir(sub_file) and os.path.isfile(config_file): # diffusion or cond cfg = json.load(open(config_file, 'r')) if 'cond_stage_model.' in cfg['target_modules']: cond_cfg = copy.deepcopy(cfg) if 'cond_stage_model.*' in cond_cfg[ 'target_modules']: cond_cfg['target_modules'] = cond_cfg[ 'target_modules'].replace( 'cond_stage_model.*', '.*') else: cond_cfg['target_modules'] = cond_cfg[ 'target_modules'].replace( 'cond_stage_model.', '') if cond_cfg['target_modules'].startswith('*'): cond_cfg['target_modules'] = '.' + cond_cfg[ 'target_modules'] os.makedirs(local_cond_cache + '_' + sub, exist_ok=True) cond_tuner[os.path.basename(local_cond_cache) + '_' + sub] = hashlib.md5( (local_cond_cache + '_' + sub).encode('utf-8')).hexdigest() os.makedirs(local_cond_cache + '_' + sub, exist_ok=True) json.dump( cond_cfg, open( os.path.join(local_cond_cache + '_' + sub, CONFIG_NAME), 'w')) if 'model.' in cfg['target_modules'].replace( 'cond_stage_model.', ''): diffusion_cfg = copy.deepcopy(cfg) if 'model.*' in diffusion_cfg['target_modules']: diffusion_cfg[ 'target_modules'] = diffusion_cfg[ 'target_modules'].replace( 'model.*', '.*') else: diffusion_cfg[ 'target_modules'] = diffusion_cfg[ 'target_modules'].replace( 'model.', '') if diffusion_cfg['target_modules'].startswith('*'): diffusion_cfg[ 'target_modules'] = '.' + diffusion_cfg[ 'target_modules'] os.makedirs(local_diffusion_cache + '_' + sub, exist_ok=True) diffusion_tuner[ os.path.basename(local_diffusion_cache) + '_' + sub] = hashlib.md5( (local_diffusion_cache + '_' + sub).encode('utf-8')).hexdigest() json.dump( diffusion_cfg, open( os.path.join( local_diffusion_cache + '_' + sub, CONFIG_NAME), 'w')) state_dict = {} is_bin_file = True if os.path.isfile(bin_file): state_dict = torch.load(bin_file) elif os.path.isfile(safe_file): is_bin_file = False state_dict = safe_load_file( safe_file, device='cuda' if torch.cuda.is_available() else 'cpu') save_diffusion_state_dict = {} save_cond_state_dict = {} for key, value in state_dict.items(): if key.startswith('model.'): save_diffusion_state_dict[ key[len('model.'):].replace( sub, os.path.basename(local_diffusion_cache) + '_' + sub)] = value elif key.startswith('cond_stage_model.'): save_cond_state_dict[ key[len('cond_stage_model.'):].replace( sub, os.path.basename(local_cond_cache) + '_' + sub)] = value if is_bin_file: if len(save_diffusion_state_dict) > 0: torch.save( save_diffusion_state_dict, os.path.join( local_diffusion_cache + '_' + sub, WEIGHTS_NAME)) if len(save_cond_state_dict) > 0: torch.save( save_cond_state_dict, os.path.join(local_cond_cache + '_' + sub, WEIGHTS_NAME)) else: if len(save_diffusion_state_dict) > 0: safe_save_file( save_diffusion_state_dict, os.path.join( local_diffusion_cache + '_' + sub, SAFETENSORS_WEIGHTS_NAME), metadata={'format': 'pt'}) if len(save_cond_state_dict) > 0: safe_save_file( save_cond_state_dict, os.path.join(local_cond_cache + '_' + sub, SAFETENSORS_WEIGHTS_NAME), metadata={'format': 'pt'}) json.dump( { 'diffusion_tuner': diffusion_tuner, 'cond_tuner': cond_tuner }, open(meta_file, 'w')) else: meta_conf = json.load(open(meta_file, 'r')) diffusion_tuner = meta_conf['diffusion_tuner'] cond_tuner = meta_conf['cond_tuner'] all_diffusion_tuner.update(diffusion_tuner) all_cond_tuner.update(cond_tuner) if len(all_diffusion_tuner) > 0: self.load(self.diffusion_model) self.diffusion_model['model'] = Swift.from_pretrained( self.diffusion_model['model'], save_root_dir, adapter_name=all_diffusion_tuner) self.diffusion_model['model'].set_active_adapters( list(all_diffusion_tuner.values())) self.unload(self.diffusion_model) if len(all_cond_tuner) > 0: self.load(self.cond_stage_model) self.cond_stage_model['model'] = Swift.from_pretrained( self.cond_stage_model['model'], save_root_dir, adapter_name=all_cond_tuner) self.cond_stage_model['model'].set_active_adapters( list(all_cond_tuner.values())) self.unload(self.cond_stage_model) def register_controllers(self, control_model_ins): if control_model_ins is None or control_model_ins == '': if isinstance(self.diffusion_model['model'], SwiftModel): if (hasattr(self.diffusion_model['model'].base_model, 'control_blocks') and self.diffusion_model['model'].base_model.control_blocks ): # noqa del self.diffusion_model['model'].base_model.control_blocks self.diffusion_model[ 'model'].base_model.control_blocks = None self.diffusion_model['model'].base_model.control_name = [] else: del self.diffusion_model['model'].control_blocks self.diffusion_model['model'].control_blocks = None self.diffusion_model['model'].control_name = [] return if not isinstance(control_model_ins, list): control_model_ins = [control_model_ins] control_model = nn.ModuleList([]) control_model_folder = [] for one_control in control_model_ins: one_control_model_folder = one_control.MODEL_PATH control_model_folder.append(one_control_model_folder) have_list = getattr(self.diffusion_model['model'], 'control_name', []) if one_control_model_folder in have_list: ind = have_list.index(one_control_model_folder) csc_tuners = copy.deepcopy( self.diffusion_model['model'].control_blocks[ind]) else: one_local_control_model = FS.get_dir_to_local_dir( one_control_model_folder) control_cfg = Config(cfg_file=os.path.join( one_local_control_model, 'configuration.json')) assert hasattr(control_cfg, 'CONTROL_MODEL') control_cfg.CONTROL_MODEL[ 'INPUT_BLOCK_CHANS'] = self.diffusion_model[ 'model']._input_block_chans control_cfg.CONTROL_MODEL[ 'INPUT_DOWN_FLAG'] = self.diffusion_model[ 'model']._input_down_flag control_cfg.CONTROL_MODEL.PRETRAINED_MODEL = os.path.join( one_local_control_model, 'pytorch_model.bin') csc_tuners = TUNERS.build(control_cfg.CONTROL_MODEL, logger=self.logger) control_model.append(csc_tuners) if isinstance(self.diffusion_model['model'], SwiftModel): del self.diffusion_model['model'].base_model.control_blocks self.diffusion_model[ 'model'].base_model.control_blocks = control_model self.diffusion_model[ 'model'].base_model.control_name = control_model_folder else: del self.diffusion_model['model'].control_blocks self.diffusion_model['model'].control_blocks = control_model self.diffusion_model['model'].control_name = control_model_folder def redefine_paras(self, cfg): if cfg.get('PRETRAINED_MODEL', None): assert FS.isfile(cfg.PRETRAINED_MODEL) with FS.get_from(cfg.PRETRAINED_MODEL, wait_finish=True) as local_path: if local_path.endswith('safetensors'): sd = load_safetensors(local_path) else: sd = torch.load(local_path, map_location='cpu') first_stage_model_path = os.path.join( os.path.dirname(local_path), 'first_stage_model.pth') cond_stage_model_path = os.path.join( os.path.dirname(local_path), 'cond_stage_model.pth') diffusion_model_path = os.path.join( os.path.dirname(local_path), 'diffusion_model.pth') if (not os.path.exists(first_stage_model_path) or not os.path.exists(cond_stage_model_path) or not os.path.exists(diffusion_model_path)): self.logger.info( 'Now read the whole model and rearrange the modules, it may take several mins.' ) first_stage_model = OrderedDict() cond_stage_model = OrderedDict() diffusion_model = OrderedDict() for k, v in sd.items(): if k.startswith('first_stage_model.'): first_stage_model[k.replace( 'first_stage_model.', '')] = v elif k.startswith('conditioner.'): cond_stage_model[k.replace('conditioner.', '')] = v elif k.startswith('cond_stage_model.'): if k.startswith('cond_stage_model.model.'): cond_stage_model[k.replace( 'cond_stage_model.model.', '')] = v else: cond_stage_model[k.replace( 'cond_stage_model.', '')] = v elif k.startswith('model.diffusion_model.'): diffusion_model[k.replace('model.diffusion_model.', '')] = v else: continue if cfg.have('FIRST_STAGE_MODEL'): with open(first_stage_model_path + 'cache', 'wb') as f: torch.save(first_stage_model, f) os.rename(first_stage_model_path + 'cache', first_stage_model_path) self.logger.info( 'First stage model has been processed.') if cfg.have('COND_STAGE_MODEL'): with open(cond_stage_model_path + 'cache', 'wb') as f: torch.save(cond_stage_model, f) os.rename(cond_stage_model_path + 'cache', cond_stage_model_path) self.logger.info( 'Cond stage model has been processed.') if cfg.have('DIFFUSION_MODEL'): with open(diffusion_model_path + 'cache', 'wb') as f: torch.save(diffusion_model, f) os.rename(diffusion_model_path + 'cache', diffusion_model_path) self.logger.info('Diffusion model has been processed.') if not cfg.FIRST_STAGE_MODEL.get('PRETRAINED_MODEL', None): cfg.FIRST_STAGE_MODEL.PRETRAINED_MODEL = first_stage_model_path else: cfg.FIRST_STAGE_MODEL.RELOAD_MODEL = first_stage_model_path if not cfg.COND_STAGE_MODEL.get('PRETRAINED_MODEL', None): cfg.COND_STAGE_MODEL.PRETRAINED_MODEL = cond_stage_model_path else: cfg.COND_STAGE_MODEL.RELOAD_MODEL = cond_stage_model_path if not cfg.DIFFUSION_MODEL.get('PRETRAINED_MODEL', None): cfg.DIFFUSION_MODEL.PRETRAINED_MODEL = diffusion_model_path else: cfg.DIFFUSION_MODEL.RELOAD_MODEL = diffusion_model_path return cfg def init_from_modules(self, modules): for k, v in modules.items(): self.__setattr__(k, v) def infer_model(self, cfg, module_paras=None): module = { 'model': None, 'cfg': cfg, 'device': 'offline', 'name': cfg.NAME, 'function_info': {}, 'paras': {} } if module_paras is None: return module function_info = {} paras = { k.lower(): v for k, v in module_paras.get('PARAS', {}).items() } for function in module_paras.get('FUNCTION', []): input_dict = {} for inp in function.get('INPUT', []): if inp.lower() in self.input: input_dict[inp.lower()] = self.input[inp.lower()] function_info[function.NAME] = { 'dtype': function.get('DTYPE', 'float32'), 'input': input_dict } module['paras'] = paras module['function_info'] = function_info return module def init_from_ckpt(self, path, model, ignore_keys=list()): if path.endswith('safetensors'): sd = load_safetensors(path) else: sd = torch.load(path, map_location='cpu') new_sd = OrderedDict() for k, v in sd.items(): ignored = False for ik in ignore_keys: if ik in k: if we.rank == 0: self.logger.info( 'Ignore key {} from state_dict.'.format(k)) ignored = True break if not ignored: new_sd[k] = v missing, unexpected = model.load_state_dict(new_sd, strict=False) if we.rank == 0: self.logger.info( f'Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys' ) if len(missing) > 0: self.logger.info(f'Missing Keys:\n {missing}') if len(unexpected) > 0: self.logger.info(f'\nUnexpected Keys:\n {unexpected}') def load(self, module): if module['device'] == 'offline': if module['cfg'].NAME in MODELS.class_map: model = MODELS.build(module['cfg'], logger=self.logger).eval()
elif module['cfg'].NAME in BACKBONES.class_map:
2
2023-12-21 02:01:48+00:00
16k
RomGai/BrainVis
dc_ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "dc_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 os import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import torch.nn.functional as F from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.rank_zero import rank_zero_only from dc_ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from dc_ldm.modules.ema import LitEma from dc_ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from dc_ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL from dc_ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from dc_ldm.models.diffusion.ddim import DDIMSampler from dc_ldm.models.diffusion.plms import PLMSSampler from PIL import Image from eval_metrics import get_similarity_metric from dc_ldm.modules.encoders.modules import FrozenImageEmbedder
14,233
for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None,**kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs): if ddim: ddim_sampler = DDIMSampler(self) shape = (self.channels, self.image_size, self.image_size) samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size, shape,cond,verbose=False,**kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True,**kwargs) return samples, intermediates @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption"]: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"]) log["conditioning"] = xc elif self.cond_stage_key == 'class_label': xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"]) log['conditioning'] = xc elif isimage(xc): log["conditioning"] = xc if ismap(xc): log["original_conditioning"] = self.to_rgb(xc) if plot_diffusion_rows: # get diffusion row diffusion_row = list() z_start = z[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(z_start) z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) diffusion_row.append(self.decode_first_stage(z_noisy)) diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) log["diffusion_row"] = diffusion_grid if sample: # get denoise row with self.ema_scope("Plotting"): samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, ddim_steps=ddim_steps,eta=ddim_eta) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
""" 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., ddim_steps=300 ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) self.validation_count = 0 self.ddim_steps = ddim_steps self.return_cond = False self.output_path = None self.main_config = None self.best_val = 0.0 self.run_full_validation_threshold = 0.0 self.eval_avg = True def re_init_ema(self): if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) else: raise NotImplementedError("mu not supported") # TODO how to choose this term lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys: {missing}") if len(unexpected) > 0: print(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) def get_loss(self, pred, target, mean=True): if self.loss_type == 'l1': loss = (target - pred).abs() if mean: loss = loss.mean() elif self.loss_type == 'l2': if mean: loss = torch.nn.functional.mse_loss(target, pred) else: loss = torch.nn.functional.mse_loss(target, pred, reduction='none') else: raise NotImplementedError("unknown loss type '{loss_type}'") return loss def p_losses(self, x_start, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) model_out = self.model(x_noisy, t) loss_dict = {} if self.parameterization == "eps": target = noise elif self.parameterization == "x0": target = x_start else: raise NotImplementedError(f"Paramterization {self.parameterization} not yet supported") loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) log_prefix = 'train' if self.training else 'val' loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()}) loss_simple = loss.mean() * self.l_simple_weight loss_vlb = (self.lvlb_weights[t] * loss).mean() loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb}) loss = loss_simple + self.original_elbo_weight * loss_vlb loss_dict.update({f'{log_prefix}/loss': loss}) return loss, loss_dict def forward(self, x, *args, **kwargs): # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() return self.p_losses(x, t, *args, **kwargs) def get_input(self, batch, k): x = batch[k] if len(x.shape) == 3: x = x[..., None] x = rearrange(x, 'b h w c -> b c h w') x = x.to(memory_format=torch.contiguous_format).float() return x def shared_step(self, batch): x = self.get_input(batch, self.first_stage_key) loss, loss_dict = self(x) return loss, loss_dict def training_step(self, batch, batch_idx): self.train() self.cond_stage_model.train() ###到底是在哪里训练的 loss, loss_dict = self.shared_step(batch) self.log_dict(loss_dict, prog_bar=True, logger=True, on_step=False, on_epoch=True) if self.use_scheduler: lr = self.optimizers().param_groups[0]['lr'] self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=False, on_epoch=True) return loss @torch.no_grad() def generate(self, data, num_samples, ddim_steps=300, HW=None, limit=None, state=None): # fmri_embedding: n, seq_len, embed_dim all_samples = [] if HW is None: shape = (self.p_channels, self.p_image_size, self.p_image_size) else: num_resolutions = len(self.ch_mult) shape = (self.p_channels, HW[0] // 2**(num_resolutions-1), HW[1] // 2**(num_resolutions-1)) model = self sampler = PLMSSampler(model) # sampler = DDIMSampler(model) model.eval() if torch.cuda.is_available(): state = torch.cuda.get_rng_state() if state is None else state torch.cuda.set_rng_state(state) else: state = torch.get_rng_state() if state is None else state torch.set_rng_state(state) # rng = torch.Generator(device=self.device).manual_seed(2022).set_state(state) # state = torch.cuda.get_rng_state() with model.ema_scope(): for count, item in enumerate(zip(data['eeg'], data['image'])): if limit is not None: if count >= limit: break latent = item[0] # fmri embedding gt_image = rearrange(item[1], 'h w c -> 1 c h w') # h w c print(f"rendering {num_samples} examples in {ddim_steps} steps.") # c = model.get_learned_conditioning(repeat(latent, 'h w -> c h w', c=num_samples).to(self.device)) c, re_latent = model.get_learned_conditioning(repeat(latent, 'h w -> c h w', c=num_samples).to(self.device)) samples_ddim, _ = sampler.sample(S=ddim_steps, conditioning=c, batch_size=num_samples, shape=shape, verbose=False, generator=None) x_samples_ddim = model.decode_first_stage(samples_ddim) x_samples_ddim = torch.clamp((x_samples_ddim+1.0)/2.0,min=0.0, max=1.0) gt_image = torch.clamp((gt_image+1.0)/2.0,min=0.0, max=1.0) all_samples.append(torch.cat([gt_image.detach().cpu(), x_samples_ddim.detach().cpu()], dim=0)) # put groundtruth at first # display as grid grid = torch.stack(all_samples, 0) grid = rearrange(grid, 'n b c h w -> (n b) c h w') grid = make_grid(grid, nrow=num_samples+1) # to image grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy() return grid, (255. * torch.stack(all_samples, 0).cpu().numpy()).astype(np.uint8), state def save_images(self, all_samples, suffix=0): # print('output_path') # print(self.output_path) if self.output_path is not None: os.makedirs(os.path.join(self.output_path, 'val', f'{self.validation_count}_{suffix}'), exist_ok=True) for sp_idx, imgs in enumerate(all_samples): # for copy_idx, img in enumerate(imgs[1:]): for copy_idx, img in enumerate(imgs): img = rearrange(img, 'c h w -> h w c') Image.fromarray(img).save(os.path.join(self.output_path, 'val', f'{self.validation_count}_{suffix}', f'test{sp_idx}-{copy_idx}.png')) def full_validation(self, batch, state=None): print('###### run full validation! ######\n') grid, all_samples, state = self.generate(batch, ddim_steps=self.ddim_steps, num_samples=5, limit=None, state=state) metric, metric_list = self.get_eval_metric(all_samples) self.save_images(all_samples, suffix='%.4f'%metric[-1]) metric_dict = {f'val/{k}_full':v for k, v in zip(metric_list, metric)} # self.logger.log_metrics(metric_dict) grid_imgs = Image.fromarray(grid.astype(np.uint8)) # self.logger.log_image(key=f'samples_test_full', images=[grid_imgs]) if metric[-1] > self.best_val: self.best_val = metric[-1] torch.save( { 'model_state_dict': self.state_dict(), 'config': self.main_config, 'state': state }, os.path.join(self.output_path, 'checkpoint_best.pth') ) @torch.no_grad() def validation_step(self, batch, batch_idx): if batch_idx != 0: return if self.validation_count % 5 == 0 and self.trainer.current_epoch != 0: self.full_validation(batch) else: # pass grid, all_samples, state = self.generate(batch, ddim_steps=self.ddim_steps, num_samples=3, limit=5) metric, metric_list = self.get_eval_metric(all_samples, avg=self.eval_avg) grid_imgs = Image.fromarray(grid.astype(np.uint8)) # self.logger.log_image(key=f'samples_test', images=[grid_imgs]) metric_dict = {f'val/{k}':v for k, v in zip(metric_list, metric)} # self.logger.log_metrics(metric_dict) if metric[-1] > self.run_full_validation_threshold: self.full_validation(batch, state=state) self.validation_count += 1 def get_eval_metric(self, samples, avg=True): metric_list = ['mse', 'pcc', 'ssim', 'psm'] res_list = [] gt_images = [img[0] for img in samples] gt_images = rearrange(np.stack(gt_images), 'n c h w -> n h w c') samples_to_run = np.arange(1, len(samples[0])) if avg else [1] for m in metric_list: res_part = [] for s in samples_to_run: pred_images = [img[s] for img in samples] pred_images = rearrange(np.stack(pred_images), 'n c h w -> n h w c') res = get_similarity_metric(pred_images, gt_images, method='pair-wise', metric_name=m) res_part.append(np.mean(res)) res_list.append(np.mean(res_part)) res_part = [] for s in samples_to_run: pred_images = [img[s] for img in samples] pred_images = rearrange(np.stack(pred_images), 'n c h w -> n h w c') res = get_similarity_metric(pred_images, gt_images, 'class', None, n_way=50, num_trials=50, top_k=1, device='cuda') res_part.append(np.mean(res)) res_list.append(np.mean(res_part)) res_list.append(np.max(res_part)) metric_list.append('top-1-class') metric_list.append('top-1-class (max)') return res_list, metric_list def on_train_batch_end(self, *args, **kwargs): if self.use_ema: self.model_ema(self.model) def _get_rows_from_list(self, samples): n_imgs_per_row = len(samples) denoise_grid = rearrange(samples, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid @torch.no_grad() def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): log = dict() x = self.get_input(batch, self.first_stage_key) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) x = x.to(self.device)[:N] log["inputs"] = x # get diffusion row diffusion_row = list() x_start = x[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(x_start) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) diffusion_row.append(x_noisy) log["diffusion_row"] = self._get_rows_from_list(diffusion_row) if sample: # get denoise row with self.ema_scope("Plotting"): samples, denoise_row = self.sample(batch_size=N, return_intermediates=True) log["samples"] = samples log["denoise_row"] = self._get_rows_from_list(denoise_row) if return_keys: if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: return log else: return {key: log[key] for key in return_keys} return log def configure_optimizers(self): lr = self.learning_rate params = list(self.model.parameters()) if self.learn_logvar: params = params + [self.logvar] opt = torch.optim.AdamW(params, lr=lr) return opt class LatentDiffusion(DDPM): """main class""" def __init__(self, first_stage_config, cond_stage_config, num_timesteps_cond=None, cond_stage_key="image", cond_stage_trainable=True, concat_mode=True, cond_stage_forward=None, conditioning_key=None, scale_factor=1.0, scale_by_std=False, *args, **kwargs): self.num_timesteps_cond = default(num_timesteps_cond, 1) self.scale_by_std = scale_by_std assert self.num_timesteps_cond <= kwargs['timesteps'] # for backwards compatibility after implementation of DiffusionWrapper if conditioning_key is None: conditioning_key = 'concat' if concat_mode else 'crossattn' if cond_stage_config == '__is_unconditional__': conditioning_key = None ckpt_path = kwargs.pop("ckpt_path", None) ignore_keys = kwargs.pop("ignore_keys", []) super().__init__(conditioning_key=conditioning_key, *args, **kwargs) self.concat_mode = concat_mode self.cond_stage_trainable = cond_stage_trainable self.cond_stage_key = cond_stage_key try: self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 except: self.num_downs = 0 if not scale_by_std: self.scale_factor = scale_factor else: self.register_buffer('scale_factor', torch.tensor(scale_factor)) self.instantiate_first_stage(first_stage_config) self.instantiate_cond_stage(cond_stage_config) self.cond_stage_forward = cond_stage_forward self.clip_denoised = False self.bbox_tokenizer = None self.restarted_from_ckpt = False if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys) self.restarted_from_ckpt = True self.train_cond_stage_only = False self.clip_tune = True if self.clip_tune: self.image_embedder = FrozenImageEmbedder() self.cls_tune = False def make_cond_schedule(self, ): self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long) ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long() self.cond_ids[:self.num_timesteps_cond] = ids @rank_zero_only @torch.no_grad() def on_train_batch_start(self, batch, batch_idx, dataloader_idx): # only for very first batch if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt: assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously' # set rescale weight to 1./std of encodings print("### USING STD-RESCALING ###") x = super().get_input(batch, self.first_stage_key) x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) z = self.get_first_stage_encoding(encoder_posterior).detach() del self.scale_factor self.register_buffer('scale_factor', 1. / z.flatten().std()) print(f"setting self.scale_factor to {self.scale_factor}") print("### USING STD-RESCALING ###") def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s) self.shorten_cond_schedule = self.num_timesteps_cond > 1 if self.shorten_cond_schedule: self.make_cond_schedule() def instantiate_first_stage(self, config): model = instantiate_from_config(config) self.first_stage_model = model.eval() def freeze_diffusion_model(self): for param in self.model.parameters(): param.requires_grad = False def unfreeze_diffusion_model(self): for param in self.model.parameters(): param.requires_grad = True def freeze_cond_stage(self): for param in self.cond_stage_model.parameters(): param.requires_grad = False def unfreeze_cond_stage(self): for param in self.cond_stage_model.parameters(): param.requires_grad = True def freeze_first_stage(self): self.first_stage_model.trainable = False for param in self.first_stage_model.parameters(): param.requires_grad = False def unfreeze_first_stage(self): self.first_stage_model.trainable = True for param in self.first_stage_model.parameters(): param.requires_grad = True def freeze_whole_model(self): self.first_stage_model.trainable = False for param in self.parameters(): param.requires_grad = False def unfreeze_whole_model(self): self.first_stage_model.trainable = True for param in self.parameters(): param.requires_grad = True def instantiate_cond_stage(self, config): if not self.cond_stage_trainable: if config == "__is_first_stage__": print("Using first stage also as cond stage.") self.cond_stage_model = self.first_stage_model elif config == "__is_unconditional__": print(f"Training {self.__class__.__name__} as an unconditional model.") self.cond_stage_model = None # self.be_unconditional = True else: model = instantiate_from_config(config) self.cond_stage_model = model.eval() # self.cond_stage_model.train = disabled_train for param in self.cond_stage_model.parameters(): param.requires_grad = False else: assert config != '__is_first_stage__' assert config != '__is_unconditional__' model = instantiate_from_config(config) self.cond_stage_model = model def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False): denoise_row = [] for zd in tqdm(samples, desc=desc): denoise_row.append(self.decode_first_stage(zd.to(self.device), force_not_quantize=force_no_decoder_quantization)) n_imgs_per_row = len(denoise_row) denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w') denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w') denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) return denoise_grid def get_first_stage_encoding(self, encoder_posterior): if isinstance(encoder_posterior, DiagonalGaussianDistribution): z = encoder_posterior.sample() elif isinstance(encoder_posterior, torch.Tensor): z = encoder_posterior else: raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented") return self.scale_factor * z def get_learned_conditioning(self, c): # self.cond_stage_model.eval() if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): c, re_latent = self.cond_stage_model.encode(c) # c = self.cond_stage_model.encode(c) else: c, re_latent = self.cond_stage_model(c) # c = self.cond_stage_model(c) # return c return c, re_latent def meshgrid(self, h, w): y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) arr = torch.cat([y, x], dim=-1) return arr def delta_border(self, h, w): """ :param h: height :param w: width :return: normalized distance to image border, wtith min distance = 0 at border and max dist = 0.5 at image center """ lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) arr = self.meshgrid(h, w) / lower_right_corner dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0] return edge_dist def get_weighting(self, h, w, Ly, Lx, device): weighting = self.delta_border(h, w) weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"], self.split_input_params["clip_max_weight"], ) weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) if self.split_input_params["tie_braker"]: L_weighting = self.delta_border(Ly, Lx) L_weighting = torch.clip(L_weighting, self.split_input_params["clip_min_tie_weight"], self.split_input_params["clip_max_tie_weight"]) L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) weighting = weighting * L_weighting return weighting def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code """ :param x: img of size (bs, c, h, w) :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) """ bs, nc, h, w = x.shape # number of crops in image Ly = (h - kernel_size[0]) // stride[0] + 1 Lx = (w - kernel_size[1]) // stride[1] + 1 if uf == 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) elif uf > 1 and df == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), dilation=1, padding=0, stride=(stride[0] * uf, stride[1] * uf)) fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2) weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx)) elif df > 1 and uf == 1: fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride) unfold = torch.nn.Unfold(**fold_params) fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df), dilation=1, padding=0, stride=(stride[0] // df, stride[1] // df)) fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2) weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype) normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx)) else: raise NotImplementedError return fold, unfold, normalization, weighting @torch.no_grad() def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False, cond_key=None, return_original_cond=False, bs=None): x = super().get_input(batch, k) if bs is not None: x = x[:bs] x = x.to(self.device) encoder_posterior = self.encode_first_stage(x) # print('encoder_posterior.shape') # print(encoder_posterior.shape) z = self.get_first_stage_encoding(encoder_posterior).detach() # print('z.shape') # print(z.shape) # print(cond_key) # print(self.cond_stage_key) # print(cond_key) if self.model.conditioning_key is not None: if cond_key is None: cond_key = self.cond_stage_key if cond_key != self.first_stage_key: if cond_key in ['caption', 'coordinates_bbox','fmri', 'eeg']: xc = batch[cond_key] elif cond_key == 'class_label': xc = batch else: xc = super().get_input(batch, cond_key).to(self.device) else: xc = x # print('get input') # print(not self.cond_stage_trainable) # print(force_c_encode) if not self.cond_stage_trainable or force_c_encode : # print('get learned condition') if isinstance(xc, dict) or isinstance(xc, list): # import pudb; pudb.set_trace() c, re_latent = self.get_learned_conditioning(xc) # c = self.get_learned_conditioning(xc) else: c, re_latent = self.get_learned_conditioning(xc.to(self.device)) # c = self.get_learned_conditioning(xc.to(self.device)) else: c = xc if bs is not None: c = c[:bs] if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) ckey = __conditioning_keys__[self.model.conditioning_key] c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y} else: c = None xc = None if self.use_positional_encodings: pos_x, pos_y = self.compute_latent_shifts(batch) c = {'pos_x': pos_x, 'pos_y': pos_y} out = [z, c , batch['label'], batch['image_raw']] if return_first_stage_outputs: xrec = self.decode_first_stage(z) out.extend([x, xrec]) if return_original_cond: out.append(xc) return out @torch.no_grad() def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z if hasattr(self, "split_input_params"): if self.split_input_params["patch_distributed_vq"]: ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) uf = self.split_input_params["vqf"] bs, nc, h, w = z.shape if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print("reducing stride") fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf) z = unfold(z) # (bn, nc * prod(**ks), L) # 1. Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) # 2. apply model loop over last dim if isinstance(self.first_stage_model, VQModelInterface): output_list = [self.first_stage_model.decode(z[:, :, :, :, i], force_not_quantize=predict_cids or force_not_quantize) for i in range(z.shape[-1])] else: output_list = [self.first_stage_model.decode(z[:, :, :, :, i]) for i in range(z.shape[-1])] o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L) o = o * weighting # Reverse 1. reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together decoded = fold(o) decoded = decoded / normalization # norm is shape (1, 1, h, w) return decoded else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) # same as above but without decorator def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): if predict_cids: if z.dim() == 4: z = torch.argmax(z.exp(), dim=1).long() z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) z = rearrange(z, 'b h w c -> b c h w').contiguous() z = 1. / self.scale_factor * z if hasattr(self, "split_input_params"): if self.split_input_params["patch_distributed_vq"]: ks = self.split_input_params["ks"] # eg. (128, 128) stride = self.split_input_params["stride"] # eg. (64, 64) uf = self.split_input_params["vqf"] bs, nc, h, w = z.shape if ks[0] > h or ks[1] > w: ks = (min(ks[0], h), min(ks[1], w)) print("reducing Kernel") if stride[0] > h or stride[1] > w: stride = (min(stride[0], h), min(stride[1], w)) print("reducing stride") fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf) z = unfold(z) # (bn, nc * prod(**ks), L) # 1. Reshape to img shape z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L ) # 2. apply model loop over last dim if isinstance(self.first_stage_model, VQModelInterface): output_list = [self.first_stage_model.decode(z[:, :, :, :, i], force_not_quantize=predict_cids or force_not_quantize) for i in range(z.shape[-1])] else: output_list = [self.first_stage_model.decode(z[:, :, :, :, i]) for i in range(z.shape[-1])] o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L) o = o * weighting # Reverse 1. reshape to img shape o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L) # stitch crops together decoded = fold(o) decoded = decoded / normalization # norm is shape (1, 1, h, w) return decoded else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) else: if isinstance(self.first_stage_model, VQModelInterface): return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize) else: return self.first_stage_model.decode(z) @torch.no_grad() def encode_first_stage(self, x): return self.first_stage_model.encode(x) def shared_step(self, batch, **kwargs): self.freeze_first_stage() # print('share step\'s get input') x, c, label, image_raw = self.get_input(batch, self.first_stage_key) # print('get input shape') # print('x.shape') # print(x.shape) # print('c.shape') # print(c.shape) if self.return_cond: loss, cc = self(x, c, label, image_raw) return loss, cc else: loss = self(x, c, label, image_raw) return loss def forward(self, x, c, label, image_raw, *args, **kwargs): # print(self.num_timesteps) t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long() # print('t.shape') # print(t.shape) if self.model.conditioning_key is not None: assert c is not None imgs = c if self.cond_stage_trainable: # c = self.get_learned_conditioning(c) c, re_latent = self.get_learned_conditioning(c) # print('c.shape') # print(c.shape) prefix = 'train' if self.training else 'val' loss, loss_dict = self.p_losses(x, c, t, *args, **kwargs) # pre_cls = self.cond_stage_model.get_cls(re_latent) # rencon = self.cond_stage_model.recon(re_latent) if self.clip_tune: image_embeds = self.image_embedder(image_raw) loss_clip = self.cond_stage_model.get_clip_loss(re_latent, image_embeds) # loss_recon = self.recon_loss(imgs, rencon) # loss_cls = self.cls_loss(label, pre_cls) loss += loss_clip # loss += loss_cls # loss_recon + #(self.original_elbo_weight * loss_vlb) # loss_dict.update({f'{prefix}/loss_recon': loss_recon}) # loss_dict.update({f'{prefix}/loss_cls': loss_cls}) loss_dict.update({f'{prefix}/loss_clip': loss_clip}) if self.cls_tune: pre_cls = self.cond_stage_model.get_cls(re_latent) loss_cls = self.cls_loss(label, pre_cls) # image_embeds = self.image_embedder(image_raw) # loss_clip = self.cond_stage_model.get_clip_loss(re_latent, image_embeds) # loss_recon = self.recon_loss(imgs, rencon) # loss_cls = self.cls_loss(label, pre_cls) loss += loss_cls # loss += loss_cls # loss_recon + #(self.original_elbo_weight * loss_vlb) # loss_dict.update({f'{prefix}/loss_recon': loss_recon}) # loss_dict.update({f'{prefix}/loss_cls': loss_cls}) loss_dict.update({f'{prefix}/loss_cls': loss_cls}) # if self.return_cond: # return self.p_losses(x, c, t, *args, **kwargs), c # return self.p_losses(x, c, t, *args, **kwargs) if self.return_cond: return loss, loss_dict, c return loss, loss_dict # def recon_loss(self, ) def recon_loss(self, imgs, pred): """ imgs: [N, 1, num_voxels] pred: [N, L, p] mask: [N, L], 0 is keep, 1 is remove, """ # target = self.patchify(imgs) loss = (pred - imgs) ** 2 loss = loss.mean() # loss = loss.mean(dim=-1) # [N, L], mean loss per patch # loss = (loss * mask).sum() / mask.sum() if mask.sum() != 0 else (loss * mask).sum() # mean loss on removed patches return loss def cls_loss(self, label, pred): return torch.nn.CrossEntropyLoss()(pred, label) def _rescale_annotations(self, bboxes, crop_coordinates): # TODO: move to dataset def rescale_bbox(bbox): x0 = torch.clamp((bbox[0] - crop_coordinates[0]) / crop_coordinates[2]) y0 = torch.clamp((bbox[1] - crop_coordinates[1]) / crop_coordinates[3]) w = min(bbox[2] / crop_coordinates[2], 1 - x0) h = min(bbox[3] / crop_coordinates[3], 1 - y0) return x0, y0, w, h return [rescale_bbox(b) for b in bboxes] def apply_model(self, x_noisy, t, cond, return_ids=False): if isinstance(cond, dict): # hybrid case, cond is exptected to be a dict pass else: if not isinstance(cond, list): cond = [cond] key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn' cond = {key: cond} x_recon = self.model(x_noisy, t, **cond) # print('x_recon') # if isinstance(x_recon, tuple): # print('is tuple') # # print(len(x_recon)) # # print(x_recon[0].shape) # else: # print(x_recon.shape) if isinstance(x_recon, tuple) and not return_ids: return x_recon[0] else: return x_recon def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0) return mean_flat(kl_prior) / np.log(2.0) def p_losses(self, x_start, cond, t, noise=None): noise = default(noise, lambda: torch.randn_like(x_start)) # print('p_losses') # print('noise.shape') # print(noise.shape) x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) # print('x_noisy[0].shape') # print(x_noisy[0].shape) model_output = self.apply_model(x_noisy, t, cond) loss_dict = {} prefix = 'train' if self.training else 'val' if self.parameterization == "x0": target = x_start elif self.parameterization == "eps": target = noise else: raise NotImplementedError() loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3]) loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()}) logvar_t = self.logvar[t].to(self.device) loss = loss_simple / torch.exp(logvar_t) + logvar_t # loss = loss_simple / torch.exp(self.logvar) + self.logvar if self.learn_logvar: loss_dict.update({f'{prefix}/loss_gamma': loss.mean()}) loss_dict.update({'logvar': self.logvar.data.mean()}) loss = self.l_simple_weight * loss.mean() loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3)) loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean() loss_dict.update({f'{prefix}/loss_vlb': loss_vlb}) loss += (self.original_elbo_weight * loss_vlb) loss_dict.update({f'{prefix}/loss': loss}) return loss, loss_dict def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False, return_x0=False, score_corrector=None, corrector_kwargs=None): t_in = t model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) if score_corrector is not None: assert self.parameterization == "eps" model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs) if return_codebook_ids: model_out, logits = model_out if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out else: raise NotImplementedError() if clip_denoised: x_recon.clamp_(-1., 1.) if quantize_denoised: x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) if return_codebook_ids: return model_mean, posterior_variance, posterior_log_variance, logits elif return_x0: return model_mean, posterior_variance, posterior_log_variance, x_recon else: return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False, return_codebook_ids=False, quantize_denoised=False, return_x0=False, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): b, *_, device = *x.shape, x.device outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised, return_codebook_ids=return_codebook_ids, quantize_denoised=quantize_denoised, return_x0=return_x0, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if return_x0: model_mean, _, model_log_variance, x0 = outputs else: model_mean, _, model_log_variance = outputs noise = noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) if return_x0: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0 else: return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False, img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t timesteps = self.num_timesteps if batch_size is not None: b = batch_size if batch_size is not None else shape[0] shape = [batch_size] + list(shape) else: b = batch_size = shape[0] if x_T is None: img = torch.randn(shape, device=self.device) else: img = x_T intermediates = [] if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation', total=timesteps) if verbose else reversed( range(0, timesteps)) if type(temperature) == float: temperature = [temperature] * timesteps for i in iterator: ts = torch.full((b,), i, device=self.device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img, x0_partial = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised, return_x0=True, temperature=temperature[i], noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) if mask is not None: assert x0 is not None img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(x0_partial) if callback: callback(i) if img_callback: img_callback(img, i) return img, intermediates @torch.no_grad() def p_sample_loop(self, cond, shape, return_intermediates=False, x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, start_T=None, log_every_t=None): if not log_every_t: log_every_t = self.log_every_t device = self.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T intermediates = [img] if timesteps is None: timesteps = self.num_timesteps if start_T is not None: timesteps = min(timesteps, start_T) iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed( range(0, timesteps)) if mask is not None: assert x0 is not None assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match for i in iterator: ts = torch.full((b,), i, device=device, dtype=torch.long) if self.shorten_cond_schedule: assert self.model.conditioning_key != 'hybrid' tc = self.cond_ids[ts].to(cond.device) cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) img = self.p_sample(img, cond, ts, clip_denoised=self.clip_denoised, quantize_denoised=quantize_denoised) if mask is not None: img_orig = self.q_sample(x0, ts) img = img_orig * mask + (1. - mask) * img if i % log_every_t == 0 or i == timesteps - 1: intermediates.append(img) if callback: callback(i) if img_callback: img_callback(img, i) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None, verbose=True, timesteps=None, quantize_denoised=False, mask=None, x0=None, shape=None,**kwargs): if shape is None: shape = (batch_size, self.channels, self.image_size, self.image_size) if cond is not None: if isinstance(cond, dict): cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else list(map(lambda x: x[:batch_size], cond[key])) for key in cond} else: cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size] return self.p_sample_loop(cond, shape, return_intermediates=return_intermediates, x_T=x_T, verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised, mask=mask, x0=x0) @torch.no_grad() def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs): if ddim: ddim_sampler = DDIMSampler(self) shape = (self.channels, self.image_size, self.image_size) samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size, shape,cond,verbose=False,**kwargs) else: samples, intermediates = self.sample(cond=cond, batch_size=batch_size, return_intermediates=True,**kwargs) return samples, intermediates @torch.no_grad() def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None, quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, plot_diffusion_rows=True, **kwargs): use_ddim = ddim_steps is not None log = dict() z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key, return_first_stage_outputs=True, force_c_encode=True, return_original_cond=True, bs=N) N = min(x.shape[0], N) n_row = min(x.shape[0], n_row) log["inputs"] = x log["reconstruction"] = xrec if self.model.conditioning_key is not None: if hasattr(self.cond_stage_model, "decode"): xc = self.cond_stage_model.decode(c) log["conditioning"] = xc elif self.cond_stage_key in ["caption"]: xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"]) log["conditioning"] = xc elif self.cond_stage_key == 'class_label': xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"]) log['conditioning'] = xc elif isimage(xc): log["conditioning"] = xc if ismap(xc): log["original_conditioning"] = self.to_rgb(xc) if plot_diffusion_rows: # get diffusion row diffusion_row = list() z_start = z[:n_row] for t in range(self.num_timesteps): if t % self.log_every_t == 0 or t == self.num_timesteps - 1: t = repeat(torch.tensor([t]), '1 -> b', b=n_row) t = t.to(self.device).long() noise = torch.randn_like(z_start) z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) diffusion_row.append(self.decode_first_stage(z_noisy)) diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) log["diffusion_row"] = diffusion_grid if sample: # get denoise row with self.ema_scope("Plotting"): samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, ddim_steps=ddim_steps,eta=ddim_eta) # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) x_samples = self.decode_first_stage(samples) log["samples"] = x_samples if plot_denoise_rows: denoise_grid = self._get_denoise_row_from_list(z_denoise_row) log["denoise_row"] = denoise_grid if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
self.first_stage_model, IdentityFirstStage):
12
2023-12-16 12:52:14+00:00
16k
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
12,128
y, y_lengths, bert, bert_lengths, speakers, ) in enumerate(loader): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = ( net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step ) net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda( rank, non_blocking=True ) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda( rank, non_blocking=True ) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda( rank, non_blocking=True ) bert, bert_lengths = bert.cuda(rank, non_blocking=True), bert_lengths.cuda( rank, non_blocking=True ) speakers = speakers.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): ( y_hat, l_length, attn, ids_slice, x_mask, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_), ) = net_g(x, x_lengths, spec, spec_lengths, bert, bert_lengths, speakers) if ( hps.model.use_mel_posterior_encoder or hps.data.use_mel_posterior_encoder ): mel = spec else: # comment - choihkk # for numerical stable when using fp16 and torch>=2.0.0, # spec.float() could be help in the training stage # https://github.com/jaywalnut310/vits/issues/15 mel = spec_to_mel_torch( spec.float(), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax, ) y_mel = commons.slice_segments( mel, ids_slice, hps.train.segment_size // hps.data.hop_length ) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax, ) y = commons.slice_segments( y, ids_slice * hps.data.hop_length, hps.train.segment_size ) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( y_d_hat_r, y_d_hat_g ) loss_disc_all = loss_disc # Duration Discriminator if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc( hidden_x.detach(), x_mask.detach(), logw_.detach(), logw.detach() ) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all ( loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g, ) = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) grad_norm_dur_disc = commons.clip_grad_value_( net_dur_disc.parameters(), None ) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw_, logw) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl loss_fm = feature_loss(fmap_r, fmap_g)
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 ), f"duration_discriminator_type must be one of {AVAILABLE_DURATION_DISCRIMINATOR_TYPES}" # duration_discriminator_type = AVAILABLE_DURATION_DISCRIMINATOR_TYPES # ここ修正 if duration_discriminator_type == "dur_disc_1": net_dur_disc = DurationDiscriminatorV1( hps.model.hidden_channels, hps.model.hidden_channels, 3, 0.1, gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, ).cuda(rank) elif duration_discriminator_type == "dur_disc_2": net_dur_disc = DurationDiscriminatorV2( hps.model.hidden_channels, hps.model.hidden_channels, 3, 0.1, gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, ).cuda(rank) else: print("NOT using any duration discriminator like VITS1") net_dur_disc = None use_duration_discriminator = False net_g = SynthesizerTrn( len(symbols)+1, posterior_channels, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, mas_noise_scale_initial=mas_noise_scale_initial, noise_scale_delta=noise_scale_delta, **hps.model, ).cuda(rank) net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) optim_g = torch.optim.AdamW( net_g.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) optim_d = torch.optim.AdamW( net_d.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) if net_dur_disc is not None: optim_dur_disc = torch.optim.AdamW( net_dur_disc.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps, ) else: optim_dur_disc = None # comment - choihkk # if we comment out unused parameter like DurationDiscriminator's self.pre_out_norm1,2 self.norm_1,2 # and ResidualCouplingTransformersLayer's self.post_transformer # we don't have to set find_unused_parameters=True # but I will not proceed with commenting out for compatibility with the latest work for others net_g = DDP(net_g, device_ids=[rank]) net_d = DDP(net_d, device_ids=[rank]) if net_dur_disc is not None: net_dur_disc = DDP( net_dur_disc, device_ids=[rank]) try: _, _, _, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g ) _, _, _, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d ) if net_dur_disc is not None: _, _, _, epoch_str = utils.load_checkpoint( utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, ) global_step = (epoch_str - 1) * len(train_loader) input = input("Initialize Global Steps and Epochs ??? y/n") if input == "y": epoch_str = 1 global_step = 0 except: epoch_str = 1 global_step = 0 scheduler_g = torch.optim.lr_scheduler.ExponentialLR( optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) scheduler_d = torch.optim.lr_scheduler.ExponentialLR( optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) if net_dur_disc is not None: scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR( optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2 ) else: scheduler_dur_disc = None scaler = GradScaler(enabled=hps.train.fp16_run) for epoch in range(epoch_str, hps.train.epochs + 1): if rank == 0: train_and_evaluate( rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval], ) else: train_and_evaluate( rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None, ) scheduler_g.step() scheduler_d.step() if net_dur_disc is not None: scheduler_dur_disc.step() def train_and_evaluate( rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers ): net_g, net_d, net_dur_disc = nets optim_g, optim_d, optim_dur_disc = optims scheduler_g, scheduler_d, scheduler_dur_disc = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() if net_dur_disc is not None: net_dur_disc.train() if rank == 0: loader = tqdm.tqdm(train_loader, desc="Loading train data") else: loader = train_loader for batch_idx, ( x, x_lengths, spec, spec_lengths, y, y_lengths, bert, bert_lengths, speakers, ) in enumerate(loader): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = ( net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step ) net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda( rank, non_blocking=True ) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda( rank, non_blocking=True ) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda( rank, non_blocking=True ) bert, bert_lengths = bert.cuda(rank, non_blocking=True), bert_lengths.cuda( rank, non_blocking=True ) speakers = speakers.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): ( y_hat, l_length, attn, ids_slice, x_mask, z_mask, (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_), ) = net_g(x, x_lengths, spec, spec_lengths, bert, bert_lengths, speakers) if ( hps.model.use_mel_posterior_encoder or hps.data.use_mel_posterior_encoder ): mel = spec else: # comment - choihkk # for numerical stable when using fp16 and torch>=2.0.0, # spec.float() could be help in the training stage # https://github.com/jaywalnut310/vits/issues/15 mel = spec_to_mel_torch( spec.float(), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax, ) y_mel = commons.slice_segments( mel, ids_slice, hps.train.segment_size // hps.data.hop_length ) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax, ) y = commons.slice_segments( y, ids_slice * hps.data.hop_length, hps.train.segment_size ) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss( y_d_hat_r, y_d_hat_g ) loss_disc_all = loss_disc # Duration Discriminator if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc( hidden_x.detach(), x_mask.detach(), logw_.detach(), logw.detach() ) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all ( loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g, ) = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) grad_norm_dur_disc = commons.clip_grad_value_( net_dur_disc.parameters(), None ) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw_, logw) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl loss_fm = feature_loss(fmap_r, fmap_g)
loss_gen, losses_gen = generator_loss(y_d_hat_g)
5
2023-12-16 05:34:02+00:00
16k
Ruiyuan-Zhang/CCS
multi_part_assembly/utils/wx_transformer_utilities/multihead_attention.py
[ { "identifier": "FairseqDropout", "path": "multi_part_assembly/utils/wx_transformer_utilities/fairseq_dropout.py", "snippet": "class FairseqDropout(nn.Module):\n\n def __init__(self, p, module_name=None):\n super().__init__()\n self.p = p\n self.module_name = module_name\n ...
import math import time import numpy as np import torch import torch.nn.functional as F import multi_part_assembly.utils.wx_transformer_utilities.fairseq_utils as utils from typing import Dict, Optional, Tuple from torch import Tensor, nn from torch.nn import Parameter from .fairseq_dropout import FairseqDropout from .attention_rim import MultiHeadAttention as MHAMemory from .quant_noise import quant_noise from .group_linear_layer import GroupLinearLayer from .relational_memory_volatile import RelationalMemory from .relational_memory_regressive import RelationalMemory as RelationalMemoryRegressive
13,834
# 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. #import models.fairseq_util #from fairseq.incremental_decoding_utils import with_incremental_state #from .relational_memory_lstm import RelationalMemory # 为什么作者没有从这两个类别中引入relmem? #from fairseq.modules.shared_group_linear_layer import SharedGroupLinearLayer as GroupLinearLayer class MultiheadAttention(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__( self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False, q_noise=0.0, qn_block_size=8, nblocks=1, top_k_ratio=None, use_value_competition=True, shared_memory_attention = False, use_topk = False, topk = 3, num_steps = 5, mem_slots = 4, null_attention = False, regressive = False ): super().__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads
# 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. #import models.fairseq_util #from fairseq.incremental_decoding_utils import with_incremental_state #from .relational_memory_lstm import RelationalMemory # 为什么作者没有从这两个类别中引入relmem? #from fairseq.modules.shared_group_linear_layer import SharedGroupLinearLayer as GroupLinearLayer class MultiheadAttention(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__( self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False, q_noise=0.0, qn_block_size=8, nblocks=1, top_k_ratio=None, use_value_competition=True, shared_memory_attention = False, use_topk = False, topk = 3, num_steps = 5, mem_slots = 4, null_attention = False, regressive = False ): super().__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads
self.dropout_module = FairseqDropout(
0
2023-12-15 13:13:01+00:00
16k
camenduru/FreeInit-hf
app.py
[ { "identifier": "UNet3DConditionModel", "path": "animatediff/models/unet.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Optional[int] = None,\n in...
import os import torch import random import gradio as gr from glob import glob from omegaconf import OmegaConf from safetensors import safe_open from diffusers import AutoencoderKL from diffusers import EulerDiscreteScheduler, DDIMScheduler from diffusers.utils.import_utils import is_xformers_available from transformers import CLIPTextModel, CLIPTokenizer from animatediff.models.unet import UNet3DConditionModel from animatediff.pipelines.pipeline_animation import AnimationFreeInitPipeline from animatediff.utils.util import save_videos_grid from animatediff.utils.convert_from_ckpt import convert_ldm_unet_checkpoint, convert_ldm_clip_checkpoint, convert_ldm_vae_checkpoint from diffusers.training_utils import set_seed from animatediff.utils.freeinit_utils import get_freq_filter from collections import namedtuple
14,182
"A cute raccoon playing guitar in a boat on the ocean", "worst quality, low quality, nsfw, logo", 512, 512, "1566149281915957", "butterworth", 0.25, 0.25, 3, ["use_fp16"] ], # 4-MajicMix [ "majicmixRealistic_v5Preview.safetensors", "mm_sd_v14.ckpt", "1girl, reading book", "(ng_deepnegative_v1_75t:1.2), (badhandv4:1), (worst quality:2), (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, watermark, moles", 512, 512, "2005563494988190", "butterworth", 0.25, 0.25, 3, ["use_fp16"] ], # # 5-RealisticVision # [ # "realisticVisionV51_v20Novae.safetensors", # "mm_sd_v14.ckpt", # "A panda standing on a surfboard in the ocean in sunset.", # "worst quality, low quality, nsfw, logo", # 512, 512, "2005563494988190", # "butterworth", 0.25, 0.25, 3, # ["use_fp16"] # ] ] # clean unrelated ckpts # ckpts = [ # "realisticVisionV40_v20Novae.safetensors", # "majicmixRealistic_v5Preview.safetensors", # "rcnzCartoon3d_v10.safetensors", # "lyriel_v16.safetensors", # "toonyou_beta3.safetensors" # ] # for path in glob(os.path.join("models", "DreamBooth_LoRA", "*.safetensors")): # for ckpt in ckpts: # if path.endswith(ckpt): break # else: # print(f"### Cleaning {path} ...") # os.system(f"rm -rf {path}") # os.system(f"rm -rf {os.path.join('models', 'DreamBooth_LoRA', '*.safetensors')}") # os.system(f"bash download_bashscripts/1-ToonYou.sh") # os.system(f"bash download_bashscripts/2-Lyriel.sh") # os.system(f"bash download_bashscripts/3-RcnzCartoon.sh") # os.system(f"bash download_bashscripts/4-MajicMix.sh") # os.system(f"bash download_bashscripts/5-RealisticVision.sh") # # clean Gradio cache # print(f"### Cleaning cached examples ...") # os.system(f"rm -rf gradio_cached_examples/") class AnimateController: def __init__(self): # config dirs self.basedir = os.getcwd() self.stable_diffusion_dir = os.path.join(self.basedir, "models", "StableDiffusion") self.motion_module_dir = os.path.join(self.basedir, "models", "Motion_Module") self.personalized_model_dir = os.path.join(self.basedir, "models", "DreamBooth_LoRA") self.savedir = os.path.join(self.basedir, "samples") os.makedirs(self.savedir, exist_ok=True) self.base_model_list = [] self.motion_module_list = [] self.filter_type_list = [ "butterworth", "gaussian", "box", "ideal" ] self.selected_base_model = None self.selected_motion_module = None self.selected_filter_type = None self.set_width = None self.set_height = None self.set_d_s = None self.set_d_t = None self.refresh_motion_module() self.refresh_personalized_model() # config models self.inference_config = OmegaConf.load(inference_config_path) self.tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_path, subfolder="tokenizer") self.text_encoder = CLIPTextModel.from_pretrained(pretrained_model_path, subfolder="text_encoder").cuda() self.vae = AutoencoderKL.from_pretrained(pretrained_model_path, subfolder="vae").cuda() self.unet = UNet3DConditionModel.from_pretrained_2d(pretrained_model_path, subfolder="unet", unet_additional_kwargs=OmegaConf.to_container(self.inference_config.unet_additional_kwargs)).cuda() self.freq_filter = None self.update_base_model(self.base_model_list[-2]) self.update_motion_module(self.motion_module_list[0]) self.update_filter(512, 512, self.filter_type_list[0], 0.25, 0.25) def refresh_motion_module(self): motion_module_list = glob(os.path.join(self.motion_module_dir, "*.ckpt")) self.motion_module_list = sorted([os.path.basename(p) for p in motion_module_list]) def refresh_personalized_model(self): base_model_list = glob(os.path.join(self.personalized_model_dir, "*.safetensors")) self.base_model_list = sorted([os.path.basename(p) for p in base_model_list]) def update_base_model(self, base_model_dropdown): self.selected_base_model = base_model_dropdown base_model_dropdown = os.path.join(self.personalized_model_dir, base_model_dropdown) base_model_state_dict = {} with safe_open(base_model_dropdown, framework="pt", device="cpu") as f: for key in f.keys(): base_model_state_dict[key] = f.get_tensor(key)
pretrained_model_path = "models/StableDiffusion/stable-diffusion-v1-5" inference_config_path = "configs/inference/inference-v1.yaml" css = """ .toolbutton { margin-buttom: 0em 0em 0em 0em; max-width: 2.5em; min-width: 2.5em !important; height: 2.5em; } """ examples = [ # 0-RealisticVision [ "realisticVisionV51_v20Novae.safetensors", "mm_sd_v14.ckpt", "A panda standing on a surfboard in the ocean under moonlight.", "worst quality, low quality, nsfw, logo", 512, 512, "2005563494988190", "butterworth", 0.25, 0.25, 3, ["use_fp16"] ], # 1-ToonYou [ "toonyou_beta3.safetensors", "mm_sd_v14.ckpt", "(best quality, masterpiece), 1girl, looking at viewer, blurry background, upper body, contemporary, dress", "(worst quality, low quality)", 512, 512, "478028150728261", "butterworth", 0.25, 0.25, 3, ["use_fp16"] ], # 2-Lyriel [ "lyriel_v16.safetensors", "mm_sd_v14.ckpt", "hypercars cyberpunk moving, muted colors, swirling color smokes, legend, cityscape, space", "3d, cartoon, anime, sketches, worst quality, low quality, nsfw, logo", 512, 512, "1566149281915957", "butterworth", 0.25, 0.25, 3, ["use_fp16"] ], # 3-RCNZ [ "rcnzCartoon3d_v10.safetensors", "mm_sd_v14.ckpt", "A cute raccoon playing guitar in a boat on the ocean", "worst quality, low quality, nsfw, logo", 512, 512, "1566149281915957", "butterworth", 0.25, 0.25, 3, ["use_fp16"] ], # 4-MajicMix [ "majicmixRealistic_v5Preview.safetensors", "mm_sd_v14.ckpt", "1girl, reading book", "(ng_deepnegative_v1_75t:1.2), (badhandv4:1), (worst quality:2), (low quality:2), (normal quality:2), lowres, bad anatomy, bad hands, watermark, moles", 512, 512, "2005563494988190", "butterworth", 0.25, 0.25, 3, ["use_fp16"] ], # # 5-RealisticVision # [ # "realisticVisionV51_v20Novae.safetensors", # "mm_sd_v14.ckpt", # "A panda standing on a surfboard in the ocean in sunset.", # "worst quality, low quality, nsfw, logo", # 512, 512, "2005563494988190", # "butterworth", 0.25, 0.25, 3, # ["use_fp16"] # ] ] # clean unrelated ckpts # ckpts = [ # "realisticVisionV40_v20Novae.safetensors", # "majicmixRealistic_v5Preview.safetensors", # "rcnzCartoon3d_v10.safetensors", # "lyriel_v16.safetensors", # "toonyou_beta3.safetensors" # ] # for path in glob(os.path.join("models", "DreamBooth_LoRA", "*.safetensors")): # for ckpt in ckpts: # if path.endswith(ckpt): break # else: # print(f"### Cleaning {path} ...") # os.system(f"rm -rf {path}") # os.system(f"rm -rf {os.path.join('models', 'DreamBooth_LoRA', '*.safetensors')}") # os.system(f"bash download_bashscripts/1-ToonYou.sh") # os.system(f"bash download_bashscripts/2-Lyriel.sh") # os.system(f"bash download_bashscripts/3-RcnzCartoon.sh") # os.system(f"bash download_bashscripts/4-MajicMix.sh") # os.system(f"bash download_bashscripts/5-RealisticVision.sh") # # clean Gradio cache # print(f"### Cleaning cached examples ...") # os.system(f"rm -rf gradio_cached_examples/") class AnimateController: def __init__(self): # config dirs self.basedir = os.getcwd() self.stable_diffusion_dir = os.path.join(self.basedir, "models", "StableDiffusion") self.motion_module_dir = os.path.join(self.basedir, "models", "Motion_Module") self.personalized_model_dir = os.path.join(self.basedir, "models", "DreamBooth_LoRA") self.savedir = os.path.join(self.basedir, "samples") os.makedirs(self.savedir, exist_ok=True) self.base_model_list = [] self.motion_module_list = [] self.filter_type_list = [ "butterworth", "gaussian", "box", "ideal" ] self.selected_base_model = None self.selected_motion_module = None self.selected_filter_type = None self.set_width = None self.set_height = None self.set_d_s = None self.set_d_t = None self.refresh_motion_module() self.refresh_personalized_model() # config models self.inference_config = OmegaConf.load(inference_config_path) self.tokenizer = CLIPTokenizer.from_pretrained(pretrained_model_path, subfolder="tokenizer") self.text_encoder = CLIPTextModel.from_pretrained(pretrained_model_path, subfolder="text_encoder").cuda() self.vae = AutoencoderKL.from_pretrained(pretrained_model_path, subfolder="vae").cuda() self.unet = UNet3DConditionModel.from_pretrained_2d(pretrained_model_path, subfolder="unet", unet_additional_kwargs=OmegaConf.to_container(self.inference_config.unet_additional_kwargs)).cuda() self.freq_filter = None self.update_base_model(self.base_model_list[-2]) self.update_motion_module(self.motion_module_list[0]) self.update_filter(512, 512, self.filter_type_list[0], 0.25, 0.25) def refresh_motion_module(self): motion_module_list = glob(os.path.join(self.motion_module_dir, "*.ckpt")) self.motion_module_list = sorted([os.path.basename(p) for p in motion_module_list]) def refresh_personalized_model(self): base_model_list = glob(os.path.join(self.personalized_model_dir, "*.safetensors")) self.base_model_list = sorted([os.path.basename(p) for p in base_model_list]) def update_base_model(self, base_model_dropdown): self.selected_base_model = base_model_dropdown base_model_dropdown = os.path.join(self.personalized_model_dir, base_model_dropdown) base_model_state_dict = {} with safe_open(base_model_dropdown, framework="pt", device="cpu") as f: for key in f.keys(): base_model_state_dict[key] = f.get_tensor(key)
converted_vae_checkpoint = convert_ldm_vae_checkpoint(base_model_state_dict, self.vae.config)
5
2023-12-19 21:06:32+00:00
16k
exislow/tidal-dl-ng
tidal_dl_ng/gui.py
[ { "identifier": "get_format_template", "path": "tidal_dl_ng/helper/path.py", "snippet": "def get_format_template(\n media: Track | Album | Playlist | UserPlaylist | Video | Mix | MediaType, settings\n) -> str | bool:\n result = False\n\n if isinstance(media, Track) or media == MediaType.TRACK:\...
import math import sys import qdarktheme import coloredlogs.converter from collections.abc import Callable from tidal_dl_ng.helper.path import get_format_template from PySide6 import QtCore, QtGui, QtWidgets from rich.progress import Progress from tidalapi import Album, Mix, Playlist, Quality, Track, UserPlaylist, Video from tidalapi.session import SearchTypes from tidal_dl_ng.config import Settings, Tidal from tidal_dl_ng.constants import QualityVideo, TidalLists from tidal_dl_ng.download import Download from tidal_dl_ng.logger import XStream, logger_gui from tidal_dl_ng.model.gui_data import ProgressBars, ResultSearch from tidal_dl_ng.ui.main import Ui_MainWindow from tidal_dl_ng.ui.spinner import QtWaitingSpinner from tidal_dl_ng.worker import Worker
11,836
try: except ImportError as e: print(e) print("Qt dependencies missing. Cannot start GUI. Please execute: 'pip install pyside6 pyqtdarktheme'") sys.exit(1) # TODO: Make more use of Exceptions # TODO: Add File -> Version class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
try: except ImportError as e: print(e) print("Qt dependencies missing. Cannot start GUI. Please execute: 'pip install pyside6 pyqtdarktheme'") sys.exit(1) # TODO: Make more use of Exceptions # TODO: Add File -> Version class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
settings: Settings = None
1
2023-12-19 23:05:47+00:00
16k
zyrant/SPGroup3D
tests/test_data/test_datasets/test_scannet_dataset.py
[ { "identifier": "ScanNetDataset", "path": "mmdet3d/datasets/scannet_dataset.py", "snippet": "class ScanNetDataset(Custom3DDataset):\n r\"\"\"ScanNet Dataset for Detection Task.\n\n This class serves as the API for experiments on the ScanNet Dataset.\n\n Please refer to the `github repo <https:/...
import copy import numpy as np import pytest import torch import tempfile import tempfile import mmcv import tempfile import tempfile import mmcv import mmcv from mmdet3d.datasets import (ScanNetDataset, ScanNetInstanceSegDataset, ScanNetSegDataset, ScanNetInstanceSegV2Dataset) from mmdet3d.core.bbox.structures import DepthInstance3DBoxes from os import path as osp from mmdet3d.core.bbox import DepthInstance3DBoxes from os import path as osp from os import path as osp
11,219
2.0221e-02, 2.6153e+00, 1.5109e-02, 7.3335e-01, 1.0429e+00, 1.0251e+00, 0.0000e+00 ]])) scores_3d = torch.tensor( [1.2058e-04, 2.3012e-03, 6.2324e-06, 6.6139e-06, 6.7965e-05]) labels_3d = torch.tensor([0, 0, 0, 0, 0]) result = dict(boxes_3d=boxes_3d, scores_3d=scores_3d, labels_3d=labels_3d) results = [result] scannet_dataset.show(results, temp_dir, show=False) pts_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_points.obj') gt_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_gt.obj') pred_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_pred.obj') mmcv.check_file_exist(pts_file_path) mmcv.check_file_exist(gt_file_path) mmcv.check_file_exist(pred_file_path) tmp_dir.cleanup() # show function with pipeline class_names = ('cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'showercurtrain', 'toilet', 'sink', 'bathtub', 'garbagebin') eval_pipeline = [ dict( type='LoadPointsFromFile', coord_type='DEPTH', shift_height=False, load_dim=6, use_dim=[0, 1, 2]), dict(type='GlobalAlignment', rotation_axis=2), dict( type='DefaultFormatBundle3D', class_names=class_names, with_label=False), dict(type='Collect3D', keys=['points']) ] tmp_dir = tempfile.TemporaryDirectory() temp_dir = tmp_dir.name scannet_dataset.show(results, temp_dir, show=False, pipeline=eval_pipeline) pts_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_points.obj') gt_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_gt.obj') pred_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_pred.obj') mmcv.check_file_exist(pts_file_path) mmcv.check_file_exist(gt_file_path) mmcv.check_file_exist(pred_file_path) tmp_dir.cleanup() def test_seg_getitem(): np.random.seed(0) root_path = './tests/data/scannet/' ann_file = './tests/data/scannet/scannet_infos.pkl' class_names = ('wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'showercurtrain', 'toilet', 'sink', 'bathtub', 'otherfurniture') palette = [ [174, 199, 232], [152, 223, 138], [31, 119, 180], [255, 187, 120], [188, 189, 34], [140, 86, 75], [255, 152, 150], [214, 39, 40], [197, 176, 213], [148, 103, 189], [196, 156, 148], [23, 190, 207], [247, 182, 210], [219, 219, 141], [255, 127, 14], [158, 218, 229], [44, 160, 44], [112, 128, 144], [227, 119, 194], [82, 84, 163], ] scene_idxs = [0 for _ in range(20)] # test network inputs are (xyz, rgb, normalized_xyz) pipelines = [ dict( type='LoadPointsFromFile', coord_type='DEPTH', shift_height=False, use_color=True, load_dim=6, use_dim=[0, 1, 2, 3, 4, 5]), dict( type='LoadAnnotations3D', with_bbox_3d=False, with_label_3d=False, with_mask_3d=False, with_seg_3d=True), dict( type='PointSegClassMapping', valid_cat_ids=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39), max_cat_id=40), dict( type='IndoorPatchPointSample', num_points=5, block_size=1.5, ignore_index=len(class_names), use_normalized_coord=True, enlarge_size=0.2, min_unique_num=None), dict(type='NormalizePointsColor', color_mean=None), dict(type='DefaultFormatBundle3D', class_names=class_names), dict( type='Collect3D', keys=['points', 'pts_semantic_mask'], meta_keys=['file_name', 'sample_idx']) ]
# Copyright (c) OpenMMLab. All rights reserved. def test_getitem(): np.random.seed(0) root_path = './tests/data/scannet/' ann_file = './tests/data/scannet/scannet_infos.pkl' class_names = ('cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'showercurtrain', 'toilet', 'sink', 'bathtub', 'garbagebin') pipelines = [ dict( type='LoadPointsFromFile', coord_type='DEPTH', shift_height=True, load_dim=6, use_dim=[0, 1, 2]), dict( type='LoadAnnotations3D', with_bbox_3d=True, with_label_3d=True, with_mask_3d=True, with_seg_3d=True), dict(type='GlobalAlignment', rotation_axis=2), dict( type='PointSegClassMapping', valid_cat_ids=(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39)), dict(type='PointSample', num_points=5), dict( type='RandomFlip3D', sync_2d=False, flip_ratio_bev_horizontal=1.0, flip_ratio_bev_vertical=1.0), dict( type='GlobalRotScaleTrans', rot_range=[-0.087266, 0.087266], scale_ratio_range=[1.0, 1.0], shift_height=True), dict(type='DefaultFormatBundle3D', class_names=class_names), dict( type='Collect3D', keys=[ 'points', 'gt_bboxes_3d', 'gt_labels_3d', 'pts_semantic_mask', 'pts_instance_mask' ], meta_keys=['file_name', 'sample_idx', 'pcd_rotation']), ] scannet_dataset = ScanNetDataset(root_path, ann_file, pipelines) data = scannet_dataset[0] points = data['points']._data gt_bboxes_3d = data['gt_bboxes_3d']._data gt_labels = data['gt_labels_3d']._data pts_semantic_mask = data['pts_semantic_mask']._data pts_instance_mask = data['pts_instance_mask']._data file_name = data['img_metas']._data['file_name'] pcd_rotation = data['img_metas']._data['pcd_rotation'] sample_idx = data['img_metas']._data['sample_idx'] expected_rotation = np.array([[0.99654, 0.08311407, 0.], [-0.08311407, 0.99654, 0.], [0., 0., 1.]]) assert file_name == './tests/data/scannet/points/scene0000_00.bin' assert np.allclose(pcd_rotation, expected_rotation, 1e-3) assert sample_idx == 'scene0000_00' expected_points = torch.tensor( [[1.8339e+00, 2.1093e+00, 2.2900e+00, 2.3895e+00], [3.6079e+00, 1.4592e-01, 2.0687e+00, 2.1682e+00], [4.1886e+00, 5.0614e+00, -1.0841e-01, -8.8736e-03], [6.8790e+00, 1.5086e+00, -9.3154e-02, 6.3816e-03], [4.8253e+00, 2.6668e-01, 1.4917e+00, 1.5912e+00]]) expected_gt_bboxes_3d = torch.tensor( [[-1.1835, -3.6317, 1.5704, 1.7577, 0.3761, 0.5724, 0.0000], [-3.1832, 3.2269, 1.1911, 0.6727, 0.2251, 0.6715, 0.0000], [-0.9598, -2.2864, 0.0093, 0.7506, 2.5709, 1.2145, 0.0000], [-2.6988, -2.7354, 0.8288, 0.7680, 1.8877, 0.2870, 0.0000], [3.2989, 0.2885, -0.0090, 0.7600, 3.8814, 2.1603, 0.0000]]) expected_gt_labels = np.array([ 6, 6, 4, 9, 11, 11, 10, 0, 15, 17, 17, 17, 3, 12, 4, 4, 14, 1, 0, 0, 0, 0, 0, 0, 5, 5, 5 ]) expected_pts_semantic_mask = np.array([0, 18, 18, 18, 18]) expected_pts_instance_mask = np.array([44, 22, 10, 10, 57]) original_classes = scannet_dataset.CLASSES assert scannet_dataset.CLASSES == class_names assert torch.allclose(points, expected_points, 1e-2) assert gt_bboxes_3d.tensor[:5].shape == (5, 7) assert torch.allclose(gt_bboxes_3d.tensor[:5], expected_gt_bboxes_3d, 1e-2) assert np.all(gt_labels.numpy() == expected_gt_labels) assert np.all(pts_semantic_mask.numpy() == expected_pts_semantic_mask) assert np.all(pts_instance_mask.numpy() == expected_pts_instance_mask) assert original_classes == class_names scannet_dataset = ScanNetDataset( root_path, ann_file, pipeline=None, classes=['cabinet', 'bed']) assert scannet_dataset.CLASSES != original_classes assert scannet_dataset.CLASSES == ['cabinet', 'bed'] scannet_dataset = ScanNetDataset( root_path, ann_file, pipeline=None, classes=('cabinet', 'bed')) assert scannet_dataset.CLASSES != original_classes assert scannet_dataset.CLASSES == ('cabinet', 'bed') # Test load classes from file with tempfile.TemporaryDirectory() as tmpdir: path = tmpdir + 'classes.txt' with open(path, 'w') as f: f.write('cabinet\nbed\n') scannet_dataset = ScanNetDataset( root_path, ann_file, pipeline=None, classes=path) assert scannet_dataset.CLASSES != original_classes assert scannet_dataset.CLASSES == ['cabinet', 'bed'] def test_evaluate(): if not torch.cuda.is_available(): pytest.skip() root_path = './tests/data/scannet' ann_file = './tests/data/scannet/scannet_infos.pkl' scannet_dataset = ScanNetDataset(root_path, ann_file) results = [] pred_boxes = dict() pred_boxes['boxes_3d'] = DepthInstance3DBoxes( torch.tensor([[ 1.4813e+00, 3.5207e+00, 1.5704e+00, 1.7445e+00, 2.3196e-01, 5.7235e-01, 0.0000e+00 ], [ 2.9040e+00, -3.4803e+00, 1.1911e+00, 6.6078e-01, 1.7072e-01, 6.7154e-01, 0.0000e+00 ], [ 1.1466e+00, 2.1987e+00, 9.2576e-03, 5.4184e-01, 2.5346e+00, 1.2145e+00, 0.0000e+00 ], [ 2.9168e+00, 2.5016e+00, 8.2875e-01, 6.1697e-01, 1.8428e+00, 2.8697e-01, 0.0000e+00 ], [ -3.3114e+00, -1.3351e-02, -8.9524e-03, 4.4082e-01, 3.8582e+00, 2.1603e+00, 0.0000e+00 ], [ -2.0135e+00, -3.4857e+00, 9.3848e-01, 1.9911e+00, 2.1603e-01, 1.2767e+00, 0.0000e+00 ], [ -2.1945e+00, -3.1402e+00, -3.8165e-02, 1.4801e+00, 6.8676e-01, 1.0586e+00, 0.0000e+00 ], [ -2.7553e+00, 2.4055e+00, -2.9972e-02, 1.4764e+00, 1.4927e+00, 2.3380e+00, 0.0000e+00 ]])) pred_boxes['labels_3d'] = torch.tensor([6, 6, 4, 9, 11, 11]) pred_boxes['scores_3d'] = torch.tensor([0.5, 1.0, 1.0, 1.0, 1.0, 0.5]) results.append(pred_boxes) metric = [0.25, 0.5] ret_dict = scannet_dataset.evaluate(results, metric) assert abs(ret_dict['table_AP_0.25'] - 0.3333) < 0.01 assert abs(ret_dict['window_AP_0.25'] - 1.0) < 0.01 assert abs(ret_dict['counter_AP_0.25'] - 1.0) < 0.01 assert abs(ret_dict['curtain_AP_0.25'] - 1.0) < 0.01 # test evaluate with pipeline class_names = ('cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'showercurtrain', 'toilet', 'sink', 'bathtub', 'garbagebin') eval_pipeline = [ dict( type='LoadPointsFromFile', coord_type='DEPTH', shift_height=False, load_dim=6, use_dim=[0, 1, 2]), dict(type='GlobalAlignment', rotation_axis=2), dict( type='DefaultFormatBundle3D', class_names=class_names, with_label=False), dict(type='Collect3D', keys=['points']) ] ret_dict = scannet_dataset.evaluate( results, metric, pipeline=eval_pipeline) assert abs(ret_dict['table_AP_0.25'] - 0.3333) < 0.01 assert abs(ret_dict['window_AP_0.25'] - 1.0) < 0.01 assert abs(ret_dict['counter_AP_0.25'] - 1.0) < 0.01 assert abs(ret_dict['curtain_AP_0.25'] - 1.0) < 0.01 def test_show(): tmp_dir = tempfile.TemporaryDirectory() temp_dir = tmp_dir.name root_path = './tests/data/scannet' ann_file = './tests/data/scannet/scannet_infos.pkl' scannet_dataset = ScanNetDataset(root_path, ann_file) boxes_3d = DepthInstance3DBoxes( torch.tensor([[ -2.4053e+00, 9.2295e-01, 8.0661e-02, 2.4054e+00, 2.1468e+00, 8.5990e-01, 0.0000e+00 ], [ -1.9341e+00, -2.0741e+00, 3.0698e-03, 3.2206e-01, 2.5322e-01, 3.5144e-01, 0.0000e+00 ], [ -3.6908e+00, 8.0684e-03, 2.6201e-01, 4.1515e-01, 7.6489e-01, 5.3585e-01, 0.0000e+00 ], [ 2.6332e+00, 8.5143e-01, -4.9964e-03, 3.0367e-01, 1.3448e+00, 1.8329e+00, 0.0000e+00 ], [ 2.0221e-02, 2.6153e+00, 1.5109e-02, 7.3335e-01, 1.0429e+00, 1.0251e+00, 0.0000e+00 ]])) scores_3d = torch.tensor( [1.2058e-04, 2.3012e-03, 6.2324e-06, 6.6139e-06, 6.7965e-05]) labels_3d = torch.tensor([0, 0, 0, 0, 0]) result = dict(boxes_3d=boxes_3d, scores_3d=scores_3d, labels_3d=labels_3d) results = [result] scannet_dataset.show(results, temp_dir, show=False) pts_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_points.obj') gt_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_gt.obj') pred_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_pred.obj') mmcv.check_file_exist(pts_file_path) mmcv.check_file_exist(gt_file_path) mmcv.check_file_exist(pred_file_path) tmp_dir.cleanup() # show function with pipeline class_names = ('cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'showercurtrain', 'toilet', 'sink', 'bathtub', 'garbagebin') eval_pipeline = [ dict( type='LoadPointsFromFile', coord_type='DEPTH', shift_height=False, load_dim=6, use_dim=[0, 1, 2]), dict(type='GlobalAlignment', rotation_axis=2), dict( type='DefaultFormatBundle3D', class_names=class_names, with_label=False), dict(type='Collect3D', keys=['points']) ] tmp_dir = tempfile.TemporaryDirectory() temp_dir = tmp_dir.name scannet_dataset.show(results, temp_dir, show=False, pipeline=eval_pipeline) pts_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_points.obj') gt_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_gt.obj') pred_file_path = osp.join(temp_dir, 'scene0000_00', 'scene0000_00_pred.obj') mmcv.check_file_exist(pts_file_path) mmcv.check_file_exist(gt_file_path) mmcv.check_file_exist(pred_file_path) tmp_dir.cleanup() def test_seg_getitem(): np.random.seed(0) root_path = './tests/data/scannet/' ann_file = './tests/data/scannet/scannet_infos.pkl' class_names = ('wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window', 'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator', 'showercurtrain', 'toilet', 'sink', 'bathtub', 'otherfurniture') palette = [ [174, 199, 232], [152, 223, 138], [31, 119, 180], [255, 187, 120], [188, 189, 34], [140, 86, 75], [255, 152, 150], [214, 39, 40], [197, 176, 213], [148, 103, 189], [196, 156, 148], [23, 190, 207], [247, 182, 210], [219, 219, 141], [255, 127, 14], [158, 218, 229], [44, 160, 44], [112, 128, 144], [227, 119, 194], [82, 84, 163], ] scene_idxs = [0 for _ in range(20)] # test network inputs are (xyz, rgb, normalized_xyz) pipelines = [ dict( type='LoadPointsFromFile', coord_type='DEPTH', shift_height=False, use_color=True, load_dim=6, use_dim=[0, 1, 2, 3, 4, 5]), dict( type='LoadAnnotations3D', with_bbox_3d=False, with_label_3d=False, with_mask_3d=False, with_seg_3d=True), dict( type='PointSegClassMapping', valid_cat_ids=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39), max_cat_id=40), dict( type='IndoorPatchPointSample', num_points=5, block_size=1.5, ignore_index=len(class_names), use_normalized_coord=True, enlarge_size=0.2, min_unique_num=None), dict(type='NormalizePointsColor', color_mean=None), dict(type='DefaultFormatBundle3D', class_names=class_names), dict( type='Collect3D', keys=['points', 'pts_semantic_mask'], meta_keys=['file_name', 'sample_idx']) ]
scannet_dataset = ScanNetSegDataset(
2
2023-12-21 12:50:35+00:00
16k
v3ucn/Bert-vits2-V2.2
train_ms.py
[ { "identifier": "config", "path": "config.py", "snippet": "class Resample_config:\nclass Preprocess_text_config:\nclass Bert_gen_config:\nclass Emo_gen_config:\nclass Train_ms_config:\nclass Webui_config:\nclass Server_config:\nclass Translate_config:\nclass Config:\n def __init__(self, in_dir: str, ...
import platform import os import torch import torch.distributed as dist import logging import argparse import datetime import gc import commons import utils from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from config import config from data_utils import ( TextAudioSpeakerLoader, TextAudioSpeakerCollate, DistributedBucketSampler, ) from models import ( SynthesizerTrn, MultiPeriodDiscriminator, DurationDiscriminator, ) from losses import generator_loss, discriminator_loss, feature_loss, kl_loss from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols
10,900
"--model", type=str, help="数据集文件夹路径,请注意,数据不再默认放在/logs文件夹下。如果需要用命令行配置,请声明相对于根目录的路径", default=config.dataset_path, ) args = parser.parse_args() model_dir = os.path.join(args.model, config.train_ms_config.model) if not os.path.exists(model_dir): os.makedirs(model_dir) hps = utils.get_hparams_from_file(args.config) hps.model_dir = model_dir # 比较路径是否相同 if os.path.realpath(args.config) != os.path.realpath( config.train_ms_config.config_path ): with open(args.config, "r", encoding="utf-8") as f: data = f.read() with open(config.train_ms_config.config_path, "w", encoding="utf-8") as f: f.write(data) torch.manual_seed(hps.train.seed) torch.cuda.set_device(local_rank) 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")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, ) collate_fn = TextAudioSpeakerCollate() train_loader = DataLoader( train_dataset, num_workers=min(config.train_ms_config.num_workers, os.cpu_count() - 1), shuffle=False, pin_memory=True, collate_fn=collate_fn, batch_sampler=train_sampler, persistent_workers=True, prefetch_factor=4, ) # DataLoader config could be adjusted. if rank == 0: eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) eval_loader = DataLoader( eval_dataset, num_workers=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False, collate_fn=collate_fn, ) if ( "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas is True ): print("Using noise scaled MAS for VITS2") mas_noise_scale_initial = 0.01 noise_scale_delta = 2e-6 else: print("Using normal MAS for VITS1") 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 is True ): print("Using duration discriminator for VITS2") net_dur_disc = DurationDiscriminator( hps.model.hidden_channels, hps.model.hidden_channels, 3, 0.1, gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, ).cuda(local_rank) if ( "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder is True ): if hps.data.n_speakers == 0: raise ValueError( "n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model" ) else: print("Using normal encoder for VITS1") net_g = SynthesizerTrn( len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, mas_noise_scale_initial=mas_noise_scale_initial, noise_scale_delta=noise_scale_delta, **hps.model, ).cuda(local_rank) if getattr(hps.train, "freeze_ZH_bert", False): print("Freezing ZH bert encoder !!!") for param in net_g.enc_p.bert_proj.parameters(): param.requires_grad = False if getattr(hps.train, "freeze_EN_bert", False): print("Freezing EN bert encoder !!!") for param in net_g.enc_p.en_bert_proj.parameters(): param.requires_grad = False if getattr(hps.train, "freeze_JP_bert", False): print("Freezing JP bert encoder !!!") for param in net_g.enc_p.ja_bert_proj.parameters(): param.requires_grad = False
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 torch.backends.cuda.enable_math_sdp(True) global_step = 0 def run(): # 环境变量解析 envs = config.train_ms_config.env for env_name, env_value in envs.items(): if env_name not in os.environ.keys(): print("加载config中的配置{}".format(str(env_value))) os.environ[env_name] = str(env_value) print( "加载环境变量 \nMASTER_ADDR: {},\nMASTER_PORT: {},\nWORLD_SIZE: {},\nRANK: {},\nLOCAL_RANK: {}".format( os.environ["MASTER_ADDR"], os.environ["MASTER_PORT"], os.environ["WORLD_SIZE"], os.environ["RANK"], os.environ["LOCAL_RANK"], ) ) backend = "nccl" if platform.system() == "Windows": backend = "gloo" # If Windows,switch to gloo backend. dist.init_process_group( backend=backend, init_method="env://", timeout=datetime.timedelta(seconds=300), ) # Use torchrun instead of mp.spawn rank = dist.get_rank() local_rank = int(os.environ["LOCAL_RANK"]) n_gpus = dist.get_world_size() # 命令行/config.yml配置解析 # hps = utils.get_hparams() parser = argparse.ArgumentParser() # 非必要不建议使用命令行配置,请使用config.yml文件 parser.add_argument( "-c", "--config", type=str, default=config.train_ms_config.config_path, help="JSON file for configuration", ) parser.add_argument( "-m", "--model", type=str, help="数据集文件夹路径,请注意,数据不再默认放在/logs文件夹下。如果需要用命令行配置,请声明相对于根目录的路径", default=config.dataset_path, ) args = parser.parse_args() model_dir = os.path.join(args.model, config.train_ms_config.model) if not os.path.exists(model_dir): os.makedirs(model_dir) hps = utils.get_hparams_from_file(args.config) hps.model_dir = model_dir # 比较路径是否相同 if os.path.realpath(args.config) != os.path.realpath( config.train_ms_config.config_path ): with open(args.config, "r", encoding="utf-8") as f: data = f.read() with open(config.train_ms_config.config_path, "w", encoding="utf-8") as f: f.write(data) torch.manual_seed(hps.train.seed) torch.cuda.set_device(local_rank) 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")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, ) collate_fn = TextAudioSpeakerCollate() train_loader = DataLoader( train_dataset, num_workers=min(config.train_ms_config.num_workers, os.cpu_count() - 1), shuffle=False, pin_memory=True, collate_fn=collate_fn, batch_sampler=train_sampler, persistent_workers=True, prefetch_factor=4, ) # DataLoader config could be adjusted. if rank == 0: eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) eval_loader = DataLoader( eval_dataset, num_workers=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False, collate_fn=collate_fn, ) if ( "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas is True ): print("Using noise scaled MAS for VITS2") mas_noise_scale_initial = 0.01 noise_scale_delta = 2e-6 else: print("Using normal MAS for VITS1") 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 is True ): print("Using duration discriminator for VITS2") net_dur_disc = DurationDiscriminator( hps.model.hidden_channels, hps.model.hidden_channels, 3, 0.1, gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, ).cuda(local_rank) if ( "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder is True ): if hps.data.n_speakers == 0: raise ValueError( "n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model" ) else: print("Using normal encoder for VITS1") net_g = SynthesizerTrn( len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, mas_noise_scale_initial=mas_noise_scale_initial, noise_scale_delta=noise_scale_delta, **hps.model, ).cuda(local_rank) if getattr(hps.train, "freeze_ZH_bert", False): print("Freezing ZH bert encoder !!!") for param in net_g.enc_p.bert_proj.parameters(): param.requires_grad = False if getattr(hps.train, "freeze_EN_bert", False): print("Freezing EN bert encoder !!!") for param in net_g.enc_p.en_bert_proj.parameters(): param.requires_grad = False if getattr(hps.train, "freeze_JP_bert", False): print("Freezing JP bert encoder !!!") for param in net_g.enc_p.ja_bert_proj.parameters(): param.requires_grad = False
net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(local_rank)
5
2023-12-18 04:54:46+00:00
16k
m-abr/FCPCodebase
scripts/utils/Inv_Kinematics.py
[ { "identifier": "Base_Agent", "path": "agent/Base_Agent.py", "snippet": "class Base_Agent():\n all_agents = []\n\n def __init__(self, host:str, agent_port:int, monitor_port:int, unum:int, robot_type:int, team_name:str, enable_log:bool=True,\n enable_draw:bool=True, apply_play_mode...
from agent.Base_Agent import Base_Agent as Agent from itertools import count from math_ops.Inverse_Kinematics import Inverse_Kinematics from scripts.commons.Script import Script from world.commons.Draw import Draw import numpy as np
11,392
class Inv_Kinematics(): def __init__(self, script:Script) -> None: self.args = script.args self.last_action = (0,0,0) self.gravity = True # Initial pose is a neutral pose where all angles are 0 leg_y_dev, upper_leg_height, upper_leg_depth, lower_leg_len, _, _ = Inverse_Kinematics.NAO_SPECS_PER_ROBOT[self.args.r] leg_height = upper_leg_height + lower_leg_len self.feet_pose = [ [[upper_leg_depth,leg_y_dev,-leg_height],[0,0,0]], [[upper_leg_depth,-leg_y_dev,-leg_height], [0,0,0]] ] def _user_control(self): while True: inp = input("Command:") if inp == "": return 2 elif inp == ".": return 1 elif inp == "h": self.print_help(); continue elif inp == "g": self.gravity = not self.gravity print("Using gravity:",self.gravity) if self.gravity: return 6 # extra steps for beam to take effect else: return 1 #Check if user input is a value try: val = float(inp) self.feet_pose[self.last_action[0]][self.last_action[1]][self.last_action[2]] = val continue except: pass if inp[0] not in ['l','r'] or inp[1] not in ['x','y','z','X','Y','Z']: print("Illegal command!") continue side = 0 if inp[0]=='l' else 1 pos_rot = 0 if inp[1].islower() else 1 axis = {'x':0,'y':1,'z':2}[inp[1].lower()] self.last_action = (side,pos_rot,axis) try: val = float(inp[2:]) self.feet_pose[side][pos_rot][axis] = val except: print("Illegal value conversion!")
class Inv_Kinematics(): def __init__(self, script:Script) -> None: self.args = script.args self.last_action = (0,0,0) self.gravity = True # Initial pose is a neutral pose where all angles are 0 leg_y_dev, upper_leg_height, upper_leg_depth, lower_leg_len, _, _ = Inverse_Kinematics.NAO_SPECS_PER_ROBOT[self.args.r] leg_height = upper_leg_height + lower_leg_len self.feet_pose = [ [[upper_leg_depth,leg_y_dev,-leg_height],[0,0,0]], [[upper_leg_depth,-leg_y_dev,-leg_height], [0,0,0]] ] def _user_control(self): while True: inp = input("Command:") if inp == "": return 2 elif inp == ".": return 1 elif inp == "h": self.print_help(); continue elif inp == "g": self.gravity = not self.gravity print("Using gravity:",self.gravity) if self.gravity: return 6 # extra steps for beam to take effect else: return 1 #Check if user input is a value try: val = float(inp) self.feet_pose[self.last_action[0]][self.last_action[1]][self.last_action[2]] = val continue except: pass if inp[0] not in ['l','r'] or inp[1] not in ['x','y','z','X','Y','Z']: print("Illegal command!") continue side = 0 if inp[0]=='l' else 1 pos_rot = 0 if inp[1].islower() else 1 axis = {'x':0,'y':1,'z':2}[inp[1].lower()] self.last_action = (side,pos_rot,axis) try: val = float(inp[2:]) self.feet_pose[side][pos_rot][axis] = val except: print("Illegal value conversion!")
def _draw_labels(self, player:Agent):
5
2023-12-16 23:40:23+00:00
16k
daihaojun554/biliscrapy
biliscrapy/network/bilibili_danmu.py
[ { "identifier": "bili_pb2", "path": "biliscrapy/network/protobuf/bili_pb2.py", "snippet": "DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x08my.proto\\x12 bilibili.community.service.dm.v1\\\"d\\n\\x06\\x41vatar\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\t\\x12\\x0b\\n\\x03url\\x18\\x02 \\x01(...
import logging import os import json import sys import requests from datetime import datetime from .protobuf import bili_pb2 as Danmaku from .bilibili_utils import bili_utils
12,925
headers = { 'authority': 'message.bilibili.com', 'accept': 'application/json, text/plain, */*', 'accept-language': 'zh-CN,zh;q=0.9', 'cache-control': 'no-cache', 'origin': 'https://www.bilibili.com', 'pragma': 'no-cache', 'referer': 'https://www.bilibili.com/', 'sec-ch-ua': '"Chromium";v="118", "Google Chrome";v="118", "Not=A?Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', } # import bili_pb2 as Danmaku class Danmu: def __init__(self): self.utils = bili_utils() self.script_dir = os.path.dirname(os.path.abspath(__file__)) # 构建文件路径 file_path = os.path.join(self.script_dir, 'bilibili_cookies.json') if not file_path: self.cookies = {} with open(file_path, 'r') as file: self.cookies_data = json.load(file) self.cookies = {cookie['name']: cookie['value'] for cookie in self.cookies_data} self.headers = headers self.logger = logging.getLogger('log') def bv2cid(self, bvorurl): try: bv = self.utils.bv_get(bvorurl) cid = self.utils.bv2cid(bv) return cid except Exception as e: self.logger.error(e) return None # 获取某个 oid 下存在弹幕的日期列表 def get_available_dates(self, oid, year=None, month=None): if not year or not month: now = datetime.now() year = now.year month = now.month # 如果month 是1.2.3.4.5.6.7.8.9 前面补0 if month < 10: month = '0' + str(month) url = f'https://api.bilibili.com/x/v2/dm/history/index?type=1&oid={oid}&month={year}-{month}' response = requests.get(url, cookies=self.cookies, headers=self.headers) if response.status_code == 200: data = response.json() return data.get("data", []) else: self.logger.error("请检查你输入的 oid 号码!!") self.logger.error(f"当前请求的 URL 为: {url}") return [] ''' 下载某个视频的弹幕文件 ''' def down_so_files(self, oid, dates): if dates == None: return if oid == None: self.logger.info("请输入正确的 oid 号码!!") return if not os.path.exists(os.path.join(self.script_dir, 'data/danmaku')): os.mkdir(os.path.join(self.script_dir, 'data/danmaku')) elif dates: url = f'https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid={oid}' for date in dates: url_ = f'{url}&date={date}' self.logger.info(f"正在下载 {oid}-{date}.so 文件,请稍后...") response = requests.get(url_, cookies=self.cookies, headers=self.headers) if response.status_code == 200: with open(os.path.join(self.script_dir, 'data/danmaku/', f'{oid}-{date}.so'), 'wb') as f: f.write(response.content) else: self.logger.info("请检查你输入的 oid 号码!!") self.logger.info(f"当前请求的 URL 为: {url}") return self.logger.info(f"下载完成!") # 将.so文件解析并保存为JSON文件 def parse_so_to_json(self, oid, dates): try: if dates == None: self.logger.error("日期为空") return all_danmaku = set() # 用集合存储所有弹幕数据 for date in dates: file_path = os.path.join(self.script_dir, 'data/danmaku/', f'{oid}-{date}.so') with open(file_path, 'rb') as f: data = f.read()
headers = { 'authority': 'message.bilibili.com', 'accept': 'application/json, text/plain, */*', 'accept-language': 'zh-CN,zh;q=0.9', 'cache-control': 'no-cache', 'origin': 'https://www.bilibili.com', 'pragma': 'no-cache', 'referer': 'https://www.bilibili.com/', 'sec-ch-ua': '"Chromium";v="118", "Google Chrome";v="118", "Not=A?Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', } # import bili_pb2 as Danmaku class Danmu: def __init__(self): self.utils = bili_utils() self.script_dir = os.path.dirname(os.path.abspath(__file__)) # 构建文件路径 file_path = os.path.join(self.script_dir, 'bilibili_cookies.json') if not file_path: self.cookies = {} with open(file_path, 'r') as file: self.cookies_data = json.load(file) self.cookies = {cookie['name']: cookie['value'] for cookie in self.cookies_data} self.headers = headers self.logger = logging.getLogger('log') def bv2cid(self, bvorurl): try: bv = self.utils.bv_get(bvorurl) cid = self.utils.bv2cid(bv) return cid except Exception as e: self.logger.error(e) return None # 获取某个 oid 下存在弹幕的日期列表 def get_available_dates(self, oid, year=None, month=None): if not year or not month: now = datetime.now() year = now.year month = now.month # 如果month 是1.2.3.4.5.6.7.8.9 前面补0 if month < 10: month = '0' + str(month) url = f'https://api.bilibili.com/x/v2/dm/history/index?type=1&oid={oid}&month={year}-{month}' response = requests.get(url, cookies=self.cookies, headers=self.headers) if response.status_code == 200: data = response.json() return data.get("data", []) else: self.logger.error("请检查你输入的 oid 号码!!") self.logger.error(f"当前请求的 URL 为: {url}") return [] ''' 下载某个视频的弹幕文件 ''' def down_so_files(self, oid, dates): if dates == None: return if oid == None: self.logger.info("请输入正确的 oid 号码!!") return if not os.path.exists(os.path.join(self.script_dir, 'data/danmaku')): os.mkdir(os.path.join(self.script_dir, 'data/danmaku')) elif dates: url = f'https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid={oid}' for date in dates: url_ = f'{url}&date={date}' self.logger.info(f"正在下载 {oid}-{date}.so 文件,请稍后...") response = requests.get(url_, cookies=self.cookies, headers=self.headers) if response.status_code == 200: with open(os.path.join(self.script_dir, 'data/danmaku/', f'{oid}-{date}.so'), 'wb') as f: f.write(response.content) else: self.logger.info("请检查你输入的 oid 号码!!") self.logger.info(f"当前请求的 URL 为: {url}") return self.logger.info(f"下载完成!") # 将.so文件解析并保存为JSON文件 def parse_so_to_json(self, oid, dates): try: if dates == None: self.logger.error("日期为空") return all_danmaku = set() # 用集合存储所有弹幕数据 for date in dates: file_path = os.path.join(self.script_dir, 'data/danmaku/', f'{oid}-{date}.so') with open(file_path, 'rb') as f: data = f.read()
my_seg = Danmaku.DmSegMobileReply()
0
2023-12-14 10:14:24+00:00
16k
Angryrou/udao
udao/optimization/tests/moo/test_weighted_sum.py
[ { "identifier": "logger", "path": "udao/utils/logging.py", "snippet": "def _get_logger(name: str = \"udao\", level: int = logging.DEBUG) -> logging.Logger:" }, { "identifier": "Constraint", "path": "udao/optimization/concepts/constraint.py", "snippet": "class Constraint:\n \"\"\"An op...
from typing import Dict, Optional from ....utils.logging import logger from ...concepts import Constraint, Objective from ...concepts.problem import MOProblem from ...moo.weighted_sum import WeightedSum from ...soo.grid_search_solver import GridSearchSolver from ...soo.mogd import MOGD from ...soo.random_sampler_solver import RandomSamplerSolver from ...soo.so_solver import SOSolver from ...utils.exceptions import NoSolutionError from ...utils.moo_utils import even_weights import numpy as np import pytest import torch as th
11,710
class TestWeightedSum: @pytest.mark.parametrize( "inner_solver", [ GridSearchSolver(GridSearchSolver.Params(n_grids_per_var=[2, 7])), RandomSamplerSolver(RandomSamplerSolver.Params(n_samples_per_param=30)), ], ) def test_solve_without_input_parameters( self, inner_solver: SOSolver, simple_problem: MOProblem ) -> None: """solve a dummy minimization problem with 2 objectives and 1 constraint""" ws_pairs = np.array([[0.3, 0.7], [0.6, 0.4]]) simple_problem.input_parameters = None ws_algo = WeightedSum( WeightedSum.Params( so_solver=inner_solver, ws_pairs=ws_pairs, ) ) po_objs, po_vars = ws_algo.solve(problem=simple_problem, seed=0) np.testing.assert_array_almost_equal(po_objs, np.array([[0, 0.2]])) np.testing.assert_equal(po_vars, np.array({"v1": 0, "v2": 2})) @pytest.mark.parametrize( "inner_solver", [ GridSearchSolver(GridSearchSolver.Params(n_grids_per_var=[2, 7])), RandomSamplerSolver(RandomSamplerSolver.Params(n_samples_per_param=30)), ], ) def test_solve_with_input_parameters( self, inner_solver: SOSolver, simple_problem: MOProblem ) -> None: """solve a dummy minimization problem with 2 objectives and 1 constraint""" ws_pairs = np.array([[0.3, 0.7], [0.6, 0.4]]) ws_algo = WeightedSum( WeightedSum.Params( so_solver=inner_solver, ws_pairs=ws_pairs, ) ) po_objs, po_vars = ws_algo.solve(problem=simple_problem, seed=0) np.testing.assert_almost_equal(po_objs, np.array([[1, 1.3]])) np.testing.assert_equal(po_vars, np.array([{"v1": 0, "v2": 3}])) @pytest.mark.parametrize( "inner_solver", [ GridSearchSolver(GridSearchSolver.Params(n_grids_per_var=[2, 7])), RandomSamplerSolver(RandomSamplerSolver.Params(n_samples_per_param=1000)), ], ) def test_solver_with_two_obj_problem( self, inner_solver: SOSolver, two_obj_problem: MOProblem ) -> None: ws_pairs = np.array( [ [0.3, 0.7], [0.6, 0.4], [0.1, 0.9], [0.2, 0.8], [0.4, 0.6], [0.5, 0.5], ] ) ws_algo = WeightedSum( WeightedSum.Params( so_solver=inner_solver, ws_pairs=ws_pairs, ) ) po_objs, po_vars = ws_algo.solve(problem=two_obj_problem, seed=0) np.testing.assert_almost_equal(po_objs, np.array([[0, 0]]), decimal=5) np.testing.assert_almost_equal(po_vars[0]["v1"], 0.0, decimal=3) assert po_vars[0]["v2"] == 1.0 @pytest.mark.parametrize( "strict_rounding", [ True, False, ], ) def test_solver_with_two_obj_problem_mogd( self, strict_rounding: bool, two_obj_problem: MOProblem ) -> None: inner_solver = MOGD( MOGD.Params( learning_rate=0.1, max_iters=100, patience=20, multistart=2, batch_size=10, strict_rounding=strict_rounding, ) )
class TestWeightedSum: @pytest.mark.parametrize( "inner_solver", [ GridSearchSolver(GridSearchSolver.Params(n_grids_per_var=[2, 7])), RandomSamplerSolver(RandomSamplerSolver.Params(n_samples_per_param=30)), ], ) def test_solve_without_input_parameters( self, inner_solver: SOSolver, simple_problem: MOProblem ) -> None: """solve a dummy minimization problem with 2 objectives and 1 constraint""" ws_pairs = np.array([[0.3, 0.7], [0.6, 0.4]]) simple_problem.input_parameters = None ws_algo = WeightedSum( WeightedSum.Params( so_solver=inner_solver, ws_pairs=ws_pairs, ) ) po_objs, po_vars = ws_algo.solve(problem=simple_problem, seed=0) np.testing.assert_array_almost_equal(po_objs, np.array([[0, 0.2]])) np.testing.assert_equal(po_vars, np.array({"v1": 0, "v2": 2})) @pytest.mark.parametrize( "inner_solver", [ GridSearchSolver(GridSearchSolver.Params(n_grids_per_var=[2, 7])), RandomSamplerSolver(RandomSamplerSolver.Params(n_samples_per_param=30)), ], ) def test_solve_with_input_parameters( self, inner_solver: SOSolver, simple_problem: MOProblem ) -> None: """solve a dummy minimization problem with 2 objectives and 1 constraint""" ws_pairs = np.array([[0.3, 0.7], [0.6, 0.4]]) ws_algo = WeightedSum( WeightedSum.Params( so_solver=inner_solver, ws_pairs=ws_pairs, ) ) po_objs, po_vars = ws_algo.solve(problem=simple_problem, seed=0) np.testing.assert_almost_equal(po_objs, np.array([[1, 1.3]])) np.testing.assert_equal(po_vars, np.array([{"v1": 0, "v2": 3}])) @pytest.mark.parametrize( "inner_solver", [ GridSearchSolver(GridSearchSolver.Params(n_grids_per_var=[2, 7])), RandomSamplerSolver(RandomSamplerSolver.Params(n_samples_per_param=1000)), ], ) def test_solver_with_two_obj_problem( self, inner_solver: SOSolver, two_obj_problem: MOProblem ) -> None: ws_pairs = np.array( [ [0.3, 0.7], [0.6, 0.4], [0.1, 0.9], [0.2, 0.8], [0.4, 0.6], [0.5, 0.5], ] ) ws_algo = WeightedSum( WeightedSum.Params( so_solver=inner_solver, ws_pairs=ws_pairs, ) ) po_objs, po_vars = ws_algo.solve(problem=two_obj_problem, seed=0) np.testing.assert_almost_equal(po_objs, np.array([[0, 0]]), decimal=5) np.testing.assert_almost_equal(po_vars[0]["v1"], 0.0, decimal=3) assert po_vars[0]["v2"] == 1.0 @pytest.mark.parametrize( "strict_rounding", [ True, False, ], ) def test_solver_with_two_obj_problem_mogd( self, strict_rounding: bool, two_obj_problem: MOProblem ) -> None: inner_solver = MOGD( MOGD.Params( learning_rate=0.1, max_iters=100, patience=20, multistart=2, batch_size=10, strict_rounding=strict_rounding, ) )
ws_pairs = even_weights(0.1, 2)
10
2023-12-20 09:10:42+00:00
16k
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,809
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')
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')
visualize_image(show_img, show=True, fig_path='/xlearning/pengxin/Temp/MissingRec.svg')
6
2023-12-21 08:50:36+00:00
16k
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, )
11,400
def characters_popularity_compare( language: str, ordered_characters: List[str] ) -> float: """ Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) """ if language not in FREQUENCIES: raise ValueError("{} not available".format(language)) character_approved_count: int = 0 FREQUENCIES_language_set = set(FREQUENCIES[language]) ordered_characters_count: int = len(ordered_characters) target_language_characters_count: int = len(FREQUENCIES[language]) large_alphabet: bool = target_language_characters_count > 26 for character, character_rank in zip( ordered_characters, range(0, ordered_characters_count) ): if character not in FREQUENCIES_language_set: continue character_rank_in_language: int = FREQUENCIES[language].index(character) expected_projection_ratio: float = ( target_language_characters_count / ordered_characters_count ) character_rank_projection: int = int(character_rank * expected_projection_ratio) if ( large_alphabet is False and abs(character_rank_projection - character_rank_in_language) > 4 ): continue if ( large_alphabet is True and abs(character_rank_projection - character_rank_in_language) < target_language_characters_count / 3 ): character_approved_count += 1 continue characters_before_source: List[str] = FREQUENCIES[language][ 0:character_rank_in_language ] characters_after_source: List[str] = FREQUENCIES[language][ character_rank_in_language: ] characters_before: List[str] = ordered_characters[0:character_rank] characters_after: List[str] = ordered_characters[character_rank:] before_match_count: int = len( set(characters_before) & set(characters_before_source) ) after_match_count: int = len( set(characters_after) & set(characters_after_source) ) if len(characters_before_source) == 0 and before_match_count <= 4: character_approved_count += 1 continue if len(characters_after_source) == 0 and after_match_count <= 4: character_approved_count += 1 continue if ( before_match_count / len(characters_before_source) >= 0.4 or after_match_count / len(characters_after_source) >= 0.4 ): character_approved_count += 1 continue return character_approved_count / len(ordered_characters) def alpha_unicode_split(decoded_sequence: str) -> List[str]: """ Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; One containing the latin letters and the other hebrew. """ layers: Dict[str, str] = {} for character in decoded_sequence: if character.isalpha() is False: continue character_range: Optional[str] = unicode_range(character) if character_range is None: continue layer_target_range: Optional[str] = None for discovered_range in layers: if ( is_suspiciously_successive_range(discovered_range, character_range) is False ): layer_target_range = discovered_range break if layer_target_range is None: layer_target_range = character_range if layer_target_range not in layers: layers[layer_target_range] = character.lower() continue layers[layer_target_range] += character.lower() return list(layers.values())
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: target_pure_latin = False return target_have_accents, target_pure_latin def alphabet_languages( characters: List[str], ignore_non_latin: bool = False ) -> List[str]: """ Return associated languages associated to given characters. """ languages: List[Tuple[str, float]] = [] source_have_accents = any(is_accentuated(character) for character in characters) for language, language_characters in FREQUENCIES.items(): target_have_accents, target_pure_latin = get_target_features(language) if ignore_non_latin and target_pure_latin is False: continue if target_have_accents is False and source_have_accents: continue character_count: int = len(language_characters) character_match_count: int = len( [c for c in language_characters if c in characters] ) ratio: float = character_match_count / character_count if ratio >= 0.2: languages.append((language, ratio)) languages = sorted(languages, key=lambda x: x[1], reverse=True) return [compatible_language[0] for compatible_language in languages] def characters_popularity_compare( language: str, ordered_characters: List[str] ) -> float: """ Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) """ if language not in FREQUENCIES: raise ValueError("{} not available".format(language)) character_approved_count: int = 0 FREQUENCIES_language_set = set(FREQUENCIES[language]) ordered_characters_count: int = len(ordered_characters) target_language_characters_count: int = len(FREQUENCIES[language]) large_alphabet: bool = target_language_characters_count > 26 for character, character_rank in zip( ordered_characters, range(0, ordered_characters_count) ): if character not in FREQUENCIES_language_set: continue character_rank_in_language: int = FREQUENCIES[language].index(character) expected_projection_ratio: float = ( target_language_characters_count / ordered_characters_count ) character_rank_projection: int = int(character_rank * expected_projection_ratio) if ( large_alphabet is False and abs(character_rank_projection - character_rank_in_language) > 4 ): continue if ( large_alphabet is True and abs(character_rank_projection - character_rank_in_language) < target_language_characters_count / 3 ): character_approved_count += 1 continue characters_before_source: List[str] = FREQUENCIES[language][ 0:character_rank_in_language ] characters_after_source: List[str] = FREQUENCIES[language][ character_rank_in_language: ] characters_before: List[str] = ordered_characters[0:character_rank] characters_after: List[str] = ordered_characters[character_rank:] before_match_count: int = len( set(characters_before) & set(characters_before_source) ) after_match_count: int = len( set(characters_after) & set(characters_after_source) ) if len(characters_before_source) == 0 and before_match_count <= 4: character_approved_count += 1 continue if len(characters_after_source) == 0 and after_match_count <= 4: character_approved_count += 1 continue if ( before_match_count / len(characters_before_source) >= 0.4 or after_match_count / len(characters_after_source) >= 0.4 ): character_approved_count += 1 continue return character_approved_count / len(ordered_characters) def alpha_unicode_split(decoded_sequence: str) -> List[str]: """ Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; One containing the latin letters and the other hebrew. """ layers: Dict[str, str] = {} for character in decoded_sequence: if character.isalpha() is False: continue character_range: Optional[str] = unicode_range(character) if character_range is None: continue layer_target_range: Optional[str] = None for discovered_range in layers: if ( is_suspiciously_successive_range(discovered_range, character_range) is False ): layer_target_range = discovered_range break if layer_target_range is None: layer_target_range = character_range if layer_target_range not in layers: layers[layer_target_range] = character.lower() continue layers[layer_target_range] += character.lower() return list(layers.values())
def merge_coherence_ratios(results: List[CoherenceMatches]) -> CoherenceMatches:
6
2023-12-16 04:12:01+00:00
16k
YaoFANGUK/video-subtitle-remover
backend/scenedetect/scene_manager.py
[ { "identifier": "SimpleTableCell", "path": "backend/scenedetect/_thirdparty/simpletable.py", "snippet": "class SimpleTableCell(object):\n \"\"\"A table class to create table cells.\n\n Example:\n cell = SimpleTableCell('Hello, world!')\n \"\"\"\n\n def __init__(self, text, header=False):\...
import csv import threading import queue import logging import math import sys import cv2 import numpy as np from enum import Enum from typing import Iterable, List, Tuple, Optional, Dict, Callable, Union, TextIO from backend.scenedetect._thirdparty.simpletable import (SimpleTableCell, SimpleTableImage, SimpleTableRow, SimpleTable, HTMLPage) from backend.scenedetect.platform import (tqdm, get_and_create_path, get_cv2_imwrite_params, Template) from backend.scenedetect.frame_timecode import FrameTimecode from backend.scenedetect.video_stream import VideoStream from backend.scenedetect.scene_detector import SceneDetector, SparseSceneDetector from backend.scenedetect.stats_manager import StatsManager, FrameMetricRegistered
14,375
csv_writer = csv.writer(output_csv_file, lineterminator='\n') # If required, output the cutting list as the first row (i.e. before the header row). if include_cut_list: csv_writer.writerow( ["Timecode List:"] + cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]]) csv_writer.writerow([ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ]) for i, (start, end) in enumerate(scene_list): duration = end - start csv_writer.writerow([ '%d' % (i + 1), '%d' % (start.get_frames() + 1), start.get_timecode(), '%.3f' % start.get_seconds(), '%d' % end.get_frames(), end.get_timecode(), '%.3f' % end.get_seconds(), '%d' % duration.get_frames(), duration.get_timecode(), '%.3f' % duration.get_seconds() ]) def write_scene_list_html(output_html_filename, scene_list, cut_list=None, css=None, css_class='mytable', image_filenames=None, image_width=None, image_height=None): """Writes the given list of scenes to an output file handle in html format. Arguments: output_html_filename: filename of output html file scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not passed, the start times of each scene (besides the 0th scene) is used instead. css: String containing all the css information for the resulting html page. css_class: String containing the named css class image_filenames: dict where key i contains a list with n elements (filenames of the n saved images from that scene) image_width: Optional desired width of images in table in pixels image_height: Optional desired height of images in table in pixels """ if not css: css = """ table.mytable { font-family: times; font-size:12px; color:#000000; border-width: 1px; border-color: #eeeeee; border-collapse: collapse; background-color: #ffffff; width=100%; max-width:550px; table-layout:fixed; } table.mytable th { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; background-color: #e6eed6; color:#000000; } table.mytable td { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; } #code { display:inline; font-family: courier; color: #3d9400; } #string { display:inline; font-weight: bold; } """ # Output Timecode list timecode_table = SimpleTable( [["Timecode List:"] + (cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]])], css_class=css_class) # Output list of scenes header_row = [ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ] for i, (start, end) in enumerate(scene_list): duration = end - start row = SimpleTableRow([ '%d' % (i + 1), '%d' % (start.get_frames() + 1), start.get_timecode(), '%.3f' % start.get_seconds(), '%d' % end.get_frames(), end.get_timecode(), '%.3f' % end.get_seconds(), '%d' % duration.get_frames(), duration.get_timecode(), '%.3f' % duration.get_seconds() ]) if image_filenames: for image in image_filenames[i]: row.add_cell(
# -*- 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. # """``scenedetect.scene_manager`` Module This module implements :class:`SceneManager`, coordinates running a :mod:`SceneDetector <scenedetect.detectors>` over the frames of a video (:mod:`VideoStream <scenedetect.video_stream>`). Video decoding is done in a separate thread to improve performance. This module also contains other helper functions (e.g. :func:`save_images`) which can be used to process the resulting scene list. =============================================================== Usage =============================================================== The following example shows basic usage of a :class:`SceneManager`: .. code:: python from scenedetect import open_video, SceneManager, ContentDetector video = open_video(video_path) scene_manager = SceneManager() scene_manager.add_detector(ContentDetector()) # Detect all scenes in video from current position to end. scene_manager.detect_scenes(video) # `get_scene_list` returns a list of start/end timecode pairs # for each scene that was found. scenes = scene_manager.get_scene_list() An optional callback can also be invoked on each detected scene, for example: .. code:: python from scenedetect import open_video, SceneManager, ContentDetector # Callback to invoke on the first frame of every new scene detection. def on_new_scene(frame_img: numpy.ndarray, frame_num: int): print("New scene found at frame %d." % frame_num) video = open_video(test_video_file) scene_manager = SceneManager() scene_manager.add_detector(ContentDetector()) scene_manager.detect_scenes(video=video, callback=on_new_scene) To use a `SceneManager` with a webcam/device or existing `cv2.VideoCapture` device, use the :class:`VideoCaptureAdapter <scenedetect.backends.opencv.VideoCaptureAdapter>` instead of `open_video`. ======================================================================= Storing Per-Frame Statistics ======================================================================= `SceneManager` can use an optional :class:`StatsManager <scenedetect.stats_manager.StatsManager>` to save frame statistics to disk: .. code:: python from scenedetect import open_video, ContentDetector, SceneManager, StatsManager video = open_video(test_video_file) scene_manager = SceneManager(stats_manager=StatsManager()) scene_manager.add_detector(ContentDetector()) scene_manager.detect_scenes(video=video) scene_list = scene_manager.get_scene_list() print_scenes(scene_list=scene_list) # Save per-frame statistics to disk. scene_manager.stats_manager.save_to_csv(csv_file=STATS_FILE_PATH) The statsfile can be used to find a better threshold for certain inputs, or perform statistical analysis of the video. """ logger = logging.getLogger('pyscenedetect') # TODO: This value can and should be tuned for performance improvements as much as possible, # until accuracy falls, on a large enough dataset. This has yet to be done, but the current # value doesn't seem to have caused any issues at least. DEFAULT_MIN_WIDTH: int = 256 """The default minimum width a frame will be downscaled to when calculating a downscale factor.""" MAX_FRAME_QUEUE_LENGTH: int = 4 """Maximum number of decoded frames which can be buffered while waiting to be processed.""" PROGRESS_BAR_DESCRIPTION = 'Detected: %d | Progress' """Template to use for progress bar.""" class Interpolation(Enum): """Interpolation method used for image resizing. Based on constants defined in OpenCV.""" NEAREST = cv2.INTER_NEAREST """Nearest neighbor interpolation.""" LINEAR = cv2.INTER_LINEAR """Bilinear interpolation.""" CUBIC = cv2.INTER_CUBIC """Bicubic interpolation.""" AREA = cv2.INTER_AREA """Pixel area relation resampling. Provides moire'-free downscaling.""" LANCZOS4 = cv2.INTER_LANCZOS4 """Lanczos interpolation over 8x8 neighborhood.""" def compute_downscale_factor(frame_width: int, effective_width: int = DEFAULT_MIN_WIDTH) -> int: """Get the optimal default downscale factor based on a video's resolution (currently only the width in pixels is considered). The resulting effective width of the video will be between frame_width and 1.5 * frame_width pixels (e.g. if frame_width is 200, the range of effective widths will be between 200 and 300). Arguments: frame_width: Actual width of the video frame in pixels. effective_width: Desired minimum width in pixels. Returns: int: The default downscale factor to use to achieve at least the target effective_width. """ assert not (frame_width < 1 or effective_width < 1) if frame_width < effective_width: return 1 return frame_width // effective_width def get_scenes_from_cuts( cut_list: Iterable[FrameTimecode], start_pos: Union[int, FrameTimecode], end_pos: Union[int, FrameTimecode], base_timecode: Optional[FrameTimecode] = None, ) -> List[Tuple[FrameTimecode, FrameTimecode]]: """Returns a list of tuples of start/end FrameTimecodes for each scene based on a list of detected scene cuts/breaks. This function is called when using the :meth:`SceneManager.get_scene_list` method. The scene list is generated from a cutting list (:meth:`SceneManager.get_cut_list`), noting that each scene is contiguous, starting from the first to last frame of the input. If `cut_list` is empty, the resulting scene will span from `start_pos` to `end_pos`. Arguments: cut_list: List of FrameTimecode objects where scene cuts/breaks occur. base_timecode: The base_timecode of which all FrameTimecodes in the cut_list are based on. num_frames: The number of frames, or FrameTimecode representing duration, of the video that was processed (used to generate last scene's end time). start_frame: The start frame or FrameTimecode of the cut list. Used to generate the first scene's start time. base_timecode: [DEPRECATED] DO NOT USE. For backwards compatibility only. Returns: List of tuples in the form (start_time, end_time), where both start_time and end_time are FrameTimecode objects representing the exact time/frame where each scene occupies based on the input cut_list. """ # TODO(v0.7): Use the warnings module to turn this into a warning. if base_timecode is not None: logger.error('`base_timecode` argument is deprecated has no effect.') # Scene list, where scenes are tuples of (Start FrameTimecode, End FrameTimecode). scene_list = [] if not cut_list: scene_list.append((start_pos, end_pos)) return scene_list # Initialize last_cut to the first frame we processed,as it will be # the start timecode for the first scene in the list. last_cut = start_pos for cut in cut_list: scene_list.append((last_cut, cut)) last_cut = cut # Last scene is from last cut to end of video. scene_list.append((last_cut, end_pos)) return scene_list def write_scene_list(output_csv_file: TextIO, scene_list: Iterable[Tuple[FrameTimecode, FrameTimecode]], include_cut_list: bool = True, cut_list: Optional[Iterable[FrameTimecode]] = None) -> None: """Writes the given list of scenes to an output file handle in CSV format. Arguments: output_csv_file: Handle to open file in write mode. scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. include_cut_list: Bool indicating if the first row should include the timecodes where each scene starts. Should be set to False if RFC 4180 compliant CSV output is required. cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not specified, the cut list is generated using the start times of each scene following the first one. """ csv_writer = csv.writer(output_csv_file, lineterminator='\n') # If required, output the cutting list as the first row (i.e. before the header row). if include_cut_list: csv_writer.writerow( ["Timecode List:"] + cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]]) csv_writer.writerow([ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ]) for i, (start, end) in enumerate(scene_list): duration = end - start csv_writer.writerow([ '%d' % (i + 1), '%d' % (start.get_frames() + 1), start.get_timecode(), '%.3f' % start.get_seconds(), '%d' % end.get_frames(), end.get_timecode(), '%.3f' % end.get_seconds(), '%d' % duration.get_frames(), duration.get_timecode(), '%.3f' % duration.get_seconds() ]) def write_scene_list_html(output_html_filename, scene_list, cut_list=None, css=None, css_class='mytable', image_filenames=None, image_width=None, image_height=None): """Writes the given list of scenes to an output file handle in html format. Arguments: output_html_filename: filename of output html file scene_list: List of pairs of FrameTimecodes denoting each scene's start/end FrameTimecode. cut_list: Optional list of FrameTimecode objects denoting the cut list (i.e. the frames in the video that need to be split to generate individual scenes). If not passed, the start times of each scene (besides the 0th scene) is used instead. css: String containing all the css information for the resulting html page. css_class: String containing the named css class image_filenames: dict where key i contains a list with n elements (filenames of the n saved images from that scene) image_width: Optional desired width of images in table in pixels image_height: Optional desired height of images in table in pixels """ if not css: css = """ table.mytable { font-family: times; font-size:12px; color:#000000; border-width: 1px; border-color: #eeeeee; border-collapse: collapse; background-color: #ffffff; width=100%; max-width:550px; table-layout:fixed; } table.mytable th { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; background-color: #e6eed6; color:#000000; } table.mytable td { border-width: 1px; padding: 8px; border-style: solid; border-color: #eeeeee; } #code { display:inline; font-family: courier; color: #3d9400; } #string { display:inline; font-weight: bold; } """ # Output Timecode list timecode_table = SimpleTable( [["Timecode List:"] + (cut_list if cut_list else [start.get_timecode() for start, _ in scene_list[1:]])], css_class=css_class) # Output list of scenes header_row = [ "Scene Number", "Start Frame", "Start Timecode", "Start Time (seconds)", "End Frame", "End Timecode", "End Time (seconds)", "Length (frames)", "Length (timecode)", "Length (seconds)" ] for i, (start, end) in enumerate(scene_list): duration = end - start row = SimpleTableRow([ '%d' % (i + 1), '%d' % (start.get_frames() + 1), start.get_timecode(), '%.3f' % start.get_seconds(), '%d' % end.get_frames(), end.get_timecode(), '%.3f' % end.get_seconds(), '%d' % duration.get_frames(), duration.get_timecode(), '%.3f' % duration.get_seconds() ]) if image_filenames: for image in image_filenames[i]: row.add_cell(
SimpleTableCell(
0
2023-10-25 02:50:01+00:00
16k
EulerSearch/embedding_studio
embedding_studio/workers/fine_tuning/finetune_embedding_one_param.py
[ { "identifier": "QueryRetriever", "path": "embedding_studio/embeddings/data/clickstream/query_retriever.py", "snippet": "class QueryRetriever(object):\n \"\"\"As we can't exactly predict a schema of storing queries:\n 1. As text exceptly in clickstream service\n 2. As ID of a record with a text...
import logging import torch from typing import Optional from pytorch_lightning import Trainer from pytorch_lightning.callbacks import EarlyStopping from torch.utils.data import DataLoader from embedding_studio.embeddings.data.clickstream.query_retriever import ( QueryRetriever, ) from embedding_studio.embeddings.data.ranking_data import RankingData from embedding_studio.embeddings.models.interface import ( EmbeddingsModelInterface, ) from embedding_studio.embeddings.training.embeddings_finetuner import ( EmbeddingsFineTuner, ) from embedding_studio.workers.fine_tuning.experiments.experiments_tracker import ( ExperimentsManager, ) from embedding_studio.workers.fine_tuning.experiments.finetuning_params import ( FineTuningParams, ) from embedding_studio.workers.fine_tuning.experiments.finetuning_settings import ( FineTuningSettings, )
11,796
logger = logging.getLogger(__name__) class CustomDataCollator: def __call__(self, batch): return batch def fine_tune_embedding_model_one_param( initial_model: EmbeddingsModelInterface, settings: FineTuningSettings, ranking_data: RankingData,
logger = logging.getLogger(__name__) class CustomDataCollator: def __call__(self, batch): return batch def fine_tune_embedding_model_one_param( initial_model: EmbeddingsModelInterface, settings: FineTuningSettings, ranking_data: RankingData,
query_retriever: QueryRetriever,
0
2023-10-31 00:33:13+00:00
16k
masked-spacetime-hashing/msth
dataparser.py
[ { "identifier": "camera_utils", "path": "nerfstudio/cameras/camera_utils.py", "snippet": "_EPS = np.finfo(float).eps * 4.0\n M = np.array(matrix, dtype=np.float64, copy=False)[:4, :4]\n K = np.array(\n [\n [m00 - m11 - m22, 0.0, 0.0, 0.0],\n [m01 + m10,...
import json import math import os import cv2 import numpy as np import torch from copy import deepcopy from dataclasses import dataclass, field from pathlib import Path, PurePath from typing import List, Optional, Type from typing import * from PIL import Image from rich.console import Console from typing_extensions import Literal from nerfstudio.cameras import camera_utils from nerfstudio.cameras.cameras import CAMERA_MODEL_TO_TYPE, Cameras, CameraType from nerfstudio.configs.config_utils import to_immutable_dict from nerfstudio.data.dataparsers.base_dataparser import ( DataParser, DataParserConfig, DataparserOutputs, ) from nerfstudio.data.scene_box import SceneBox from nerfstudio.utils.io import load_from_json from torchtyping import TensorType
12,904
from __future__ import annotations CONSOLE = Console(width=120) MAX_AUTO_RESOLUTION = 1600 @dataclass class VideoDataParserOutputs: data_dir: Path video_filenames: List[Path] start_frame: int num_frames: int """Dataparser outputs for the which will be used by the DataManager for creating RayBundle and RayGT objects.""" """Filenames for the images."""
from __future__ import annotations CONSOLE = Console(width=120) MAX_AUTO_RESOLUTION = 1600 @dataclass class VideoDataParserOutputs: data_dir: Path video_filenames: List[Path] start_frame: int num_frames: int """Dataparser outputs for the which will be used by the DataManager for creating RayBundle and RayGT objects.""" """Filenames for the images."""
cameras: Cameras
2
2023-10-26 04:39:15+00:00
16k
Trustworthy-AI-Group/TransferAttack
transferattack/model_related/ghost.py
[ { "identifier": "Attack", "path": "transferattack/attack.py", "snippet": "class Attack(object):\n \"\"\"\n Base class for all attacks.\n \"\"\"\n def __init__(self, attack, model_name, epsilon, targeted, random_start, norm, loss, device=None):\n \"\"\"\n Initialize the hyperpar...
from ..utils import * from ..attack import Attack from .ghost_networks.resnet import ghost_resnet101, ghost_resnet152 from ..gradient.mifgsm import MIFGSM from ..gradient.nifgsm import NIFGSM from ..gradient.vmifgsm import VMIFGSM from ..input_transformation.dim import DIM from ..input_transformation.tim import TIM from ..input_transformation.sim import SIM from ..input_transformation.admix import Admix from torch import Tensor from ..utils import * from ..gradient.mifgsm import MIFGSM from ..gradient.nifgsm import NIFGSM from ..input_transformation.dim import DIM from ..input_transformation.tim import TIM from ..input_transformation.sim import SIM from ..input_transformation.admix import Admix
11,180
# example bash: python main.py --attack=ghost_network support_models = { "resnet101": ghost_resnet101, "resnet152": ghost_resnet152, } class GhostNetwork_MIFGSM(MIFGSM): """ Ghost Network Attack: Arguments: model (str): the surrogate model for attack. ghost_keep_prob (float): the dropout rate when generating ghost networks. ghost_random_range (float): the dropout rate when generating ghost networks of residual structure. """ def __init__(self, model_name='inc_v3', ghost_keep_prob=0.994, ghost_random_range=0.16, *args, **kwargs): self.ghost_keep_prob = ghost_keep_prob # do not use self.ghost_random_range = ghost_random_range # do not use super().__init__(model_name, *args, **kwargs) def load_model(self, model_name): if model_name in support_models.keys(): # The ghost_keep_prob and ghost_random_range are correctly set as param default value, # in the __init__ function of each GhostNetwork. model = wrap_model(support_models[model_name](weights='DEFAULT').eval().cuda()) else: raise ValueError('Model {} not supported for GhostNetwork'.format(model_name)) return model class GhostNetwork_IFGSM(MIFGSM): """ Ghost Network Attack: Arguments: model (str): the surrogate model for attack. ghost_keep_prob (float): the dropout rate when generating ghost networks. ghost_random_range (float): the dropout rate when generating ghost networks of residual structure. """ def __init__(self, model_name='inc_v3', ghost_keep_prob=0.994, ghost_random_range=0.16, *args, **kwargs): self.ghost_keep_prob = ghost_keep_prob # do not use self.ghost_random_range = ghost_random_range # do not use super().__init__(model_name, *args, **kwargs) self.decay = 0. def load_model(self, model_name): if model_name in support_models.keys(): # The ghost_keep_prob and ghost_random_range are correctly set as param default value, # in the __init__ function of each GhostNetwork. model = wrap_model(support_models[model_name](weights='DEFAULT').eval().cuda()) else: raise ValueError('Model {} not supported for GhostNetwork'.format(model_name)) return model
# example bash: python main.py --attack=ghost_network support_models = { "resnet101": ghost_resnet101, "resnet152": ghost_resnet152, } class GhostNetwork_MIFGSM(MIFGSM): """ Ghost Network Attack: Arguments: model (str): the surrogate model for attack. ghost_keep_prob (float): the dropout rate when generating ghost networks. ghost_random_range (float): the dropout rate when generating ghost networks of residual structure. """ def __init__(self, model_name='inc_v3', ghost_keep_prob=0.994, ghost_random_range=0.16, *args, **kwargs): self.ghost_keep_prob = ghost_keep_prob # do not use self.ghost_random_range = ghost_random_range # do not use super().__init__(model_name, *args, **kwargs) def load_model(self, model_name): if model_name in support_models.keys(): # The ghost_keep_prob and ghost_random_range are correctly set as param default value, # in the __init__ function of each GhostNetwork. model = wrap_model(support_models[model_name](weights='DEFAULT').eval().cuda()) else: raise ValueError('Model {} not supported for GhostNetwork'.format(model_name)) return model class GhostNetwork_IFGSM(MIFGSM): """ Ghost Network Attack: Arguments: model (str): the surrogate model for attack. ghost_keep_prob (float): the dropout rate when generating ghost networks. ghost_random_range (float): the dropout rate when generating ghost networks of residual structure. """ def __init__(self, model_name='inc_v3', ghost_keep_prob=0.994, ghost_random_range=0.16, *args, **kwargs): self.ghost_keep_prob = ghost_keep_prob # do not use self.ghost_random_range = ghost_random_range # do not use super().__init__(model_name, *args, **kwargs) self.decay = 0. def load_model(self, model_name): if model_name in support_models.keys(): # The ghost_keep_prob and ghost_random_range are correctly set as param default value, # in the __init__ function of each GhostNetwork. model = wrap_model(support_models[model_name](weights='DEFAULT').eval().cuda()) else: raise ValueError('Model {} not supported for GhostNetwork'.format(model_name)) return model
class GhostNetwork_NIFGSM(NIFGSM):
11
2023-10-31 03:43:26+00:00
16k
chenruduan/OAReactDiff
demo.py
[ { "identifier": "LEFTNet", "path": "oa_reactdiff/model/leftnet.py", "snippet": "class LEFTNet(torch.nn.Module):\n r\"\"\"\n LEFTNet\n\n Args:\n pos_require_grad (bool, optional): If set to :obj:`True`, will require to take derivative of model output with respect to the atomic positions. ...
import torch import py3Dmol import numpy as np import plotly.express as px import json from typing import Optional from torch import tensor from e3nn import o3 from torch_scatter import scatter_mean from oa_reactdiff.model import LEFTNet from oa_reactdiff.tests.model.utils import ( generate_full_eij, get_cut_graph_mask, ) from torch.utils.data import DataLoader from oa_reactdiff.trainer.pl_trainer import DDPMModule from oa_reactdiff.dataset import ProcessedTS1x from oa_reactdiff.diffusion._schedule import DiffSchedule, PredefinedNoiseSchedule from oa_reactdiff.diffusion._normalizer import FEATURE_MAPPING from oa_reactdiff.analyze.rmsd import batch_rmsd from oa_reactdiff.utils.sampling_tools import ( assemble_sample_inputs, write_tmp_xyz, ) from glob import glob from oa_reactdiff.analyze.rmsd import xyz2pmg, pymatgen_rmsd from pymatgen.core import Molecule from collections import OrderedDict from sklearn.cluster import KMeans from glob import glob from pymatgen.io.xyz import XYZ from openbabel import pybel from oa_reactdiff.analyze.rmsd import pymatgen_rmsd
11,579
# --- 导入和定义一些函数 ---- default_float = torch.float64 torch.set_default_dtype(default_float) # 使用双精度,测试更准确 def remove_mean_batch( x: tensor, indices: Optional[tensor] = None ) -> tensor: """将x中的每个batch的均值去掉 Args: x (tensor): input tensor. indices (Optional[tensor], optional): batch indices. Defaults to None. Returns: tensor: output tensor with batch mean as 0. """ if indices == None: return x - torch.mean(x, dim=0) mean = scatter_mean(x, indices, dim=0) x = x - mean[indices] return x def draw_in_3dmol(mol: str, fmt: str = "xyz") -> py3Dmol.view: """画分子 Args: mol (str): str content of molecule. fmt (str, optional): format. Defaults to "xyz". Returns: py3Dmol.view: output viewer """ viewer = py3Dmol.view(1024, 576) viewer.addModel(mol, fmt) viewer.setStyle({'stick': {}, "sphere": {"radius": 0.36}}) viewer.zoomTo() return viewer def assemble_xyz(z: list, pos: tensor) -> str: """将原子序数和位置组装成xyz格式 Args: z (list): chemical elements pos (tensor): 3D coordinates Returns: str: xyz string """ natoms =len(z) xyz = f"{natoms}\n\n" for _z, _pos in zip(z, pos.numpy()): xyz += f"{_z}\t" + "\t".join([str(x) for x in _pos]) + "\n" return xyz num_layers = 2 hidden_channels = 8 in_hidden_channels = 4 num_radial = 4
# --- 导入和定义一些函数 ---- default_float = torch.float64 torch.set_default_dtype(default_float) # 使用双精度,测试更准确 def remove_mean_batch( x: tensor, indices: Optional[tensor] = None ) -> tensor: """将x中的每个batch的均值去掉 Args: x (tensor): input tensor. indices (Optional[tensor], optional): batch indices. Defaults to None. Returns: tensor: output tensor with batch mean as 0. """ if indices == None: return x - torch.mean(x, dim=0) mean = scatter_mean(x, indices, dim=0) x = x - mean[indices] return x def draw_in_3dmol(mol: str, fmt: str = "xyz") -> py3Dmol.view: """画分子 Args: mol (str): str content of molecule. fmt (str, optional): format. Defaults to "xyz". Returns: py3Dmol.view: output viewer """ viewer = py3Dmol.view(1024, 576) viewer.addModel(mol, fmt) viewer.setStyle({'stick': {}, "sphere": {"radius": 0.36}}) viewer.zoomTo() return viewer def assemble_xyz(z: list, pos: tensor) -> str: """将原子序数和位置组装成xyz格式 Args: z (list): chemical elements pos (tensor): 3D coordinates Returns: str: xyz string """ natoms =len(z) xyz = f"{natoms}\n\n" for _z, _pos in zip(z, pos.numpy()): xyz += f"{_z}\t" + "\t".join([str(x) for x in _pos]) + "\n" return xyz num_layers = 2 hidden_channels = 8 in_hidden_channels = 4 num_radial = 4
model = LEFTNet(
0
2023-10-30 02:53:38+00:00
16k
Weitheskmt/WeiDMD
build/lib/weidmd/cdmd.py
[ { "identifier": "DMDBase", "path": "build/lib/weidmd/dmdbase.py", "snippet": "class DMDBase:\n \"\"\"\n Dynamic Mode Decomposition base class.\n\n :param svd_rank: the rank for the truncation; If 0, the method computes the\n optimal rank and uses it for truncation; if positive interger, ...
import numpy as np import scipy.sparse from scipy.linalg import sqrtm from .dmdbase import DMDBase from .dmdoperator import DMDOperator from .snapshots import Snapshots from .utils import compute_svd, compute_tlsq
10,856
from __future__ import division class CDMDOperator(DMDOperator): """ DMD operator for Compressed-DMD. :param svd_rank: the rank for the truncation; If 0, the method computes the optimal rank and uses it for truncation; if positive interger, the method uses the argument for the truncation; if float between 0 and 1, the rank is the number of the biggest singular values that are needed to reach the 'energy' specified by `svd_rank`; if -1, the method does not compute truncation. :type svd_rank: int or float :param rescale_mode: Scale Atilde as shown in 10.1016/j.jneumeth.2015.10.010 (section 2.4) before computing its eigendecomposition. None means no rescaling, 'auto' means automatic rescaling using singular values, otherwise the scaling factors. :type rescale_mode: {'auto'} or None or numpy.ndarray :param bool forward_backward: If True, the low-rank operator is computed like in fbDMD (reference: https://arxiv.org/abs/1507.02264). Default is False. :param sorted_eigs: Sort eigenvalues (and modes/dynamics accordingly) by magnitude if `sorted_eigs='abs'`, by real part (and then by imaginary part to break ties) if `sorted_eigs='real'`. Default: False. :type sorted_eigs: {'real', 'abs'} or False :param tikhonov_regularization: Tikhonov parameter for the regularization. If `None`, no regularization is applied, if `float`, it is used as the :math:`\lambda` tikhonov parameter. :type tikhonov_regularization: int or float """ def __init__( self, svd_rank, rescale_mode, forward_backward, sorted_eigs, tikhonov_regularization, ): super().__init__( svd_rank=svd_rank, exact=True, rescale_mode=rescale_mode, forward_backward=forward_backward, sorted_eigs=sorted_eigs, tikhonov_regularization=tikhonov_regularization, ) self._Atilde = None def compute_operator(self, compressedX, compressedY, nonCompressedY): """ Compute the low-rank operator. :param numpy.ndarray compressedX: the compressed version of the matrix containing the snapshots x0,..x{n-1} by column. :param numpy.ndarray compressedY: the compressed version of the matrix containing the snapshots x1,..x{n} by column. :param numpy.ndarray nonCompressedY: the matrix containing the snapshots x1,..x{n} by column. :return: the (truncated) left-singular vectors matrix, the (truncated) singular values array, the (truncated) right-singular vectors matrix of compressedX. :rtype: numpy.ndarray, numpy.ndarray, numpy.ndarray """ U, s, V = compute_svd(compressedX, svd_rank=self._svd_rank) atilde = self._least_square_operator(U, s, V, compressedY) if self._forward_backward: # b stands for "backward" bU, bs, bV = compute_svd(compressedY, svd_rank=self._svd_rank) atilde_back = self._least_square_operator(bU, bs, bV, compressedX) atilde = sqrtm(atilde.dot(np.linalg.inv(atilde_back))) self._Atilde = atilde self._compute_eigenquantities() self._compute_modes(nonCompressedY, U, s, V) return U, s, V
from __future__ import division class CDMDOperator(DMDOperator): """ DMD operator for Compressed-DMD. :param svd_rank: the rank for the truncation; If 0, the method computes the optimal rank and uses it for truncation; if positive interger, the method uses the argument for the truncation; if float between 0 and 1, the rank is the number of the biggest singular values that are needed to reach the 'energy' specified by `svd_rank`; if -1, the method does not compute truncation. :type svd_rank: int or float :param rescale_mode: Scale Atilde as shown in 10.1016/j.jneumeth.2015.10.010 (section 2.4) before computing its eigendecomposition. None means no rescaling, 'auto' means automatic rescaling using singular values, otherwise the scaling factors. :type rescale_mode: {'auto'} or None or numpy.ndarray :param bool forward_backward: If True, the low-rank operator is computed like in fbDMD (reference: https://arxiv.org/abs/1507.02264). Default is False. :param sorted_eigs: Sort eigenvalues (and modes/dynamics accordingly) by magnitude if `sorted_eigs='abs'`, by real part (and then by imaginary part to break ties) if `sorted_eigs='real'`. Default: False. :type sorted_eigs: {'real', 'abs'} or False :param tikhonov_regularization: Tikhonov parameter for the regularization. If `None`, no regularization is applied, if `float`, it is used as the :math:`\lambda` tikhonov parameter. :type tikhonov_regularization: int or float """ def __init__( self, svd_rank, rescale_mode, forward_backward, sorted_eigs, tikhonov_regularization, ): super().__init__( svd_rank=svd_rank, exact=True, rescale_mode=rescale_mode, forward_backward=forward_backward, sorted_eigs=sorted_eigs, tikhonov_regularization=tikhonov_regularization, ) self._Atilde = None def compute_operator(self, compressedX, compressedY, nonCompressedY): """ Compute the low-rank operator. :param numpy.ndarray compressedX: the compressed version of the matrix containing the snapshots x0,..x{n-1} by column. :param numpy.ndarray compressedY: the compressed version of the matrix containing the snapshots x1,..x{n} by column. :param numpy.ndarray nonCompressedY: the matrix containing the snapshots x1,..x{n} by column. :return: the (truncated) left-singular vectors matrix, the (truncated) singular values array, the (truncated) right-singular vectors matrix of compressedX. :rtype: numpy.ndarray, numpy.ndarray, numpy.ndarray """ U, s, V = compute_svd(compressedX, svd_rank=self._svd_rank) atilde = self._least_square_operator(U, s, V, compressedY) if self._forward_backward: # b stands for "backward" bU, bs, bV = compute_svd(compressedY, svd_rank=self._svd_rank) atilde_back = self._least_square_operator(bU, bs, bV, compressedX) atilde = sqrtm(atilde.dot(np.linalg.inv(atilde_back))) self._Atilde = atilde self._compute_eigenquantities() self._compute_modes(nonCompressedY, U, s, V) return U, s, V
class CDMD(DMDBase):
0
2023-10-30 12:37:40+00:00
16k
lewandofskee/DiAD
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 os import logging import timm 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 from scipy.ndimage import gaussian_filter from utils.util import cal_anomaly_map, log_local, create_logger from utils.eval_helper import dump, log_metrics, merge_together, performances
14,186
@torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] if self.make_it_fit: n_params = len([name for name, _ in itertools.chain(self.named_parameters(), self.named_buffers())]) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys:\n {missing}") if len(unexpected) > 0: print(f"\nUnexpected Keys:\n {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def predict_start_from_z_and_v(self, x_t, t, v): # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def predict_eps_from_z_and_v(self, x_t, t, v): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor self.make_it_fit = make_it_fit if reset_ema: assert exists(ckpt_path) if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) if reset_ema: assert self.use_ema print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.") self.model_ema = LitEma(self.model) if reset_num_ema_updates: print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ") assert self.use_ema self.model_ema.reset_num_updates() self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) else: self.register_buffer('logvar', logvar) self.ucg_training = ucg_training or dict() if self.ucg_training: self.ucg_prng = np.random.RandomState() def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) elif self.parameterization == "v": lvlb_weights = torch.ones_like(self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))) else: raise NotImplementedError("mu not supported") lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: print(f"{context}: Switched to EMA weights") try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) if context is not None: print(f"{context}: Restored training weights") @torch.no_grad() def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] if self.make_it_fit: n_params = len([name for name, _ in itertools.chain(self.named_parameters(), self.named_buffers())]) for name, param in tqdm( itertools.chain(self.named_parameters(), self.named_buffers()), desc="Fitting old weights to new weights", total=n_params ): if not name in sd: continue old_shape = sd[name].shape new_shape = param.shape assert len(old_shape) == len(new_shape) if len(new_shape) > 2: # we only modify first two axes assert new_shape[2:] == old_shape[2:] # assumes first axis corresponds to output dim if not new_shape == old_shape: new_param = param.clone() old_param = sd[name] if len(new_shape) == 1: for i in range(new_param.shape[0]): new_param[i] = old_param[i % old_shape[0]] elif len(new_shape) >= 2: for i in range(new_param.shape[0]): for j in range(new_param.shape[1]): new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]] n_used_old = torch.ones(old_shape[1]) for j in range(new_param.shape[1]): n_used_old[j % old_shape[1]] += 1 n_used_new = torch.zeros(new_shape[1]) for j in range(new_param.shape[1]): n_used_new[j] = n_used_old[j % old_shape[1]] n_used_new = n_used_new[None, :] while len(n_used_new.shape) < len(new_shape): n_used_new = n_used_new.unsqueeze(-1) new_param /= n_used_new sd[name] = new_param missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys:\n {missing}") if len(unexpected) > 0: print(f"\nUnexpected Keys:\n {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def predict_start_from_z_and_v(self, x_t, t, v): # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def predict_eps_from_z_and_v(self, x_t, t, v): return ( extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
noise = noise_like(x.shape, device, repeat_noise)
15
2023-10-30 14:21:09+00:00
16k
nv-tlabs/trace
tbsim/evaluation/env_builders.py
[ { "identifier": "UnifiedDataset", "path": "trajdata/src/trajdata/dataset.py", "snippet": "class UnifiedDataset(Dataset):\n # @profile\n def __init__(\n self,\n desired_data: List[str],\n scene_description_contains: Optional[List[str]] = None,\n centric: str = \"agent\",...
from collections import defaultdict from trajdata import UnifiedDataset from tbsim.configs.eval_config import EvaluationConfig from tbsim.configs.base import ExperimentConfig from tbsim.envs.env_trajdata import EnvUnifiedSimulation from tbsim.utils.config_utils import translate_pass_trajdata_cfg from tbsim.utils.trajdata_utils import TRAJDATA_AGENT_TYPE_MAP import tbsim.envs.env_metrics as EnvMetrics
13,174
class EnvironmentBuilder(object): """Builds an simulation environment for evaluation.""" def __init__(self, eval_config: EvaluationConfig, exp_config: ExperimentConfig, device): self.eval_cfg = eval_config self.exp_cfg = exp_config self.device = device def _get_analytical_metrics(self): metrics = dict( all_off_road_rate=EnvMetrics.OffRoadRate(), all_disk_off_road_rate=EnvMetrics.DiskOffRoadRate(), all_sem_layer_rate=EnvMetrics.SemLayerRate(), all_collision_rate=EnvMetrics.CollisionRate(), all_disk_collision_rate=EnvMetrics.DiskCollisionRate(), agents_collision_rate=EnvMetrics.CollisionRate(), all_failure=EnvMetrics.CriticalFailure(num_offroad_frames=2), all_comfort=EnvMetrics.Comfort(sim_dt=self.exp_cfg.algo.step_time, stat_dt=0.5), ) return metrics def get_env(self): raise NotImplementedError class EnvUnifiedBuilder(EnvironmentBuilder): def get_env(self): exp_cfg = self.exp_cfg.clone() exp_cfg.unlock() exp_cfg.env.simulation.num_simulation_steps = self.eval_cfg.num_simulation_steps exp_cfg.env.simulation.start_frame_index = exp_cfg.algo.history_num_frames + 1 exp_cfg.lock() # the config used at training time data_cfg = translate_pass_trajdata_cfg(exp_cfg) future_sec = data_cfg.future_num_frames * data_cfg.step_time history_sec = data_cfg.history_num_frames * data_cfg.step_time neighbor_distance = data_cfg.max_agents_distance
class EnvironmentBuilder(object): """Builds an simulation environment for evaluation.""" def __init__(self, eval_config: EvaluationConfig, exp_config: ExperimentConfig, device): self.eval_cfg = eval_config self.exp_cfg = exp_config self.device = device def _get_analytical_metrics(self): metrics = dict( all_off_road_rate=EnvMetrics.OffRoadRate(), all_disk_off_road_rate=EnvMetrics.DiskOffRoadRate(), all_sem_layer_rate=EnvMetrics.SemLayerRate(), all_collision_rate=EnvMetrics.CollisionRate(), all_disk_collision_rate=EnvMetrics.DiskCollisionRate(), agents_collision_rate=EnvMetrics.CollisionRate(), all_failure=EnvMetrics.CriticalFailure(num_offroad_frames=2), all_comfort=EnvMetrics.Comfort(sim_dt=self.exp_cfg.algo.step_time, stat_dt=0.5), ) return metrics def get_env(self): raise NotImplementedError class EnvUnifiedBuilder(EnvironmentBuilder): def get_env(self): exp_cfg = self.exp_cfg.clone() exp_cfg.unlock() exp_cfg.env.simulation.num_simulation_steps = self.eval_cfg.num_simulation_steps exp_cfg.env.simulation.start_frame_index = exp_cfg.algo.history_num_frames + 1 exp_cfg.lock() # the config used at training time data_cfg = translate_pass_trajdata_cfg(exp_cfg) future_sec = data_cfg.future_num_frames * data_cfg.step_time history_sec = data_cfg.history_num_frames * data_cfg.step_time neighbor_distance = data_cfg.max_agents_distance
agent_only_types = [TRAJDATA_AGENT_TYPE_MAP[cur_type] for cur_type in data_cfg.trajdata_only_types]
5
2023-10-31 18:43:07+00:00
16k
nv-tlabs/pacer
uhc/smpllib/np_smpl_humanoid_batch.py
[ { "identifier": "dict_to_torch", "path": "uhc/utils/torch_ext.py", "snippet": "def dict_to_torch(input_dict, dtype = None, device = None, add_dim = False):\n if not isinstance(input_dict, dict):\n return None\n out_dict = {}\n for key, value in input_dict.items():\n if isinstance(...
import torch import glob import os import sys import pdb import os.path as osp import joblib import pytorch3d.transforms as tR import autograd.numpy as np import time import ipdb from uhc.utils.torch_ext import dict_to_torch from uhc.utils.torch_utils import * from uhc.utils.transform_utils import * from scipy.spatial.transform import Rotation as sRot from uhc.smpllib.smpl_mujoco import SMPLConverter, smpl_to_qpose, smpl_to_qpose_torch, SMPL_BONE_ORDER_NAMES from uhc.smpllib.smpl_parser import SMPL_EE_NAMES from uhc.utils.tools import get_expert, get_expert_master from uhc.smpllib.smpl_parser import ( SMPL_Parser, SMPLH_Parser, SMPLX_Parser, ) from autograd import elementwise_grad as egrad from uhc.smpllib.smpl_robot import Robot from uhc.smpllib.torch_smpl_humanoid import Humanoid from uhc.utils.config_utils.copycat_config import Config from uhc.data_loaders.dataset_amass_single import DatasetAMASSSingle from uhc.utils.torch_ext import dict_to_torch from uhc.smpllib.smpl_mujoco import smpl_to_qpose_torch, smplh_to_smpl
11,659
pred_joints2d.squeeze()[7:8]).squeeze().mean() def fk_batch(self, pose, trans, convert_to_mat=True, count_offset=True): pose, trans = pose.cpu().numpy(), trans.cpu().numpy() B, seq_len = pose.shape[:2] if convert_to_mat: pose_mat = rodrigues(pose.reshape(B * seq_len * 24, 1, 3)).reshape( B, seq_len, -1, 3, 3) else: pose_mat = pose if pose_mat.shape != 5: pose_mat = pose_mat.reshape(B, seq_len, -1, 3, 3) J = pose_mat.shape[2] - 1 # Exclude root if count_offset: trans = trans + self._offsets[:, 0:1] pose_mat_ordered = pose_mat[:, :, self.smpl_index] wbody_pos, wbody_mat = self.forward_kinematics_batch( pose_mat_ordered[:, :, 1:], pose_mat_ordered[:, :, 0:1], trans) return_dic = {} return_dic["wbpos"] = wbody_pos return_dic["wbmat"] = wbody_mat return return_dic def fk_batch_grad(self, input_vec, count_offset=True): trans, pose = input_vec[:, :, :3], input_vec[:, :, 3:] B, seq_len = pose.shape[:2] pose_mat = rodrigues(pose.reshape(-1, 1, 3)).reshape(B, seq_len, -1, 3, 3) # pose_mat = [ # rodrigues_vec_to_rotation_mat(a) for a in pose.reshape(-1, 3) # ] # pose_mat = np.stack(pose_mat).reshape(B, seq_len, -1, 3, 3) J = pose_mat.shape[2] - 1 # Exclude root if count_offset: trans = trans + self._offsets[:, 0:1] pose_mat_ordered = pose_mat[:, :, self.smpl_index] wbody_pos, wbody_mat = self.forward_kinematics_batch( pose_mat_ordered[:, :, 1:], pose_mat_ordered[:, :, 0:1], trans) return wbody_pos def get_ee_pos(self, body_xpos, root_q, transform): ee_name = SMPL_EE_NAMES ee_pos = [] root_pos = body_xpos[:, 0, :] for name in ee_name: bone_id = self.model._body_name2id[name] - 1 bone_vec = body_xpos[:, bone_id] if transform is not None: bone_vec = bone_vec - root_pos bone_vec = transform_vec_batch(bone_vec, root_q, transform) ee_pos.append(bone_vec) return torch.swapaxes(torch.stack(ee_pos, dim=0), 0, 1) def forward_kinematics_batch(self, rotations, root_rotations, root_positions): """ Perform forward kinematics using the given trajectory and local rotations. Arguments (where B = batch size, J = number of joints): -- rotations: (B, J, 4) tensor of unit quaternions describing the local rotations of each joint. -- root_positions: (B, 3) tensor describing the root joint positions. Output: joint positions (B, J, 3) """ B, seq_len = rotations.shape[0:2] J = self._offsets.shape[1] positions_world = [] rotations_world = [] expanded_offsets = np.repeat(np.repeat(self._offsets, B, axis=0)[:, None, :], seq_len, axis=1) for i in range(J): if self._parents[i] == -1: positions_world.append(root_positions) rotations_world.append(root_rotations) else: jpos = ( np.matmul(rotations_world[self._parents[i]][:, :, 0], expanded_offsets[:, :, i, :, None]).squeeze(-1) + positions_world[self._parents[i]]) rot_mat = np.matmul(rotations_world[self._parents[i]], rotations[:, :, (i - 1):i, :]) positions_world.append(jpos) rotations_world.append(rot_mat) positions_world = np.stack(positions_world, axis=2) rotations_world = np.concatenate(rotations_world, axis=2) return positions_world, rotations_world if __name__ == "__main__": torch.manual_seed(0) cfg = Config( cfg_id="copycat_44", create_dirs=False, ) smpl_robot = Robot( cfg.robot_cfg, data_dir=osp.join(cfg.base_dir, "data/smpl"), masterfoot=False, ) dataset = DatasetAMASSSingle(cfg.data_specs, "test") humanoid_batch = Humanoid_Batch() data_test = dataset.sample_seq()
# import numpy as np sys.path.append(os.getcwd()) def smpl_op_to_op(pred_joints2d): new_2d = np.concatenate([pred_joints2d[..., [1, 4], :].mean(axis = -2, keepdims = True), \ pred_joints2d[..., 1:7, :], \ pred_joints2d[..., [7, 8, 11], :].mean(axis = -2, keepdims = True), \ pred_joints2d[..., 9:11, :], \ pred_joints2d[..., 12:, :]], \ axis = -2) return new_2d def normalize_screen_coordinates(X, w=1920, h=1080): assert X.shape[-1] == 2 # Normalize so that [0, w] is mapped to # [-1, 1], while preserving the aspect ratio return X / w * 2 - np.array([1, h / w]) def rodrigues(r): """ Rodrigues' rotation formula that turns axis-angle vector into rotation matrix in a batch-ed manner. Parameter: ---------- r: Axis-angle rotation vector of shape [batch_size, 1, 3]. Return: ------- Rotation matrix of shape [batch_size, 3, 3]. """ theta = np.linalg.norm(r, axis=(1, 2))[:, None, None] # avoid zero divide theta = np.maximum(theta, np.finfo(r.dtype).eps) r_hat = r / theta cos = np.cos(theta) z_stick = np.zeros(theta.shape[0]) m = np.stack([ z_stick, -r_hat[:, 0, 2], r_hat[:, 0, 1], r_hat[:, 0, 2], z_stick, -r_hat[:, 0, 0], -r_hat[:, 0, 1], r_hat[:, 0, 0], z_stick ], axis=1).reshape([-1, 3, 3]) i_cube = np.broadcast_to(np.expand_dims(np.eye(3), axis=0), [theta.shape[0], 3, 3]) A = np.transpose(r_hat, axes=[0, 2, 1]) B = r_hat dot = np.matmul(A, B) R = cos * i_cube + (1 - cos) * dot + np.sin(theta) * m return R def rodrigues_vec_to_rotation_mat(rot): theta = np.linalg.norm(rot, axis=0) if theta < sys.float_info.epsilon: rotation_mat = np.eye(3, dtype=float) else: rot = rot / theta I = np.eye(3, dtype=float) r_rT = np.array([[rot[0] * rot[0], rot[0] * rot[1], rot[0] * rot[2]], [rot[1] * rot[0], rot[1] * rot[1], rot[1] * rot[2]], [rot[2] * rot[0], rot[2] * rot[1], rot[2] * rot[2]]]) r_cross = np.array([[0, -rot[2], rot[1]], [rot[2], 0, -rot[0]], [-rot[1], rot[0], 0]]) rotation_mat = np.cos(theta) * I + ( 1 - np.cos(theta)) * r_rT + np.sin(theta) * r_cross return rotation_mat class Humanoid_Batch: def __init__(self, smpl_model="smpl", data_dir="data/smpl"): self.smpl_model = smpl_model if self.smpl_model == "smpl": self.smpl_parser_n = SMPL_Parser(model_path=data_dir, gender="neutral") self.smpl_parser_m = SMPL_Parser(model_path=data_dir, gender="male") self.smpl_parser_f = SMPL_Parser(model_path=data_dir, gender="female") elif self.smpl_model == "smplh": self.smpl_parser_n = SMPLH_Parser( model_path=data_dir, gender="neutral", use_pca=False, create_transl=False, ) self.smpl_parser_m = SMPLH_Parser(model_path=data_dir, gender="male", use_pca=False, create_transl=False) self.smpl_parser_f = SMPLH_Parser(model_path=data_dir, gender="female", use_pca=False, create_transl=False) elif self.smpl_model == "smplx": self.smpl_parser_n = SMPLX_Parser( model_path=data_dir, gender="neutral", use_pca=False, create_transl=False, ) self.smpl_parser_m = SMPLX_Parser(model_path=data_dir, gender="male", use_pca=False, create_transl=False) self.smpl_parser_f = SMPLX_Parser(model_path=data_dir, gender="female", use_pca=False, create_transl=False) self.model_names = [ 'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee', 'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax', 'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder', 'R_Elbow', 'R_Wrist', 'R_Hand' ] self._parents = [ -1, 0, 1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 12, 11, 14, 15, 16, 17, 11, 19, 20, 21, 22 ] self.smpl_index = [ SMPL_BONE_ORDER_NAMES.index(i) for i in self.model_names ] def update_model(self, betas, gender): betas, gender = betas.cpu().float(), gender.cpu().long() B, _ = betas.shape betas_f = betas[gender == 2] if len(betas_f) > 0: _, _, _, _, joint_offsets_f, _, _, _, _, _, _, = self.smpl_parser_f.get_mesh_offsets_batch( betas=betas_f[:, :10]) betas_n = betas[gender == 0] if len(betas_n) > 0: _, _, _, _, joint_offsets_n, _, _, _, _, _, _, = self.smpl_parser_n.get_mesh_offsets_batch( betas=betas_n[:, :10]) betas_m = betas[gender == 1] if len(betas_m) > 0: _, _, _, _, joint_offsets_m, _, _, _, _, _, _, = self.smpl_parser_m.get_mesh_offsets_batch( betas=betas_m[:, :10]) joint_offsets_all = dict() for n in SMPL_BONE_ORDER_NAMES: joint_offsets_all[n] = torch.zeros([B, 3]).float() if len(betas_f) > 0: joint_offsets_all[n][gender == 2] = joint_offsets_f[n] if len(betas_n) > 0: joint_offsets_all[n][gender == 0] = joint_offsets_n[n] if len(betas_m) > 0: joint_offsets_all[n][gender == 1] = joint_offsets_m[n] off_sets = [] for n in self.model_names: off_sets.append(joint_offsets_all[n]) # self._offsets = torch.from_numpy(np.stack(off_sets, axis=1)) self._offsets = np.round(np.stack(off_sets, axis=1), decimals=5) self.trans2joint = -self._offsets[:, 0:1] self.trans2joint[:, :, 2] = 0 # self._offsets = joblib.load("curr_offset.pkl")[None, ] def update_projection(self, cam_params, smpl2op_map, MUJOCO_2_SMPL): self.full_R = cam_params['full_R'] self.full_t = cam_params['full_t'] self.K = cam_params['K'] self.img_w = cam_params['img_w'] self.img_h = cam_params['img_h'] self.openpose_subindex = smpl2op_map < 22 self.smpl2op_map = smpl2op_map self.smpl2op_partial = self.smpl2op_map[self.openpose_subindex] self.MUJOCO_2_SMPL = MUJOCO_2_SMPL def update_tgt_joints(self, tgt_joints, inliers): self.gt_2d_joints = tgt_joints self.inliers = inliers.astype(bool) num_joints = self.gt_2d_joints.shape[-2] self.gt_2d_joints_norm = normalize_screen_coordinates(self.gt_2d_joints, self.img_w, self.img_h) self.num_frames = self.gt_2d_joints.shape[0] self.camera_rays = np.concatenate([self.gt_2d_joints, np.ones([self.num_frames, num_joints, 1])], axis=2).dot(np.linalg.inv(self.K).T) self.camera_rays /= np.linalg.norm(self.camera_rays, axis=2)[..., None] lam = 0.3 self.weighting = np.exp(lam * -np.arange(self.num_frames)) / np.sum( np.exp(lam * -np.arange(self.num_frames))) self.weighting = np.tile(self.weighting[:, None, None], [1, num_joints, 2]) # self.weighting = np.ones(self.num_frames) / self.num_frames def proj2d(self, wbpos, return_cam_3d=False): # wbpos in mujoco pred_joints3d = wbpos.squeeze()[self.MUJOCO_2_SMPL][ self.smpl2op_partial][None, ] pred_joints3d = pred_joints3d @ self.full_R.T + self.full_t pred_joints2d = pred_joints3d @ (self.K.T) z = pred_joints2d[:, :, 2:] pred_joints2d = pred_joints2d[:, :, :2] / z pred_joints2d = smpl_op_to_op(pred_joints2d) if return_cam_3d: return pred_joints2d, pred_joints3d else: return pred_joints2d def proj_2d_line_loss(self, input_vec): wbpos = self.fk_batch_grad(input_vec) _, pred_joints3d = self.proj2d(wbpos, return_cam_3d=True) dist = np.cross(pred_joints3d[0], pred_joints3d[0] - self.camera_rays)**2 return dist.mean() def proj_2d_loss(self, input_vec, ord=2, normalize = True): wbpos = self.fk_batch_grad(input_vec) pred_joints2d = self.proj2d(wbpos) curr_weighting = np.array(self.weighting) if normalize: pred_joints2d = normalize_screen_coordinates(pred_joints2d, self.img_w, self.img_h) gt_2d_joints = self.gt_2d_joints_norm else: gt_2d_joints = self.gt_2d_joints if ord == 1: loss = np.abs( gt_2d_joints[self.inliers] - pred_joints2d.squeeze()[self.inliers]).squeeze().mean() else: diff = (gt_2d_joints - pred_joints2d.squeeze())**2 curr_weighting[~self.inliers] = 0 loss = (diff * curr_weighting).sum(axis=0).mean() return loss def proj_2d_body_loss(self, input_vec, ord=2, normalize = False): # Has to use the current translation (to roughly put at the same position, and then zero out the translation) wbpos = self.fk_batch_grad(input_vec) pred_joints2d = self.proj2d(wbpos) gt2d_center = self.gt_2d_joints[..., 7:8, :].copy() pred_joints2d += (gt2d_center - pred_joints2d[..., 7:8, :]) curr_weighting = np.array(self.weighting) if normalize: pred_joints2d = normalize_screen_coordinates(pred_joints2d, self.img_w, self.img_h) gt_2d_joints = self.gt_2d_joints_norm else: gt_2d_joints = self.gt_2d_joints if ord == 1: loss = np.abs(gt_2d_joints[self.inliers] - pred_joints2d.squeeze()[self.inliers]).squeeze().mean() else: diff = (gt_2d_joints - pred_joints2d.squeeze())**2 curr_weighting[~self.inliers] = 0 loss = (diff * curr_weighting).sum(axis=0).mean() return loss def proj_2d_root_loss(self, root_pos_rot): input_vec = np.concatenate( [root_pos_rot.reshape([1, 1, 6]), np.zeros([1, 1, 69])], axis=2) wbpos = self.fk_batch_grad(input_vec) pred_joints2d = self.proj2d(wbpos) return np.abs(self.gt_2d_joints[7:8] - pred_joints2d.squeeze()[7:8]).squeeze().mean() def fk_batch(self, pose, trans, convert_to_mat=True, count_offset=True): pose, trans = pose.cpu().numpy(), trans.cpu().numpy() B, seq_len = pose.shape[:2] if convert_to_mat: pose_mat = rodrigues(pose.reshape(B * seq_len * 24, 1, 3)).reshape( B, seq_len, -1, 3, 3) else: pose_mat = pose if pose_mat.shape != 5: pose_mat = pose_mat.reshape(B, seq_len, -1, 3, 3) J = pose_mat.shape[2] - 1 # Exclude root if count_offset: trans = trans + self._offsets[:, 0:1] pose_mat_ordered = pose_mat[:, :, self.smpl_index] wbody_pos, wbody_mat = self.forward_kinematics_batch( pose_mat_ordered[:, :, 1:], pose_mat_ordered[:, :, 0:1], trans) return_dic = {} return_dic["wbpos"] = wbody_pos return_dic["wbmat"] = wbody_mat return return_dic def fk_batch_grad(self, input_vec, count_offset=True): trans, pose = input_vec[:, :, :3], input_vec[:, :, 3:] B, seq_len = pose.shape[:2] pose_mat = rodrigues(pose.reshape(-1, 1, 3)).reshape(B, seq_len, -1, 3, 3) # pose_mat = [ # rodrigues_vec_to_rotation_mat(a) for a in pose.reshape(-1, 3) # ] # pose_mat = np.stack(pose_mat).reshape(B, seq_len, -1, 3, 3) J = pose_mat.shape[2] - 1 # Exclude root if count_offset: trans = trans + self._offsets[:, 0:1] pose_mat_ordered = pose_mat[:, :, self.smpl_index] wbody_pos, wbody_mat = self.forward_kinematics_batch( pose_mat_ordered[:, :, 1:], pose_mat_ordered[:, :, 0:1], trans) return wbody_pos def get_ee_pos(self, body_xpos, root_q, transform): ee_name = SMPL_EE_NAMES ee_pos = [] root_pos = body_xpos[:, 0, :] for name in ee_name: bone_id = self.model._body_name2id[name] - 1 bone_vec = body_xpos[:, bone_id] if transform is not None: bone_vec = bone_vec - root_pos bone_vec = transform_vec_batch(bone_vec, root_q, transform) ee_pos.append(bone_vec) return torch.swapaxes(torch.stack(ee_pos, dim=0), 0, 1) def forward_kinematics_batch(self, rotations, root_rotations, root_positions): """ Perform forward kinematics using the given trajectory and local rotations. Arguments (where B = batch size, J = number of joints): -- rotations: (B, J, 4) tensor of unit quaternions describing the local rotations of each joint. -- root_positions: (B, 3) tensor describing the root joint positions. Output: joint positions (B, J, 3) """ B, seq_len = rotations.shape[0:2] J = self._offsets.shape[1] positions_world = [] rotations_world = [] expanded_offsets = np.repeat(np.repeat(self._offsets, B, axis=0)[:, None, :], seq_len, axis=1) for i in range(J): if self._parents[i] == -1: positions_world.append(root_positions) rotations_world.append(root_rotations) else: jpos = ( np.matmul(rotations_world[self._parents[i]][:, :, 0], expanded_offsets[:, :, i, :, None]).squeeze(-1) + positions_world[self._parents[i]]) rot_mat = np.matmul(rotations_world[self._parents[i]], rotations[:, :, (i - 1):i, :]) positions_world.append(jpos) rotations_world.append(rot_mat) positions_world = np.stack(positions_world, axis=2) rotations_world = np.concatenate(rotations_world, axis=2) return positions_world, rotations_world if __name__ == "__main__": torch.manual_seed(0) cfg = Config( cfg_id="copycat_44", create_dirs=False, ) smpl_robot = Robot( cfg.robot_cfg, data_dir=osp.join(cfg.base_dir, "data/smpl"), masterfoot=False, ) dataset = DatasetAMASSSingle(cfg.data_specs, "test") humanoid_batch = Humanoid_Batch() data_test = dataset.sample_seq()
data_test = dict_to_torch(data_test)
0
2023-10-31 20:47:12+00:00
16k
Improbable-AI/dexenv
dexenv/envs/dclaw_base.py
[ { "identifier": "VecTask", "path": "dexenv/envs/base/vec_task.py", "snippet": "class VecTask(Env):\n\n def __init__(self, config, sim_device, rl_device, graphics_device_id, headless):\n \"\"\"Initialise the `VecTask`.\n Args:\n config: config dictionary for the environment.\n...
import time import torch import dexenv from isaacgym import gymapi from isaacgym import gymtorch from isaacgym.gymutil import get_property_getter_map from isaacgym.gymutil import get_property_setter_map from isaacgymenvs.utils.torch_jit_utils import * from loguru import logger from dexenv.envs.base.vec_task import VecTask from dexenv.envs.rewards import compute_dclaw_reward from dexenv.utils.common import get_module_path from dexenv.utils.common import pathlib_file from dexenv.utils.hand_color import dclaw_body_color_mapping from dexenv.utils.isaac_utils import get_camera_params from dexenv.utils.torch_utils import random_quaternions from dexenv.utils.torch_utils import torch_long
10,857
cam_focus_pt = np.array([0.08, 0, 0.15]) cam_focus_pt = gymapi.Vec3(*cam_focus_pt) cam_pos = gymapi.Vec3(*cam_pos) camera_poses = [(cam_pos, cam_focus_pt)] camera_params = get_camera_params(width=self.cfg.cam.visual_render_width, height=self.cfg.cam.visual_render_height, hov=45, cuda=False) return camera_poses, camera_params def create_hand_actor(self, env_ptr, dclaw_asset, dclaw_start_pose, dclaw_dof_props, env_id): dclaw_actor = self.gym.create_actor(env_ptr, dclaw_asset, dclaw_start_pose, "hand", env_id, 0, 0) if self.cfg.env.dof_torque_on: self.gym.enable_actor_dof_force_sensors(env_ptr, dclaw_actor) self.hand_start_states.append( [dclaw_start_pose.p.x, dclaw_start_pose.p.y, dclaw_start_pose.p.z, dclaw_start_pose.r.x, dclaw_start_pose.r.y, dclaw_start_pose.r.z, dclaw_start_pose.r.w, 0, 0, 0, 0, 0, 0]) self.gym.set_actor_dof_properties(env_ptr, dclaw_actor, dclaw_dof_props) hand_idx = self.gym.get_actor_index(env_ptr, dclaw_actor, gymapi.DOMAIN_SIM) self.hand_indices.append(hand_idx) self.gym.set_actor_dof_states(env_ptr, dclaw_actor, self.dclaw_default_dof_states, gymapi.STATE_ALL) if self.obs_type == "full_state": self.gym.enable_actor_dof_force_sensors(env_ptr, dclaw_actor) self.dclaws.append(dclaw_actor) self.set_hand_color(env_ptr, dclaw_actor) def set_hand_color(self, env_ptr, dclaw_actor): rgd_dict = self.gym.get_actor_rigid_body_dict(env_ptr, dclaw_actor) for bd, bd_id in rgd_dict.items(): if bd not in dclaw_body_color_mapping: continue color = gymapi.Vec3(*dclaw_body_color_mapping[bd]) self.gym.set_rigid_body_color(env_ptr, dclaw_actor, bd_id, gymapi.MESH_VISUAL, color) def get_table_asset(self): asset_options = gymapi.AssetOptions() asset_options.armature = 0.001 asset_options.fix_base_link = True asset_options.thickness = 0.001 asset_options.disable_gravity = True table_dims = gymapi.Vec3(0.6, 0.6, 0.1) table_asset = self.gym.create_box(self.sim, table_dims.x, table_dims.y, table_dims.z, asset_options) table_props = self.gym.get_asset_rigid_shape_properties(table_asset) for p in table_props: p.friction = self.cfg.env.table.friction p.torsion_friction = self.cfg.env.table.torsion_friction p.restitution = self.cfg.env.table.restitution p.rolling_friction = self.cfg.env.table.rolling_friction self.gym.set_asset_rigid_shape_properties(table_asset, table_props) return table_asset def get_table_pose(self): object_start_pose = gymapi.Transform() object_start_pose.p = gymapi.Vec3() object_start_pose.p.x = 0 object_start_pose.p.y = 0 object_start_pose.p.z = -0.05 return object_start_pose def get_dclaw_start_pose(self): dclaw_start_pose = gymapi.Transform() dclaw_start_pose.p = gymapi.Vec3(*get_axis_params(0.25, self.up_axis_idx)) dclaw_start_pose.r = gymapi.Quat.from_axis_angle(gymapi.Vec3(0, 1, 0), np.pi) return dclaw_start_pose def setup_torch_states(self): self.render_rgb_obs_buf = None if self.cfg.rgb_render: self.gym.set_light_parameters(self.sim, 0, gymapi.Vec3(0.9, 0.9, 0.9), gymapi.Vec3(0.9, 0.9, 0.9), gymapi.Vec3(0, 0, 0)) else: self.gym.set_light_parameters(self.sim, 0, gymapi.Vec3(0.9, 0.9, 0.9), gymapi.Vec3(0.7, 0.7, 0.7), gymapi.Vec3(0, 0, 0)) self.object_init_state = to_torch(self.object_init_state, device=self.device, dtype=torch.float).view( self.num_envs, 13) self.goal_states = self.object_init_state.clone() self.goal_states[:, self.up_axis_idx] -= 0.04 self.goal_init_state = self.goal_states.clone() self.hand_start_states = to_torch(self.hand_start_states, device=self.device).view(self.num_envs, 13) self.fingertip_handles = to_torch(self.fingertip_handles, dtype=torch.long, device=self.device) self.object_rb_handles = to_torch(self.object_rb_handles, dtype=torch.long, device=self.device) self.object_rb_masses = None self.update_obj_mass() self.hand_indices = to_torch(self.hand_indices, dtype=torch.long, device=self.device) self.object_indices = to_torch(self.object_indices, dtype=torch.long, device=self.device) self.goal_object_indices = to_torch(self.goal_object_indices, dtype=torch.long, device=self.device) def get_dclaw_asset(self, asset_root=None, asset_options=None): # load dclaw asset if asset_options is None: asset_options = gymapi.AssetOptions() asset_options.flip_visual_attachments = False asset_options.fix_base_link = True asset_options.collapse_fixed_joints = False asset_options.disable_gravity = False asset_options.thickness = 0.001 asset_options.angular_damping = 0.01 asset_options.override_inertia = True asset_options.override_com = True logger.info(f'VHACD:{self.cfg.env.vhacd}') if self.cfg.env.vhacd: asset_options.convex_decomposition_from_submeshes = True if self.cfg.physics_engine == "physx": # if self.physics_engine == gymapi.SIM_PHYSX: asset_options.use_physx_armature = True asset_options.default_dof_drive_mode = gymapi.DOF_MODE_POS if asset_root is None: asset_root = dexenv.LIB_PATH.joinpath('assets', 'dclaw_4f').as_posix() robot_name = self.cfg.env.robot
class DClawBase(VecTask): def __init__(self, cfg, sim_device, rl_device, graphics_device_id): self.cfg = cfg headless = self.cfg.headless self.randomize = self.cfg["task"]["randomize"] if self.randomize: logger.warning(f'Domain randomization is enabled!') self.randomization_params = self.cfg["task"]["randomization_params"] self.aggregate_mode = self.cfg["env"]["aggregateMode"] self.dist_reward_scale = self.cfg["env"]["rew"]["distRewardScale"] self.rot_reward_scale = self.cfg["env"]["rew"]["rotRewardScale"] self.success_tolerance = self.cfg["env"]["rew"]["successTolerance"] self.reach_goal_bonus = self.cfg["env"]["rew"]["reachGoalBonus"] self.fall_dist = self.cfg["env"]["rew"]["fallDistance"] self.fall_penalty = self.cfg["env"]["rew"]["fallPenalty"] self.rot_eps = self.cfg["env"]["rew"]["rotEps"] self.vel_obs_scale = 0.2 # scale factor of velocity based observations self.force_torque_obs_scale = 10.0 # scale factor of velocity based observations self.reset_position_noise = self.cfg["env"]["resetPositionNoise"] self.reset_rotation_noise = self.cfg["env"]["resetRotationNoise"] self.reset_dof_pos_noise = self.cfg["env"]["resetDofPosRandomInterval"] self.reset_dof_vel_noise = self.cfg["env"]["resetDofVelRandomInterval"] self.force_scale = self.cfg["env"].get("forceScale", 0.0) self.force_prob_range = self.cfg["env"].get("forceProbRange", [0.001, 0.1]) self.force_decay = self.cfg["env"].get("forceDecay", 0.99) self.force_decay_interval = self.cfg["env"].get("forceDecayInterval", 0.08) self.dclaw_dof_speed_scale = self.cfg["env"]["dofSpeedScale"] # self.act_moving_average = self.cfg["env"]["actionsMovingAverage"] self.debug_viz = self.cfg["env"]["enableDebugVis"] self.max_episode_length = self.cfg["env"]["episodeLength"] self.reset_time = self.cfg["env"].get("resetTime", -1.0) self.print_success_stat = self.cfg["env"]["printNumSuccesses"] self.max_consecutive_successes = self.cfg["env"]["maxConsecutiveSuccesses"] self.av_factor = self.cfg["env"].get("averFactor", 0.1) self.object_type = self.cfg["env"]["objectType"] self.asset_files_dict = { "block": "urdf/objects/cube_multicolor.urdf", "egg": "mjcf/open_ai_assets/hand/egg.xml", "airplane": "single_objects/airplane/model.urdf", 'power_drill': 'single_objects/power_drill/model.urdf', 'mug': 'single_objects/mug/model.urdf', 'elephant': 'asymm/train/elephant/var_000/model.urdf', 'train': 'asymm/train/train/var_000/model.urdf', 'stanford_bunny': 'asymm/train/stanford_bunny/var_004/model.urdf' } self.objs_in_isaacgym = ['block', 'egg'] if "asset" in self.cfg["env"]: self.asset_files_dict["block"] = self.cfg["env"]["asset"].get("assetFileNameBlock", self.asset_files_dict["block"]) self.asset_files_dict["egg"] = self.cfg["env"]["asset"].get("assetFileNameEgg", self.asset_files_dict["egg"]) self.obs_type = self.cfg["env"]["observationType"] if not (self.obs_type in ["full_no_vel", "full", "full_state"]): raise Exception( "Unknown type of observations!\nobservationType should be one of: [openai, full_no_vel, full, full_state]") print("Obs type:", self.obs_type) ## TODO: change value here self.num_obs_dict = { "full_no_vel": 42, "full": 87, "full_state": 114 } self.up_axis = 'z' num_states = 0 self.cfg["env"]["numObservations"] = self.num_obs_dict[self.obs_type] self.cfg["env"]["numStates"] = num_states self.cfg["env"]["numActions"] = 12 self.hist_buf_reset_env_ids = None super().__init__(config=self.cfg, sim_device=sim_device, rl_device=rl_device, graphics_device_id=graphics_device_id, headless=headless) self.dt = self.sim_params.dt control_freq_inv = self.cfg["env"].get("controlFrequencyInv", 1) if self.reset_time > 0.0: self.max_episode_length = int(round(self.reset_time / (control_freq_inv * self.dt))) print("Reset time: ", self.reset_time) print("New episode length: ", self.max_episode_length) if self.viewer != None: cam_pos = gymapi.Vec3(0.16, -0.5, 0.5) cam_target = gymapi.Vec3(0.0, 0.0, 0.15) self.gym.viewer_camera_look_at(self.viewer, None, cam_pos, cam_target) actor_root_state_tensor = self.gym.acquire_actor_root_state_tensor(self.sim) dof_state_tensor = self.gym.acquire_dof_state_tensor(self.sim) rigid_body_tensor = self.gym.acquire_rigid_body_state_tensor(self.sim) dof_force_tensor = self.gym.acquire_dof_force_tensor(self.sim) if self.obs_type == "full_state": sensor_tensor = self.gym.acquire_force_sensor_tensor(self.sim) self.vec_sensor_tensor = gymtorch.wrap_tensor(sensor_tensor).view(self.num_envs, self.num_fingertips * 6) dof_force_tensor = self.gym.acquire_dof_force_tensor(self.sim) self.dof_force_tensor = gymtorch.wrap_tensor(dof_force_tensor).view(self.num_envs, self.num_dclaw_dofs) self.gym.refresh_actor_root_state_tensor(self.sim) self.gym.refresh_dof_state_tensor(self.sim) if self.cfg.env.dof_torque_on: self.gym.refresh_dof_force_tensor(self.sim) self.gym.refresh_rigid_body_state_tensor(self.sim) self.dof_state = gymtorch.wrap_tensor(dof_state_tensor) self.dclaw_dof_state = self.dof_state.view(self.num_envs, -1, 2)[:, :self.num_dclaw_dofs] self.dclaw_dof_pos = self.dclaw_dof_state[..., 0] self.dclaw_dof_vel = self.dclaw_dof_state[..., 1] if self.cfg.env.dof_torque_on: self.dclaw_dof_torque = gymtorch.wrap_tensor(dof_force_tensor).view(self.num_envs, -1) else: self.dclaw_dof_torque = None self.rigid_body_states = gymtorch.wrap_tensor(rigid_body_tensor).view(self.num_envs, -1, 13) self.num_bodies = self.rigid_body_states.shape[1] self.root_state_tensor = gymtorch.wrap_tensor(actor_root_state_tensor).view(-1, 13) if self.cfg.env.rew.pen_tb_contact: _net_cf = self.gym.acquire_net_contact_force_tensor(self.sim) self.net_contact_force = gymtorch.wrap_tensor(_net_cf).view(self.num_envs, -1, 3) table_handle = self.gym.find_actor_handle(self.envs[0], 'table') self.table_body_index = self.gym.find_actor_rigid_body_index(self.envs[0], table_handle, 'table', gymapi.DOMAIN_ENV) logger.warning(f'Table body index:{self.table_body_index}') self.table_contact_force = self.net_contact_force[:, self.table_body_index] self.num_dofs = self.gym.get_sim_dof_count(self.sim) // self.num_envs self.prev_targets = torch.zeros((self.num_envs, self.num_dofs), dtype=torch.float, device=self.device) self.cur_targets = torch.zeros((self.num_envs, self.num_dofs), dtype=torch.float, device=self.device) self.global_indices = torch.arange(self.num_envs * 3, dtype=torch.int32, device=self.device).view(self.num_envs, -1) self.reset_goal_buf = self.reset_buf.clone() self.successes = torch.zeros(self.num_envs, dtype=torch.float, device=self.device) self.consecutive_successes = torch.zeros(1, dtype=torch.float, device=self.device) self.av_factor = to_torch(self.av_factor, dtype=torch.float, device=self.device) self.total_successes = 0 self.total_resets = 0 self.force_decay = to_torch(self.force_decay, dtype=torch.float, device=self.device) self.force_prob_range = to_torch(self.force_prob_range, dtype=torch.float, device=self.device) self.random_force_prob = torch.exp((torch.log(self.force_prob_range[0]) - torch.log(self.force_prob_range[1])) * torch.rand(self.num_envs, device=self.device) + torch.log( self.force_prob_range[1])) self.rb_forces = torch.zeros((self.num_envs, self.num_bodies, 3), dtype=torch.float, device=self.device) self.num_actions = self.num_dclaw_dofs self.actions = self.zero_actions() DClawBase.compute_observations(self) self.num_observations = self.obs_buf.shape[-1] self.cfg.env.numObservations = self.num_observations self.create_ob_act_space() def create_sim(self): self.dt = self.cfg["sim"]["dt"] self.up_axis_idx = self.set_sim_params_up_axis(self.sim_params, self.up_axis) self.sim = super().create_sim(self.device_id, self.graphics_device_id, self.physics_engine, self.sim_params) self._create_ground_plane() self._create_envs(self.num_envs, self.cfg["env"]['envSpacing'], int(np.sqrt(self.num_envs))) if self.randomize: self.apply_randomizations(self.randomization_params) def _create_ground_plane(self): plane_params = gymapi.PlaneParams() plane_params.normal = gymapi.Vec3(0.0, 0.0, 1.0) plane_params.distance = 0.1 self.gym.add_ground(self.sim, plane_params) def _create_envs(self, num_envs, spacing, num_per_row): lower = gymapi.Vec3(-spacing, -spacing, 0.0) upper = gymapi.Vec3(spacing, spacing, spacing) asset_root = dexenv.LIB_PATH.joinpath('assets', 'dclaw').as_posix() object_asset_file = self.asset_files_dict[self.object_type] dclaw_asset, dclaw_dof_props = self.get_dclaw_asset(asset_root=asset_root) table_asset = self.get_table_asset() table_pose = self.get_table_pose() if self.obs_type == "full_state": sensor_pose = gymapi.Transform() for ft_handle in self.fingertip_handles: self.gym.create_asset_force_sensor(dclaw_asset, ft_handle, sensor_pose) if self.object_type in self.objs_in_isaacgym: asset_root = get_module_path('isaacgymenvs').parent.joinpath('assets').as_posix() else: asset_root = dexenv.LIB_PATH.joinpath('assets').as_posix() object_asset_options = gymapi.AssetOptions() if self.cfg.env.vhacd: object_asset_options.convex_decomposition_from_submeshes = True object_asset = self.gym.load_asset(self.sim, asset_root, object_asset_file, object_asset_options) object_asset_options.disable_gravity = True goal_asset = self.gym.load_asset(self.sim, asset_root, object_asset_file, object_asset_options) dclaw_start_pose = self.get_dclaw_start_pose() object_start_pose = self.get_object_start_pose(dclaw_start_pose) goal_start_pose = self.get_goal_object_start_pose(object_start_pose=object_start_pose) self.dclaws = [] self.envs = [] self.object_init_state = [] self.hand_start_states = [] self.hand_indices = [] self.fingertip_indices = [] self.object_indices = [] self.goal_object_indices = [] self.render_camera_handles = [] if self.cfg.rgb_render: render_cam_pose, render_cam_params = self.get_visual_render_camera_setup() self.fingertip_handles = [self.gym.find_asset_rigid_body_index(dclaw_asset, name) for name in self.fingertips] print(f'Fingertip handles:{self.fingertip_handles}') dclaw_rb_count = self.gym.get_asset_rigid_body_count(dclaw_asset) object_rb_count = self.gym.get_asset_rigid_body_count(object_asset) object_rs_count = self.gym.get_asset_rigid_shape_count(object_asset) self.object_rb_handles = list(range(dclaw_rb_count, dclaw_rb_count + object_rb_count)) self.object_handles = [] max_agg_bodies = self.num_dclaw_bodies + 2 * object_rb_count + 1 max_agg_shapes = self.num_dclaw_shapes + 2 * object_rs_count + 1 for i in range(self.num_envs): env_ptr = self.gym.create_env( self.sim, lower, upper, num_per_row ) if self.aggregate_mode >= 1: self.gym.begin_aggregate(env_ptr, max_agg_bodies, max_agg_shapes, True) self.create_hand_actor(env_ptr=env_ptr, dclaw_asset=dclaw_asset, dclaw_start_pose=dclaw_start_pose, dclaw_dof_props=dclaw_dof_props, env_id=i) object_handle = self.gym.create_actor(env_ptr, object_asset, object_start_pose, "object", i, 0, 1) self.object_handles.append(object_handle) self.object_init_state.append([object_start_pose.p.x, object_start_pose.p.y, object_start_pose.p.z, object_start_pose.r.x, object_start_pose.r.y, object_start_pose.r.z, object_start_pose.r.w, 0, 0, 0, 0, 0, 0]) object_idx = self.gym.get_actor_index(env_ptr, object_handle, gymapi.DOMAIN_SIM) self.object_indices.append(object_idx) goal_handle = self.gym.create_actor(env_ptr, goal_asset, goal_start_pose, "goal_object", i + self.num_envs, 0, 2) goal_object_idx = self.gym.get_actor_index(env_ptr, goal_handle, gymapi.DOMAIN_SIM) self.goal_object_indices.append(goal_object_idx) if self.cfg.env.blockscale is not None and self.cfg.env.objectType == 'block': blockscale = float(self.cfg.env.blockscale) self.gym.set_actor_scale(env_ptr, object_handle, blockscale) self.gym.set_actor_scale(env_ptr, goal_handle, blockscale) if self.object_type != "block": self.gym.set_rigid_body_color( env_ptr, object_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98)) self.gym.set_rigid_body_color( env_ptr, goal_handle, 0, gymapi.MESH_VISUAL, gymapi.Vec3(0.6, 0.72, 0.98)) table_handle = self.gym.create_actor(env_ptr, table_asset, table_pose, "table", i, 0) if self.cfg.rgb_render: render_camera_handle = self.create_camera(render_cam_pose, env_ptr, render_cam_params) self.render_camera_handles.append(render_camera_handle[0]) if self.aggregate_mode > 0: self.gym.end_aggregate(env_ptr) self.envs.append(env_ptr) self.setup_torch_states() def create_camera(self, camera_poses, env_ptr, camera_params): cam_handles = [] for ic in range(min(len(camera_poses), self.cfg.cam.cam_num)): camera_handle = self.gym.create_camera_sensor(env_ptr, camera_params) if isinstance(camera_poses[ic], tuple): self.gym.set_camera_location(camera_handle, env_ptr, camera_poses[ic][0], camera_poses[ic][1]) else: self.gym.set_camera_transform(camera_handle, env_ptr, camera_poses[ic]) cam_handles.append(camera_handle) return cam_handles def get_visual_render_camera_setup(self): cam_pos = np.array([-0.7, 0, 0.5]) cam_focus_pt = np.array([0.08, 0, 0.15]) cam_focus_pt = gymapi.Vec3(*cam_focus_pt) cam_pos = gymapi.Vec3(*cam_pos) camera_poses = [(cam_pos, cam_focus_pt)] camera_params = get_camera_params(width=self.cfg.cam.visual_render_width, height=self.cfg.cam.visual_render_height, hov=45, cuda=False) return camera_poses, camera_params def create_hand_actor(self, env_ptr, dclaw_asset, dclaw_start_pose, dclaw_dof_props, env_id): dclaw_actor = self.gym.create_actor(env_ptr, dclaw_asset, dclaw_start_pose, "hand", env_id, 0, 0) if self.cfg.env.dof_torque_on: self.gym.enable_actor_dof_force_sensors(env_ptr, dclaw_actor) self.hand_start_states.append( [dclaw_start_pose.p.x, dclaw_start_pose.p.y, dclaw_start_pose.p.z, dclaw_start_pose.r.x, dclaw_start_pose.r.y, dclaw_start_pose.r.z, dclaw_start_pose.r.w, 0, 0, 0, 0, 0, 0]) self.gym.set_actor_dof_properties(env_ptr, dclaw_actor, dclaw_dof_props) hand_idx = self.gym.get_actor_index(env_ptr, dclaw_actor, gymapi.DOMAIN_SIM) self.hand_indices.append(hand_idx) self.gym.set_actor_dof_states(env_ptr, dclaw_actor, self.dclaw_default_dof_states, gymapi.STATE_ALL) if self.obs_type == "full_state": self.gym.enable_actor_dof_force_sensors(env_ptr, dclaw_actor) self.dclaws.append(dclaw_actor) self.set_hand_color(env_ptr, dclaw_actor) def set_hand_color(self, env_ptr, dclaw_actor): rgd_dict = self.gym.get_actor_rigid_body_dict(env_ptr, dclaw_actor) for bd, bd_id in rgd_dict.items(): if bd not in dclaw_body_color_mapping: continue color = gymapi.Vec3(*dclaw_body_color_mapping[bd]) self.gym.set_rigid_body_color(env_ptr, dclaw_actor, bd_id, gymapi.MESH_VISUAL, color) def get_table_asset(self): asset_options = gymapi.AssetOptions() asset_options.armature = 0.001 asset_options.fix_base_link = True asset_options.thickness = 0.001 asset_options.disable_gravity = True table_dims = gymapi.Vec3(0.6, 0.6, 0.1) table_asset = self.gym.create_box(self.sim, table_dims.x, table_dims.y, table_dims.z, asset_options) table_props = self.gym.get_asset_rigid_shape_properties(table_asset) for p in table_props: p.friction = self.cfg.env.table.friction p.torsion_friction = self.cfg.env.table.torsion_friction p.restitution = self.cfg.env.table.restitution p.rolling_friction = self.cfg.env.table.rolling_friction self.gym.set_asset_rigid_shape_properties(table_asset, table_props) return table_asset def get_table_pose(self): object_start_pose = gymapi.Transform() object_start_pose.p = gymapi.Vec3() object_start_pose.p.x = 0 object_start_pose.p.y = 0 object_start_pose.p.z = -0.05 return object_start_pose def get_dclaw_start_pose(self): dclaw_start_pose = gymapi.Transform() dclaw_start_pose.p = gymapi.Vec3(*get_axis_params(0.25, self.up_axis_idx)) dclaw_start_pose.r = gymapi.Quat.from_axis_angle(gymapi.Vec3(0, 1, 0), np.pi) return dclaw_start_pose def setup_torch_states(self): self.render_rgb_obs_buf = None if self.cfg.rgb_render: self.gym.set_light_parameters(self.sim, 0, gymapi.Vec3(0.9, 0.9, 0.9), gymapi.Vec3(0.9, 0.9, 0.9), gymapi.Vec3(0, 0, 0)) else: self.gym.set_light_parameters(self.sim, 0, gymapi.Vec3(0.9, 0.9, 0.9), gymapi.Vec3(0.7, 0.7, 0.7), gymapi.Vec3(0, 0, 0)) self.object_init_state = to_torch(self.object_init_state, device=self.device, dtype=torch.float).view( self.num_envs, 13) self.goal_states = self.object_init_state.clone() self.goal_states[:, self.up_axis_idx] -= 0.04 self.goal_init_state = self.goal_states.clone() self.hand_start_states = to_torch(self.hand_start_states, device=self.device).view(self.num_envs, 13) self.fingertip_handles = to_torch(self.fingertip_handles, dtype=torch.long, device=self.device) self.object_rb_handles = to_torch(self.object_rb_handles, dtype=torch.long, device=self.device) self.object_rb_masses = None self.update_obj_mass() self.hand_indices = to_torch(self.hand_indices, dtype=torch.long, device=self.device) self.object_indices = to_torch(self.object_indices, dtype=torch.long, device=self.device) self.goal_object_indices = to_torch(self.goal_object_indices, dtype=torch.long, device=self.device) def get_dclaw_asset(self, asset_root=None, asset_options=None): # load dclaw asset if asset_options is None: asset_options = gymapi.AssetOptions() asset_options.flip_visual_attachments = False asset_options.fix_base_link = True asset_options.collapse_fixed_joints = False asset_options.disable_gravity = False asset_options.thickness = 0.001 asset_options.angular_damping = 0.01 asset_options.override_inertia = True asset_options.override_com = True logger.info(f'VHACD:{self.cfg.env.vhacd}') if self.cfg.env.vhacd: asset_options.convex_decomposition_from_submeshes = True if self.cfg.physics_engine == "physx": # if self.physics_engine == gymapi.SIM_PHYSX: asset_options.use_physx_armature = True asset_options.default_dof_drive_mode = gymapi.DOF_MODE_POS if asset_root is None: asset_root = dexenv.LIB_PATH.joinpath('assets', 'dclaw_4f').as_posix() robot_name = self.cfg.env.robot
asset_root = pathlib_file(asset_root).parent.joinpath(f'{robot_name}').as_posix()
3
2023-10-25 17:22:41+00:00
16k
CVHub520/yolov5_obb
detect.py
[ { "identifier": "DetectMultiBackend", "path": "models/common.py", "snippet": "class DetectMultiBackend(nn.Module):\n # YOLOv5 MultiBackend class for python inference on various backends\n def __init__(self, weights='yolov5s.pt', device=None, dnn=False):\n # Usage:\n # PyTorch: ...
import argparse import os import sys import cv2 import torch import torch.backends.cudnn as cudnn from pathlib import Path from models.common import DetectMultiBackend from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, increment_path, non_max_suppression, non_max_suppression_obb, print_args, scale_coords, scale_polys, strip_optimizer, xyxy2xywh) from utils.plots import Annotator, colors, save_one_box from utils.torch_utils import select_device, time_sync from utils.rboxs_utils import poly2rbox, rbox2poly
14,097
""" FILE = Path(__file__).resolve() ROOT = FILE.parents[0] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative @torch.no_grad() def run(weights=ROOT / 'yolov5s.pt', # model.pt path(s) source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / 'runs/detect', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference ): source = str(source) save_img = not nosave and not source.endswith('.txt') # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file) if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn) stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine imgsz = check_img_size(imgsz, s=stride) # check image size # Half half &= (pt or jit or engine) and device.type != 'cpu' # half precision only supported by PyTorch on CUDA if pt or jit: model.model.half() if half else model.model.float() # Dataloader if webcam: view_img = check_imshow() cudnn.benchmark = True # set True to speed up constant image size inference dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt) bs = len(dataset) # batch_size else: dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt) bs = 1 # batch_size vid_path, vid_writer = [None] * bs, [None] * bs # Run inference model.warmup(imgsz=(1, 3, *imgsz), half=half) # warmup dt, seen = [0.0, 0.0, 0.0], 0 for path, im, im0s, vid_cap, s in dataset: t1 = time_sync() im = torch.from_numpy(im).to(device) im = im.half() if half else im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 if len(im.shape) == 3: im = im[None] # expand for batch dim t2 = time_sync() dt[0] += t2 - t1 # Inference visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False pred = model(im, augment=augment, visualize=visualize) t3 = time_sync() dt[1] += t3 - t2 # NMS # pred: list*(n, [xylsθ, conf, cls]) θ ∈ [-pi/2, pi/2) pred = non_max_suppression_obb(pred, conf_thres, iou_thres, classes, agnostic_nms, multi_label=True, max_det=max_det) dt[2] += time_sync() - t3 # Second-stage classifier (optional) # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s) # Process predictions for i, det in enumerate(pred): # per image pred_poly = rbox2poly(det[:, :5]) # (n, [x1 y1 x2 y2 x3 y3 x4 y4]) seen += 1 if webcam: # batch_size >= 1 p, im0, frame = path[i], im0s[i].copy(), dataset.count s += f'{i}: ' else: p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0) p = Path(p) # to Path save_path = str(save_dir / p.name) # im.jpg txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt s += '%gx%g ' % im.shape[2:] # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh imc = im0.copy() if save_crop else im0 # for save_crop annotator = Annotator(im0, line_width=line_thickness, example=str(names)) if len(det): # Rescale polys from img_size to im0 size # det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Run inference on images, videos, directories, streams, etc. Usage: $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam img.jpg # image vid.mp4 # video path/ # directory path/*.jpg # glob 'https://youtu.be/Zgi9g1ksQHc' # YouTube 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream """ FILE = Path(__file__).resolve() ROOT = FILE.parents[0] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative @torch.no_grad() def run(weights=ROOT / 'yolov5s.pt', # model.pt path(s) source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam imgsz=(640, 640), # inference size (height, width) conf_thres=0.25, # confidence threshold iou_thres=0.45, # NMS IOU threshold max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=False, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project=ROOT / 'runs/detect', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference dnn=False, # use OpenCV DNN for ONNX inference ): source = str(source) save_img = not nosave and not source.endswith('.txt') # save inference images is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS) is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file) if is_url and is_file: source = check_file(source) # download # Directories save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir # Load model device = select_device(device) model = DetectMultiBackend(weights, device=device, dnn=dnn) stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine imgsz = check_img_size(imgsz, s=stride) # check image size # Half half &= (pt or jit or engine) and device.type != 'cpu' # half precision only supported by PyTorch on CUDA if pt or jit: model.model.half() if half else model.model.float() # Dataloader if webcam: view_img = check_imshow() cudnn.benchmark = True # set True to speed up constant image size inference dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt) bs = len(dataset) # batch_size else: dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt) bs = 1 # batch_size vid_path, vid_writer = [None] * bs, [None] * bs # Run inference model.warmup(imgsz=(1, 3, *imgsz), half=half) # warmup dt, seen = [0.0, 0.0, 0.0], 0 for path, im, im0s, vid_cap, s in dataset: t1 = time_sync() im = torch.from_numpy(im).to(device) im = im.half() if half else im.float() # uint8 to fp16/32 im /= 255 # 0 - 255 to 0.0 - 1.0 if len(im.shape) == 3: im = im[None] # expand for batch dim t2 = time_sync() dt[0] += t2 - t1 # Inference visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False pred = model(im, augment=augment, visualize=visualize) t3 = time_sync() dt[1] += t3 - t2 # NMS # pred: list*(n, [xylsθ, conf, cls]) θ ∈ [-pi/2, pi/2) pred = non_max_suppression_obb(pred, conf_thres, iou_thres, classes, agnostic_nms, multi_label=True, max_det=max_det) dt[2] += time_sync() - t3 # Second-stage classifier (optional) # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s) # Process predictions for i, det in enumerate(pred): # per image pred_poly = rbox2poly(det[:, :5]) # (n, [x1 y1 x2 y2 x3 y3 x4 y4]) seen += 1 if webcam: # batch_size >= 1 p, im0, frame = path[i], im0s[i].copy(), dataset.count s += f'{i}: ' else: p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0) p = Path(p) # to Path save_path = str(save_dir / p.name) # im.jpg txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # im.txt s += '%gx%g ' % im.shape[2:] # print string gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh imc = im0.copy() if save_crop else im0 # for save_crop annotator = Annotator(im0, line_width=line_thickness, example=str(names)) if len(det): # Rescale polys from img_size to im0 size # det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
pred_poly = scale_polys(im.shape[2:], pred_poly, im0.shape)
16
2023-10-31 06:06:41+00:00
16k
DataCanvasIO/LMS
lms/runtime/prune/llm_pruner/LLMPruner/peft/mapping.py
[ { "identifier": "PeftModel", "path": "lms/runtime/prune/llm_pruner/LLMPruner/peft/peft_model.py", "snippet": "class PeftModel(PushToHubMixin, torch.nn.Module):\n \"\"\"\n Base model encompassing various Peft methods.\n\n Args:\n model ([`~transformers.PreTrainedModel`]): The base transfo...
from .peft_model import ( PeftModel, PeftModelForCausalLM, PeftModelForSeq2SeqLM, PeftModelForSequenceClassification, PeftModelForTokenClassification, ) from .tuners import AdaLoraConfig, LoraConfig, PrefixTuningConfig, PromptEncoderConfig, PromptTuningConfig from .utils import PromptLearningConfig
14,279
# coding=utf-8 # Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. MODEL_TYPE_TO_PEFT_MODEL_MAPPING = { "SEQ_CLS": PeftModelForSequenceClassification, "SEQ_2_SEQ_LM": PeftModelForSeq2SeqLM, "CAUSAL_LM": PeftModelForCausalLM, "TOKEN_CLS": PeftModelForTokenClassification, } PEFT_TYPE_TO_CONFIG_MAPPING = { "PROMPT_TUNING": PromptTuningConfig,
# coding=utf-8 # Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. MODEL_TYPE_TO_PEFT_MODEL_MAPPING = { "SEQ_CLS": PeftModelForSequenceClassification, "SEQ_2_SEQ_LM": PeftModelForSeq2SeqLM, "CAUSAL_LM": PeftModelForCausalLM, "TOKEN_CLS": PeftModelForTokenClassification, } PEFT_TYPE_TO_CONFIG_MAPPING = { "PROMPT_TUNING": PromptTuningConfig,
"PREFIX_TUNING": PrefixTuningConfig,
8
2023-10-30 10:50:32+00:00
16k
chenran-li/RQL-release
stable_baselines3/a2c/a2c.py
[ { "identifier": "OnPolicyAlgorithm", "path": "stable_baselines3/common/on_policy_algorithm.py", "snippet": "class OnPolicyAlgorithm(BaseAlgorithm):\n \"\"\"\n The base for On-Policy algorithms (ex: A2C/PPO).\n\n :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)\n :param env:...
from typing import Any, Dict, Optional, Type, TypeVar, Union from gym import spaces from torch.nn import functional as F from stable_baselines3.common.on_policy_algorithm import OnPolicyAlgorithm from stable_baselines3.common.policies import ActorCriticCnnPolicy, ActorCriticPolicy, BasePolicy, MultiInputActorCriticPolicy from stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, Schedule from stable_baselines3.common.utils import explained_variance import torch as th
10,962
:param _init_setup_model: Whether or not to build the network at the creation of the instance """ policy_aliases: Dict[str, Type[BasePolicy]] = { "MlpPolicy": ActorCriticPolicy, "CnnPolicy": ActorCriticCnnPolicy, "MultiInputPolicy": MultiInputActorCriticPolicy, } def __init__( self, policy: Union[str, Type[ActorCriticPolicy]], env: Union[GymEnv, str], learning_rate: Union[float, Schedule] = 7e-4, n_steps: int = 5, gamma: float = 0.99, gae_lambda: float = 1.0, ent_coef: float = 0.0, vf_coef: float = 0.5, max_grad_norm: float = 0.5, rms_prop_eps: float = 1e-5, use_rms_prop: bool = True, use_sde: bool = False, sde_sample_freq: int = -1, normalize_advantage: bool = False, tensorboard_log: Optional[str] = None, policy_kwargs: Optional[Dict[str, Any]] = None, verbose: int = 0, seed: Optional[int] = None, device: Union[th.device, str] = "auto", _init_setup_model: bool = True, ): super().__init__( policy, env, learning_rate=learning_rate, n_steps=n_steps, gamma=gamma, gae_lambda=gae_lambda, ent_coef=ent_coef, vf_coef=vf_coef, max_grad_norm=max_grad_norm, use_sde=use_sde, sde_sample_freq=sde_sample_freq, tensorboard_log=tensorboard_log, policy_kwargs=policy_kwargs, verbose=verbose, device=device, seed=seed, _init_setup_model=False, supported_action_spaces=( spaces.Box, spaces.Discrete, spaces.MultiDiscrete, spaces.MultiBinary, ), ) self.normalize_advantage = normalize_advantage # Update optimizer inside the policy if we want to use RMSProp # (original implementation) rather than Adam if use_rms_prop and "optimizer_class" not in self.policy_kwargs: self.policy_kwargs["optimizer_class"] = th.optim.RMSprop self.policy_kwargs["optimizer_kwargs"] = dict(alpha=0.99, eps=rms_prop_eps, weight_decay=0) if _init_setup_model: self._setup_model() def train(self) -> None: """ Update policy using the currently gathered rollout buffer (one gradient step over whole data). """ # Switch to train mode (this affects batch norm / dropout) self.policy.set_training_mode(True) # Update optimizer learning rate self._update_learning_rate(self.policy.optimizer) # This will only loop once (get all data in one go) for rollout_data in self.rollout_buffer.get(batch_size=None): actions = rollout_data.actions if isinstance(self.action_space, spaces.Discrete): # Convert discrete action from float to long actions = actions.long().flatten() values, log_prob, entropy = self.policy.evaluate_actions(rollout_data.observations, actions) values = values.flatten() # Normalize advantage (not present in the original implementation) advantages = rollout_data.advantages if self.normalize_advantage: advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) # Policy gradient loss policy_loss = -(advantages * log_prob).mean() # Value loss using the TD(gae_lambda) target value_loss = F.mse_loss(rollout_data.returns, values) # Entropy loss favor exploration if entropy is None: # Approximate entropy when no analytical form entropy_loss = -th.mean(-log_prob) else: entropy_loss = -th.mean(entropy) loss = policy_loss + self.ent_coef * entropy_loss + self.vf_coef * value_loss # Optimization step self.policy.optimizer.zero_grad() loss.backward() # Clip grad norm th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm) self.policy.optimizer.step()
SelfA2C = TypeVar("SelfA2C", bound="A2C") class A2C(OnPolicyAlgorithm): """ Advantage Actor Critic (A2C) Paper: https://arxiv.org/abs/1602.01783 Code: This implementation borrows code from https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail and and Stable Baselines (https://github.com/hill-a/stable-baselines) Introduction to A2C: https://hackernoon.com/intuitive-rl-intro-to-advantage-actor-critic-a2c-4ff545978752 :param policy: The policy model to use (MlpPolicy, CnnPolicy, ...) :param env: The environment to learn from (if registered in Gym, can be str) :param learning_rate: The learning rate, it can be a function of the current progress remaining (from 1 to 0) :param n_steps: The number of steps to run for each environment per update (i.e. batch size is n_steps * n_env where n_env is number of environment copies running in parallel) :param gamma: Discount factor :param gae_lambda: Factor for trade-off of bias vs variance for Generalized Advantage Estimator Equivalent to classic advantage when set to 1. :param ent_coef: Entropy coefficient for the loss calculation :param vf_coef: Value function coefficient for the loss calculation :param max_grad_norm: The maximum value for the gradient clipping :param rms_prop_eps: RMSProp epsilon. It stabilizes square root computation in denominator of RMSProp update :param use_rms_prop: Whether to use RMSprop (default) or Adam as optimizer :param use_sde: Whether to use generalized State Dependent Exploration (gSDE) instead of action noise exploration (default: False) :param sde_sample_freq: Sample a new noise matrix every n steps when using gSDE Default: -1 (only sample at the beginning of the rollout) :param normalize_advantage: Whether to normalize or not the advantage :param tensorboard_log: the log location for tensorboard (if None, no logging) :param policy_kwargs: additional arguments to be passed to the policy on creation :param verbose: Verbosity level: 0 for no output, 1 for info messages (such as device or wrappers used), 2 for debug messages :param seed: Seed for the pseudo random generators :param device: Device (cpu, cuda, ...) on which the code should be run. Setting it to auto, the code will be run on the GPU if possible. :param _init_setup_model: Whether or not to build the network at the creation of the instance """ policy_aliases: Dict[str, Type[BasePolicy]] = { "MlpPolicy": ActorCriticPolicy, "CnnPolicy": ActorCriticCnnPolicy, "MultiInputPolicy": MultiInputActorCriticPolicy, } def __init__( self, policy: Union[str, Type[ActorCriticPolicy]], env: Union[GymEnv, str], learning_rate: Union[float, Schedule] = 7e-4, n_steps: int = 5, gamma: float = 0.99, gae_lambda: float = 1.0, ent_coef: float = 0.0, vf_coef: float = 0.5, max_grad_norm: float = 0.5, rms_prop_eps: float = 1e-5, use_rms_prop: bool = True, use_sde: bool = False, sde_sample_freq: int = -1, normalize_advantage: bool = False, tensorboard_log: Optional[str] = None, policy_kwargs: Optional[Dict[str, Any]] = None, verbose: int = 0, seed: Optional[int] = None, device: Union[th.device, str] = "auto", _init_setup_model: bool = True, ): super().__init__( policy, env, learning_rate=learning_rate, n_steps=n_steps, gamma=gamma, gae_lambda=gae_lambda, ent_coef=ent_coef, vf_coef=vf_coef, max_grad_norm=max_grad_norm, use_sde=use_sde, sde_sample_freq=sde_sample_freq, tensorboard_log=tensorboard_log, policy_kwargs=policy_kwargs, verbose=verbose, device=device, seed=seed, _init_setup_model=False, supported_action_spaces=( spaces.Box, spaces.Discrete, spaces.MultiDiscrete, spaces.MultiBinary, ), ) self.normalize_advantage = normalize_advantage # Update optimizer inside the policy if we want to use RMSProp # (original implementation) rather than Adam if use_rms_prop and "optimizer_class" not in self.policy_kwargs: self.policy_kwargs["optimizer_class"] = th.optim.RMSprop self.policy_kwargs["optimizer_kwargs"] = dict(alpha=0.99, eps=rms_prop_eps, weight_decay=0) if _init_setup_model: self._setup_model() def train(self) -> None: """ Update policy using the currently gathered rollout buffer (one gradient step over whole data). """ # Switch to train mode (this affects batch norm / dropout) self.policy.set_training_mode(True) # Update optimizer learning rate self._update_learning_rate(self.policy.optimizer) # This will only loop once (get all data in one go) for rollout_data in self.rollout_buffer.get(batch_size=None): actions = rollout_data.actions if isinstance(self.action_space, spaces.Discrete): # Convert discrete action from float to long actions = actions.long().flatten() values, log_prob, entropy = self.policy.evaluate_actions(rollout_data.observations, actions) values = values.flatten() # Normalize advantage (not present in the original implementation) advantages = rollout_data.advantages if self.normalize_advantage: advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) # Policy gradient loss policy_loss = -(advantages * log_prob).mean() # Value loss using the TD(gae_lambda) target value_loss = F.mse_loss(rollout_data.returns, values) # Entropy loss favor exploration if entropy is None: # Approximate entropy when no analytical form entropy_loss = -th.mean(-log_prob) else: entropy_loss = -th.mean(entropy) loss = policy_loss + self.ent_coef * entropy_loss + self.vf_coef * value_loss # Optimization step self.policy.optimizer.zero_grad() loss.backward() # Clip grad norm th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm) self.policy.optimizer.step()
explained_var = explained_variance(self.rollout_buffer.values.flatten(), self.rollout_buffer.returns.flatten())
6
2023-10-28 01:09:21+00:00
16k
zyang1580/CoLLM
minigpt4/runners/runner_base_rec.py
[ { "identifier": "download_cached_file", "path": "minigpt4/common/dist_utils.py", "snippet": "def download_cached_file(url, check_hash=True, progress=False):\n \"\"\"\n Download a file from a URL and cache it locally. If the file already exists, it is not downloaded again.\n If distributed, only...
import datetime import json import logging import os import time import torch import torch.distributed as dist import webdataset as wds from pathlib import Path from minigpt4.common.dist_utils import ( download_cached_file, get_rank, get_world_size, is_main_process, main_process, ) from minigpt4.common.registry import registry from minigpt4.common.utils import is_url from minigpt4.datasets.data_utils import concat_datasets, reorg_datasets_by_split, ChainDataset from minigpt4.datasets.datasets.dataloader_utils import ( IterLoader, MultiIterLoader, PrefetchLoader, ) from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.data import DataLoader, DistributedSampler from minigpt4.runners.runner_base import RunnerBase
11,148
# sampler=sampler, # shuffle=sampler is None and is_train, # collate_fn=collate_fn, # drop_last=True if is_train else False, # ) # loader = PrefetchLoader(loader) # if is_train: # loader = IterLoader(loader, use_distributed=self.use_distributed) # return loader # loaders = [] # for dataset, bsz, is_train, collate_fn in zip( # datasets, batch_sizes, is_trains, collate_fns # ): # if isinstance(dataset, list) or isinstance(dataset, tuple): # if hasattr(dataset[0], 'sample_ratio') and dataset_ratios is None: # dataset_ratios = [d.sample_ratio for d in dataset] # loader = MultiIterLoader( # loaders=[ # _create_loader(d, num_workers, bsz, is_train, collate_fn[i]) # for i, d in enumerate(dataset) # ], # ratios=dataset_ratios, # ) # else: # loader = _create_loader(dataset, num_workers, bsz, is_train, collate_fn) # loaders.append(loader) # return loaders # @main_process # def _save_checkpoint(self, cur_epoch, is_best=False): # """ # Save the checkpoint at the current epoch. # """ # model_no_ddp = self.unwrap_dist_model(self.model) # param_grad_dic = { # k: v.requires_grad for (k, v) in model_no_ddp.named_parameters() # } # state_dict = model_no_ddp.state_dict() # for k in list(state_dict.keys()): # if k in param_grad_dic.keys() and not param_grad_dic[k]: # # delete parameters that do not require gradient # del state_dict[k] # save_obj = { # "model": state_dict, # "optimizer": self.optimizer.state_dict(), # "config": self.config.to_dict(), # "scaler": self.scaler.state_dict() if self.scaler else None, # "epoch": cur_epoch, # } # save_to = os.path.join( # self.output_dir, # "checkpoint_{}.pth".format("best" if is_best else cur_epoch), # ) # logging.info("Saving checkpoint at epoch {} to {}.".format(cur_epoch, save_to)) # torch.save(save_obj, save_to) # def _reload_best_model(self, model): # """ # Load the best checkpoint for evaluation. # """ # checkpoint_path = os.path.join(self.output_dir, "checkpoint_best.pth") # logging.info("Loading checkpoint from {}.".format(checkpoint_path)) # checkpoint = torch.load(checkpoint_path, map_location="cpu") # try: # model.load_state_dict(checkpoint["model"]) # except RuntimeError as e: # logging.warning( # """ # Key mismatch when loading checkpoint. This is expected if only part of the model is saved. # Trying to load the model with strict=False. # """ # ) # model.load_state_dict(checkpoint["model"], strict=False) # return model # def _load_checkpoint(self, url_or_filename): # """ # Resume from a checkpoint. # """ # if is_url(url_or_filename): # cached_file = download_cached_file( # url_or_filename, check_hash=False, progress=True # ) # checkpoint = torch.load(cached_file, map_location=self.device) # elif os.path.isfile(url_or_filename): # checkpoint = torch.load(url_or_filename, map_location=self.device) # else: # raise RuntimeError("checkpoint url or path is invalid") # state_dict = checkpoint["model"] # self.unwrap_dist_model(self.model).load_state_dict(state_dict,strict=False) # self.optimizer.load_state_dict(checkpoint["optimizer"]) # if self.scaler and "scaler" in checkpoint: # self.scaler.load_state_dict(checkpoint["scaler"]) # self.start_epoch = checkpoint["epoch"] + 1 # logging.info("Resume checkpoint from {}".format(url_or_filename)) # @main_process # def log_stats(self, stats, split_name): # if isinstance(stats, dict): # log_stats = {**{f"{split_name}_{k}": v for k, v in stats.items()}} # with open(os.path.join(self.output_dir, "log.txt"), "a") as f: # f.write(json.dumps(log_stats) + "\n") # elif isinstance(stats, list): # pass # @main_process # def log_config(self): # with open(os.path.join(self.output_dir, "log.txt"), "a") as f: # f.write(json.dumps(self.config.to_dict(), indent=4) + "\n")
""" Copyright (c) 2022, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause """ # @registry.register_runner("rec_runner_base") # class RecRunnerBase: # """ # A runner class to train and evaluate a model given a task and datasets. # The runner uses pytorch distributed data parallel by default. Future release # will support other distributed frameworks. # """ # def __init__(self, cfg, task, model, datasets, job_id): # self.config = cfg # self.job_id = job_id # self.task = task # self.datasets = datasets # self._model = model # self._wrapped_model = None # self._device = None # self._optimizer = None # self._scaler = None # self._dataloaders = None # self._lr_sched = None # self.start_epoch = 0 # # self.setup_seeds() # self.setup_output_dir() # @property # def device(self): # if self._device is None: # self._device = torch.device(self.config.run_cfg.device) # return self._device # @property # def use_distributed(self): # return self.config.run_cfg.distributed # @property # def model(self): # """ # A property to get the DDP-wrapped model on the device. # """ # # move model to device # if self._model.device != self.device: # self._model = self._model.to(self.device) # # distributed training wrapper # if self.use_distributed: # if self._wrapped_model is None: # self._wrapped_model = DDP( # self._model, device_ids=[self.config.run_cfg.gpu] # ) # else: # self._wrapped_model = self._model # return self._wrapped_model # @property # def optimizer(self): # # TODO make optimizer class and configurations # if self._optimizer is None: # num_parameters = 0 # p_wd, p_non_wd = [], [] # for n, p in self.model.named_parameters(): # if not p.requires_grad: # continue # frozen weights # print(n) # if p.ndim < 2 or "bias" in n or "ln" in n or "bn" in n: # p_non_wd.append(p) # else: # p_wd.append(p) # num_parameters += p.data.nelement() # logging.info("number of trainable parameters: %d" % num_parameters) # optim_params = [ # { # "params": p_wd, # "weight_decay": float(self.config.run_cfg.weight_decay), # }, # {"params": p_non_wd, "weight_decay": 0}, # ] # beta2 = self.config.run_cfg.get("beta2", 0.999) # self._optimizer = torch.optim.AdamW( # optim_params, # lr=float(self.config.run_cfg.init_lr), # weight_decay=float(self.config.run_cfg.weight_decay), # betas=(0.9, beta2), # ) # return self._optimizer # @property # def scaler(self): # amp = self.config.run_cfg.get("amp", False) # if amp: # if self._scaler is None: # self._scaler = torch.cuda.amp.GradScaler() # return self._scaler # @property # def lr_scheduler(self): # """ # A property to get and create learning rate scheduler by split just in need. # """ # if self._lr_sched is None: # lr_sched_cls = registry.get_lr_scheduler_class(self.config.run_cfg.lr_sched) # # max_epoch = self.config.run_cfg.max_epoch # max_epoch = self.max_epoch # # min_lr = self.config.run_cfg.min_lr # min_lr = self.min_lr # # init_lr = self.config.run_cfg.init_lr # init_lr = self.init_lr # # optional parameters # decay_rate = self.config.run_cfg.get("lr_decay_rate", None) # warmup_start_lr = self.config.run_cfg.get("warmup_lr", -1) # warmup_steps = self.config.run_cfg.get("warmup_steps", 0) # iters_per_epoch = self.config.run_cfg.get("iters_per_epoch", None) # if iters_per_epoch is None: # try: # iters_per_epoch = len(self.dataloaders['train']) # except (AttributeError, TypeError): # iters_per_epoch = 10000 # self._lr_sched = lr_sched_cls( # optimizer=self.optimizer, # max_epoch=max_epoch, # iters_per_epoch=iters_per_epoch, # min_lr=min_lr, # init_lr=init_lr, # decay_rate=decay_rate, # warmup_start_lr=warmup_start_lr, # warmup_steps=warmup_steps, # ) # return self._lr_sched # @property # def dataloaders(self) -> dict: # """ # A property to get and create dataloaders by split just in need. # If no train_dataset_ratio is provided, concatenate map-style datasets and # chain wds.DataPipe datasets separately. Training set becomes a tuple # (ConcatDataset, ChainDataset), both are optional but at least one of them is # required. The resultant ConcatDataset and ChainDataset will be sampled evenly. # If train_dataset_ratio is provided, create a MultiIterLoader to sample # each dataset by ratios during training. # Currently do not support multiple datasets for validation and test. # Returns: # dict: {split_name: (tuples of) dataloader} # """ # if self._dataloaders is None: # # concatenate map-style datasets and chain wds.DataPipe datasets separately # # training set becomes a tuple (ConcatDataset, ChainDataset), both are # # optional but at least one of them is required. The resultant ConcatDataset # # and ChainDataset will be sampled evenly. # logging.info( # "dataset_ratios not specified, datasets will be concatenated (map-style datasets) or chained (webdataset.DataPipeline)." # ) # datasets = reorg_datasets_by_split(self.datasets) # self.datasets = datasets # # self.datasets = concat_datasets(datasets) # # print dataset statistics after concatenation/chaining # for split_name in self.datasets: # if isinstance(self.datasets[split_name], tuple) or isinstance( # self.datasets[split_name], list # ): # # mixed wds.DataPipeline and torch.utils.data.Dataset # num_records = sum( # [ # len(d) # if not type(d) in [wds.DataPipeline, ChainDataset] # else 0 # for d in self.datasets[split_name] # ] # ) # else: # if hasattr(self.datasets[split_name], "__len__"): # # a single map-style dataset # num_records = len(self.datasets[split_name]) # else: # # a single wds.DataPipeline # num_records = -1 # logging.info( # "Only a single wds.DataPipeline dataset, no __len__ attribute." # ) # if num_records >= 0: # logging.info( # "Loaded {} records for {} split from the dataset.".format( # num_records, split_name # ) # ) # # create dataloaders # split_names = sorted(self.datasets.keys()) # datasets = [self.datasets[split] for split in split_names] # is_trains = [split in self.train_splits for split in split_names] # batch_sizes = [ # self.config.run_cfg.batch_size_train # if split == "train" # else self.config.run_cfg.batch_size_eval # for split in split_names # ] # collate_fns = [] # for dataset in datasets: # if isinstance(dataset, tuple) or isinstance(dataset, list): # collate_fns.append([getattr(d, "collater", None) for d in dataset]) # else: # collate_fns.append(getattr(dataset, "collater", None)) # dataloaders = self.create_loaders( # datasets=datasets, # num_workers=self.config.run_cfg.num_workers, # batch_sizes=batch_sizes, # is_trains=is_trains, # collate_fns=collate_fns, # ) # self._dataloaders = {k: v for k, v in zip(split_names, dataloaders)} # return self._dataloaders # @property # def cuda_enabled(self): # return self.device.type == "cuda" # @property # def max_epoch(self): # return int(self.config.run_cfg.max_epoch) # @property # def log_freq(self): # log_freq = self.config.run_cfg.get("log_freq", 50) # return int(log_freq) # @property # def init_lr(self): # return float(self.config.run_cfg.init_lr) # @property # def min_lr(self): # return float(self.config.run_cfg.min_lr) # @property # def accum_grad_iters(self): # return int(self.config.run_cfg.get("accum_grad_iters", 1)) # @property # def valid_splits(self): # valid_splits = self.config.run_cfg.get("valid_splits", []) # if len(valid_splits) == 0: # logging.info("No validation splits found.") # return valid_splits # @property # def test_splits(self): # test_splits = self.config.run_cfg.get("test_splits", []) # return test_splits # @property # def train_splits(self): # train_splits = self.config.run_cfg.get("train_splits", []) # if len(train_splits) == 0: # logging.info("Empty train splits.") # return train_splits # @property # def evaluate_only(self): # """ # Set to True to skip training. # """ # return self.config.run_cfg.evaluate # @property # def use_dist_eval_sampler(self): # return self.config.run_cfg.get("use_dist_eval_sampler", True) # @property # def resume_ckpt_path(self): # return self.config.run_cfg.get("resume_ckpt_path", None) # @property # def train_loader(self): # train_dataloader = self.dataloaders["train"] # return train_dataloader # def setup_output_dir(self): # lib_root = Path(registry.get_path("library_root")) # output_dir = lib_root / self.config.run_cfg.output_dir / self.job_id # result_dir = output_dir / "result" # output_dir.mkdir(parents=True, exist_ok=True) # result_dir.mkdir(parents=True, exist_ok=True) # registry.register_path("result_dir", str(result_dir)) # registry.register_path("output_dir", str(output_dir)) # self.result_dir = result_dir # self.output_dir = output_dir # def train(self): # start_time = time.time() # best_agg_metric = 0 # best_epoch = 0 # self.log_config() # # resume from checkpoint if specified # if not self.evaluate_only and self.resume_ckpt_path is not None: # self._load_checkpoint(self.resume_ckpt_path) # for cur_epoch in range(self.start_epoch, self.max_epoch): # # training phase # if not self.evaluate_only: # logging.info("Start training") # train_stats = self.train_epoch(cur_epoch) # self.log_stats(split_name="train", stats=train_stats) # # evaluation phase # if len(self.valid_splits) > 0: # for split_name in self.valid_splits: # logging.info("Evaluating on {}.".format(split_name)) # val_log = self.eval_epoch( # split_name=split_name, cur_epoch=cur_epoch # ) # if val_log is not None: # if is_main_process(): # assert ( # "agg_metrics" in val_log # ), "No agg_metrics found in validation log." # agg_metrics = val_log["agg_metrics"] # if agg_metrics > best_agg_metric and split_name == "val": # best_epoch, best_agg_metric = cur_epoch, agg_metrics # self._save_checkpoint(cur_epoch, is_best=True) # val_log.update({"best_epoch": best_epoch}) # self.log_stats(val_log, split_name) # else: # # if no validation split is provided, we just save the checkpoint at the end of each epoch. # if not self.evaluate_only: # self._save_checkpoint(cur_epoch, is_best=False) # if self.evaluate_only: # break # if self.config.run_cfg.distributed: # dist.barrier() # # testing phase # test_epoch = "best" if len(self.valid_splits) > 0 else cur_epoch # self.evaluate(cur_epoch=test_epoch, skip_reload=self.evaluate_only) # total_time = time.time() - start_time # total_time_str = str(datetime.timedelta(seconds=int(total_time))) # logging.info("Training time {}".format(total_time_str)) # def evaluate(self, cur_epoch="best", skip_reload=False): # test_logs = dict() # if len(self.test_splits) > 0: # for split_name in self.test_splits: # test_logs[split_name] = self.eval_epoch( # split_name=split_name, cur_epoch=cur_epoch, skip_reload=skip_reload # ) # return test_logs # def train_epoch(self, epoch): # # train # self.model.train() # return self.task.train_epoch( # epoch=epoch, # model=self.model, # data_loader=self.train_loader, # optimizer=self.optimizer, # scaler=self.scaler, # lr_scheduler=self.lr_scheduler, # cuda_enabled=self.cuda_enabled, # log_freq=self.log_freq, # accum_grad_iters=self.accum_grad_iters, # ) # @torch.no_grad() # def eval_epoch(self, split_name, cur_epoch, skip_reload=False): # """ # Evaluate the model on a given split. # Args: # split_name (str): name of the split to evaluate on. # cur_epoch (int): current epoch. # skip_reload_best (bool): whether to skip reloading the best checkpoint. # During training, we will reload the best checkpoint for validation. # During testing, we will use provided weights and skip reloading the best checkpoint . # """ # self.model.eval() # data_loader = self.dataloaders.get(split_name, None) # assert data_loader, "data_loader for split {} is None.".format(split_name) # # TODO In validation, you need to compute loss as well as metrics # # TODO consider moving to model.before_evaluation() # model = self.unwrap_dist_model(self.model) # if not skip_reload and cur_epoch == "best": # model = self._reload_best_model(model) # model.eval() # self.task.before_evaluation( # model=model, # dataset=self.datasets[split_name], # ) # results = self.task.evaluation(model, data_loader) # if results is not None: # return self.task.after_evaluation( # val_result=results, # split_name=split_name, # epoch=cur_epoch, # ) # @torch.no_grad() # def eval_epoch_new(self, split_name, cur_epoch): # """ # Evaluate the model on a given split. # Args: # split_name (str): name of the split to evaluate on. # cur_epoch (int): current epoch. # skip_reload_best (bool): whether to skip reloading the best checkpoint. # During training, we will reload the best checkpoint for validation. # During testing, we will use provided weights and skip reloading the best checkpoint . # """ # data_loader = self.dataloaders.get(split_name, None) # assert data_loader, "data_loader for split {} is None.".format(split_name) # # TODO In validation, you need to compute loss as well as metrics # # TODO consider moving to model.before_evaluation() # model = self.unwrap_dist_model(self.model) # # if not skip_reload and cur_epoch == "best": # # model = self._reload_best_model(model) # model.eval() # self.task.before_evaluation( # model=model, # dataset=self.datasets[split_name], # ) # results = self.task.evaluation(model, data_loader) # return results # # if results is not None: # # return self.task.after_evaluation( # # val_result=results, # # split_name=split_name, # # epoch=cur_epoch, # # ) # def unwrap_dist_model(self, model): # if self.use_distributed: # return model.module # else: # return model # def create_loaders( # self, # datasets, # num_workers, # batch_sizes, # is_trains, # collate_fns, # dataset_ratios=None, # ): # """ # Create dataloaders for training and validation. # """ # def _create_loader(dataset, num_workers, bsz, is_train, collate_fn): # # create a single dataloader for each split # if isinstance(dataset, ChainDataset) or isinstance( # dataset, wds.DataPipeline # ): # # wds.WebdDataset instance are chained together # # webdataset.DataPipeline has its own sampler and collate_fn # loader = iter( # DataLoader( # dataset, # batch_size=bsz, # num_workers=num_workers, # pin_memory=True, # ) # ) # else: # # map-style dataset are concatenated together # # setup distributed sampler # if self.use_distributed: # sampler = DistributedSampler( # dataset, # shuffle=is_train, # num_replicas=get_world_size(), # rank=get_rank(), # ) # if not self.use_dist_eval_sampler: # # e.g. retrieval evaluation # sampler = sampler if is_train else None # else: # sampler = None # loader = DataLoader( # dataset, # batch_size=bsz, # num_workers=num_workers, # pin_memory=True, # sampler=sampler, # shuffle=sampler is None and is_train, # collate_fn=collate_fn, # drop_last=True if is_train else False, # ) # loader = PrefetchLoader(loader) # if is_train: # loader = IterLoader(loader, use_distributed=self.use_distributed) # return loader # loaders = [] # for dataset, bsz, is_train, collate_fn in zip( # datasets, batch_sizes, is_trains, collate_fns # ): # if isinstance(dataset, list) or isinstance(dataset, tuple): # if hasattr(dataset[0], 'sample_ratio') and dataset_ratios is None: # dataset_ratios = [d.sample_ratio for d in dataset] # loader = MultiIterLoader( # loaders=[ # _create_loader(d, num_workers, bsz, is_train, collate_fn[i]) # for i, d in enumerate(dataset) # ], # ratios=dataset_ratios, # ) # else: # loader = _create_loader(dataset, num_workers, bsz, is_train, collate_fn) # loaders.append(loader) # return loaders # @main_process # def _save_checkpoint(self, cur_epoch, is_best=False): # """ # Save the checkpoint at the current epoch. # """ # model_no_ddp = self.unwrap_dist_model(self.model) # param_grad_dic = { # k: v.requires_grad for (k, v) in model_no_ddp.named_parameters() # } # state_dict = model_no_ddp.state_dict() # for k in list(state_dict.keys()): # if k in param_grad_dic.keys() and not param_grad_dic[k]: # # delete parameters that do not require gradient # del state_dict[k] # save_obj = { # "model": state_dict, # "optimizer": self.optimizer.state_dict(), # "config": self.config.to_dict(), # "scaler": self.scaler.state_dict() if self.scaler else None, # "epoch": cur_epoch, # } # save_to = os.path.join( # self.output_dir, # "checkpoint_{}.pth".format("best" if is_best else cur_epoch), # ) # logging.info("Saving checkpoint at epoch {} to {}.".format(cur_epoch, save_to)) # torch.save(save_obj, save_to) # def _reload_best_model(self, model): # """ # Load the best checkpoint for evaluation. # """ # checkpoint_path = os.path.join(self.output_dir, "checkpoint_best.pth") # logging.info("Loading checkpoint from {}.".format(checkpoint_path)) # checkpoint = torch.load(checkpoint_path, map_location="cpu") # try: # model.load_state_dict(checkpoint["model"]) # except RuntimeError as e: # logging.warning( # """ # Key mismatch when loading checkpoint. This is expected if only part of the model is saved. # Trying to load the model with strict=False. # """ # ) # model.load_state_dict(checkpoint["model"], strict=False) # return model # def _load_checkpoint(self, url_or_filename): # """ # Resume from a checkpoint. # """ # if is_url(url_or_filename): # cached_file = download_cached_file( # url_or_filename, check_hash=False, progress=True # ) # checkpoint = torch.load(cached_file, map_location=self.device) # elif os.path.isfile(url_or_filename): # checkpoint = torch.load(url_or_filename, map_location=self.device) # else: # raise RuntimeError("checkpoint url or path is invalid") # state_dict = checkpoint["model"] # self.unwrap_dist_model(self.model).load_state_dict(state_dict,strict=False) # self.optimizer.load_state_dict(checkpoint["optimizer"]) # if self.scaler and "scaler" in checkpoint: # self.scaler.load_state_dict(checkpoint["scaler"]) # self.start_epoch = checkpoint["epoch"] + 1 # logging.info("Resume checkpoint from {}".format(url_or_filename)) # @main_process # def log_stats(self, stats, split_name): # if isinstance(stats, dict): # log_stats = {**{f"{split_name}_{k}": v for k, v in stats.items()}} # with open(os.path.join(self.output_dir, "log.txt"), "a") as f: # f.write(json.dumps(log_stats) + "\n") # elif isinstance(stats, list): # pass # @main_process # def log_config(self): # with open(os.path.join(self.output_dir, "log.txt"), "a") as f: # f.write(json.dumps(self.config.to_dict(), indent=4) + "\n")
@registry.register_runner("rec_runner_base")
5
2023-10-29 12:47:25+00:00
16k
tobagin/whakarere
whakarere/windows/whakarere.py
[ { "identifier": "ConfigManager", "path": "whakarere/managers/config.py", "snippet": "class ConfigManager:\n def __init__(self, window):\n self.window = window\n self.config = {}\n self.config_file_path = os.path.expanduser(\"~/.config/whakarere/config.json\")\n atexit.regi...
import gi from whakarere.managers.config import ConfigManager from whakarere.managers.session import SessionManager from whakarere.managers.whatsapp import WhatsAppSessionManager from whakarere.widgets.titlebar import WindowTitlebarWidget from whakarere.widgets.main_menu import MainMenuButtonWidget from whakarere.pages.session import SessionManagerPage from whakarere.pages.session2 import SessionManagerPage2 from whakarere.windows.account_wizard import AccountWizardWindow from gi.repository import Adw, Gtk, Gdk
11,819
gi.require_version('Gtk', '4.0') gi.require_version('Adw', '1') gi.require_version("Gdk", "4.0") class WhakarereMainWindow(Adw.ApplicationWindow): def __init__(self, app, debug=False, dev=False): super().__init__(application=app) self.app = app self.debug = debug self.dev = dev self.settings = Gtk.Settings.get_default() self.settings.connect("notify::gtk-theme-name", self.on_theme_changed) # Initial CSS application self.update_css_for_theme() # Set the window size and default close behavior self.set_default_size(800, 600) self.set_hide_on_close(True) # Create the config manager and load the config file self.config_manager = ConfigManager(self) self.config_manager.load_config() # Create the session manager and load the sessions self.session_manager = SessionManager(self) self.session_manager.load_sessions() # Create the whatsapp manager and initialize the active sessions self.whatsapp_manager = WhatsAppSessionManager(self) self.whatsapp_manager.initialize() # Create TitleBar Widget self.window_titlebar_widget = Adw.WindowTitle() self.window_titlebar_widget.set_title("Whakarere") self.window_titlebar_widget.set_subtitle("Your Gtk4 Whatsapp Client.") # Create MainMenu Button Widget
gi.require_version('Gtk', '4.0') gi.require_version('Adw', '1') gi.require_version("Gdk", "4.0") class WhakarereMainWindow(Adw.ApplicationWindow): def __init__(self, app, debug=False, dev=False): super().__init__(application=app) self.app = app self.debug = debug self.dev = dev self.settings = Gtk.Settings.get_default() self.settings.connect("notify::gtk-theme-name", self.on_theme_changed) # Initial CSS application self.update_css_for_theme() # Set the window size and default close behavior self.set_default_size(800, 600) self.set_hide_on_close(True) # Create the config manager and load the config file self.config_manager = ConfigManager(self) self.config_manager.load_config() # Create the session manager and load the sessions self.session_manager = SessionManager(self) self.session_manager.load_sessions() # Create the whatsapp manager and initialize the active sessions self.whatsapp_manager = WhatsAppSessionManager(self) self.whatsapp_manager.initialize() # Create TitleBar Widget self.window_titlebar_widget = Adw.WindowTitle() self.window_titlebar_widget.set_title("Whakarere") self.window_titlebar_widget.set_subtitle("Your Gtk4 Whatsapp Client.") # Create MainMenu Button Widget
self.button_settings_menu = MainMenuButtonWidget()
4
2023-10-29 15:46:50+00:00
16k
KHU-VLL/CAST
dataset/datasets.py
[ { "identifier": "TubeMaskingGenerator", "path": "util_tools/masking_generator.py", "snippet": "class TubeMaskingGenerator:\n def __init__(self, input_size, mask_ratio):\n self.frames, self.height, self.width = input_size\n self.num_patches_per_frame = self.height * self.width\n ...
import os from torchvision import transforms from util_tools.transforms import * from util_tools.masking_generator import TubeMaskingGenerator from .kinetics import VideoClsDataset, VideoMAE from .ssv2 import SSVideoClsDataset from .epic import EpicVideoClsDataset
11,175
self.input_std = [0.229, 0.224, 0.225] # IMAGENET_DEFAULT_STD normalize = GroupNormalize(self.input_mean, self.input_std) self.train_augmentation = GroupMultiScaleCrop(args.input_size, [1, .875, .75, .66]) self.transform = transforms.Compose([ self.train_augmentation, Stack(roll=False), ToTorchFormatTensor(div=True), normalize, ]) if args.mask_type == 'tube': self.masked_position_generator = TubeMaskingGenerator( args.window_size, args.mask_ratio ) def __call__(self, images): process_data, _ = self.transform(images) return process_data, self.masked_position_generator() def __repr__(self): repr = "(DataAugmentationForVideoMAE,\n" repr += " transform = %s,\n" % str(self.transform) repr += " Masked position generator = %s,\n" % str(self.masked_position_generator) repr += ")" return repr def build_pretraining_dataset(args): transform = DataAugmentationForVideoMAE(args) dataset = VideoMAE( root=None, setting=args.data_path, video_ext='mp4', is_color=True, modality='rgb', new_length=args.num_frames, new_step=args.sampling_rate, transform=transform, temporal_jitter=False, video_loader=True, use_decord=True, lazy_init=False) print("Data Aug = %s" % str(transform)) return dataset def build_dataset(is_train, test_mode, args): if args.data_set == 'Kinetics-400': mode = None anno_path = args.anno_path if is_train is True: mode = 'train' anno_path = os.path.join(args.anno_path, 'train.csv') elif test_mode is True: mode = 'test' anno_path = os.path.join(args.anno_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.anno_path, 'val.csv') dataset = VideoClsDataset( anno_path=anno_path, data_path=args.data_path, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 400 elif args.data_set == 'SSV2': mode = None anno_path = None if is_train is True: mode = 'train' anno_path = os.path.join(args.anno_path, 'train.csv') elif test_mode is True: mode = 'test' anno_path = os.path.join(args.anno_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.anno_path, 'val.csv') dataset = SSVideoClsDataset( anno_path=anno_path, data_path=args.data_path, mode=mode, clip_len=1, num_segment=args.num_frames, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 174 elif args.data_set == 'EPIC': mode = None anno_path = None if is_train is True: mode = 'train' anno_path = os.path.join(args.anno_path, 'train.csv') elif test_mode is True: mode = 'test' anno_path = os.path.join(args.anno_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.anno_path, 'val.csv')
class DataAugmentationForVideoMAE(object): def __init__(self, args): self.input_mean = [0.485, 0.456, 0.406] # IMAGENET_DEFAULT_MEAN self.input_std = [0.229, 0.224, 0.225] # IMAGENET_DEFAULT_STD normalize = GroupNormalize(self.input_mean, self.input_std) self.train_augmentation = GroupMultiScaleCrop(args.input_size, [1, .875, .75, .66]) self.transform = transforms.Compose([ self.train_augmentation, Stack(roll=False), ToTorchFormatTensor(div=True), normalize, ]) if args.mask_type == 'tube': self.masked_position_generator = TubeMaskingGenerator( args.window_size, args.mask_ratio ) def __call__(self, images): process_data, _ = self.transform(images) return process_data, self.masked_position_generator() def __repr__(self): repr = "(DataAugmentationForVideoMAE,\n" repr += " transform = %s,\n" % str(self.transform) repr += " Masked position generator = %s,\n" % str(self.masked_position_generator) repr += ")" return repr def build_pretraining_dataset(args): transform = DataAugmentationForVideoMAE(args) dataset = VideoMAE( root=None, setting=args.data_path, video_ext='mp4', is_color=True, modality='rgb', new_length=args.num_frames, new_step=args.sampling_rate, transform=transform, temporal_jitter=False, video_loader=True, use_decord=True, lazy_init=False) print("Data Aug = %s" % str(transform)) return dataset def build_dataset(is_train, test_mode, args): if args.data_set == 'Kinetics-400': mode = None anno_path = args.anno_path if is_train is True: mode = 'train' anno_path = os.path.join(args.anno_path, 'train.csv') elif test_mode is True: mode = 'test' anno_path = os.path.join(args.anno_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.anno_path, 'val.csv') dataset = VideoClsDataset( anno_path=anno_path, data_path=args.data_path, mode=mode, clip_len=args.num_frames, frame_sample_rate=args.sampling_rate, num_segment=1, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 400 elif args.data_set == 'SSV2': mode = None anno_path = None if is_train is True: mode = 'train' anno_path = os.path.join(args.anno_path, 'train.csv') elif test_mode is True: mode = 'test' anno_path = os.path.join(args.anno_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.anno_path, 'val.csv') dataset = SSVideoClsDataset( anno_path=anno_path, data_path=args.data_path, mode=mode, clip_len=1, num_segment=args.num_frames, test_num_segment=args.test_num_segment, test_num_crop=args.test_num_crop, num_crop=1 if not test_mode else 3, keep_aspect_ratio=True, crop_size=args.input_size, short_side_size=args.short_side_size, new_height=256, new_width=320, args=args) nb_classes = 174 elif args.data_set == 'EPIC': mode = None anno_path = None if is_train is True: mode = 'train' anno_path = os.path.join(args.anno_path, 'train.csv') elif test_mode is True: mode = 'test' anno_path = os.path.join(args.anno_path, 'val.csv') else: mode = 'validation' anno_path = os.path.join(args.anno_path, 'val.csv')
dataset = EpicVideoClsDataset(
4
2023-10-25 07:07:05+00:00
16k
OpenProteinAI/PoET
scripts/score.py
[ { "identifier": "Uniprot21", "path": "poet/alphabets.py", "snippet": "class Uniprot21(Alphabet):\n def __init__(\n self,\n mask=False,\n include_gap=False,\n include_startstop=False,\n distinct_startstop=False,\n ):\n chars = b\"ARNDCQEGHILKMFPSTWYV\"\n ...
import argparse import itertools import string import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from pathlib import Path from typing import Callable, Optional, Sequence, TypeVar from torch.nn.utils.rnn import pad_sequence from tqdm import tqdm, trange from poet.alphabets import Uniprot21 from poet.fasta import parse_stream from poet.models.modules.packed_sequence import PackedTensorSequences from poet.models.poet import PoET from poet.msa.sampling import MSASampler, NeighborsSampler
11,929
[torch.from_numpy(v).long() for v in this_variants], batch_first=True, padding_value=alphabet.mask_token, ) if this_variants.size(1) < max_variant_length: this_variants = F.pad( this_variants, (0, max_variant_length - this_variants.size(1)), value=alphabet.mask_token, ) assert (this_variants == alphabet.gap_token).sum() == 0 this_variants = this_variants.cuda() logits = model.logits(this_variants[:, :-1], memory, preallocated_memory=True) targets = this_variants[:, 1:] score = -criteria.forward(logits.transpose(1, 2), targets).float().sum(dim=1) logps.append(score.cpu().numpy()) return np.hstack(logps) def get_logps_tiered_fast( msa_sequences: Sequence[np.ndarray], variants: Sequence[np.ndarray], model: PoET, batch_size: int, alphabet: Uniprot21, pbar_position: Optional[int] = None, ) -> np.ndarray: if len(msa_sequences) > 0: segment_sizes = torch.tensor([len(s) for s in msa_sequences]).cuda() msa_sequences: torch.Tensor = torch.cat( [torch.from_numpy(s).long() for s in msa_sequences] ).cuda() memory = model.embed( msa_sequences.unsqueeze(0), segment_sizes.unsqueeze(0), pbar_position=pbar_position, ) else: memory = None return _get_logps_tiered_fast( memory=memory, variants=variants, model=model, batch_size=batch_size, alphabet=alphabet, pbar_position=pbar_position, ) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--ckpt_path", type=str, default="data/poet.ckpt") parser.add_argument( "--msa_a3m_path", type=str, default="data/BLAT_ECOLX_ColabFold_2202.a3m" ) parser.add_argument( "--variants_fasta_path", type=str, default="data/BLAT_ECOLX_Jacquier_2013_variants.fasta", ) parser.add_argument( "--output_npy_path", type=str, default="data/BLAT_ECOLX_Jacquier_2013_variants.npy", ) parser.add_argument("--batch_size", type=int, default=8) parser.add_argument("--seed", type=int, default=188257) parser.add_argument( "--debug", action="store_true", help="run only 1/15 params from the msa sampling and filtering ensemble", ) args = parser.parse_args() args.msa_a3m_path = Path(args.msa_a3m_path) args.variants_fasta_path = Path(args.variants_fasta_path) args.output_npy_path = Path(args.output_npy_path) return args @torch.inference_mode() def main(): args = parse_args() # load model ckpt = torch.load(args.ckpt_path) model = PoET(**ckpt["hyper_parameters"]["model_spec"]["init_args"]) model.load_state_dict( {k.split(".", 1)[1]: v for k, v in ckpt["state_dict"].items()} ) del ckpt model = model.cuda().half().eval() alphabet = Uniprot21( include_gap=True, include_startstop=True, distinct_startstop=True ) jit_warmup(model, alphabet) # get variants to score variants = [ append_startstop(alphabet.encode(v), alphabet=alphabet) for v in get_seqs_from_fastalike(args.variants_fasta_path) ] # process msa msa_sequences = get_seqs_from_fastalike(args.msa_a3m_path) msa = get_encoded_msa_from_a3m_seqs(msa_sequences=msa_sequences, alphabet=alphabet) # score the variants logps = [] if not args.debug: params = list( itertools.product( [6144, 12288, 24576], [1.0, 0.95, 0.90, 0.70, 0.50], ) ) else: params = [(12288, 0.95)] for max_tokens, max_similarity in tqdm(params, desc="ensemble"):
ASCII_LOWERCASE_BYTES = string.ascii_lowercase.encode() PBAR_POSITION = 1 T = TypeVar("T", np.ndarray, torch.Tensor) def append_startstop(x: T, alphabet: Uniprot21) -> T: x_ndim = x.ndim assert x_ndim in {1, 2} if x_ndim == 1: x = x[None, :] if isinstance(x, torch.Tensor): empty_func = torch.empty else: empty_func = np.empty x_ = empty_func((x.shape[0], x.shape[1] + 2), dtype=x.dtype) x_[:, 0] = alphabet.start_token x_[:, -1] = alphabet.stop_token x_[:, 1:-1] = x if x_ndim == 1: x_ = x_.flatten() return x_ def get_seqs_from_fastalike(filepath: Path) -> list[bytes]: return [s for _, s in parse_stream(open(filepath, "rb"), upper=False)] def get_encoded_msa_from_a3m_seqs( msa_sequences: list[bytes], alphabet: Uniprot21 ) -> np.ndarray: return np.vstack( [ alphabet.encode(s.translate(None, delete=ASCII_LOWERCASE_BYTES)) for s in msa_sequences ] ) def sample_msa_sequences( get_sequence_fn: Callable[[int], bytes], sample_idxs: Sequence[int], max_tokens: int, alphabet: Uniprot21, shuffle: bool = True, shuffle_seed: Optional[int] = None, truncate: bool = True, ) -> list[np.ndarray]: assert alphabet.start_token != -1 assert alphabet.stop_token != -1 if not shuffle: assert shuffle_seed is None seqs, total_tokens = [], 0 for idx in sample_idxs: next_sequence = get_sequence_fn(idx) seqs.append(append_startstop(alphabet.encode(next_sequence), alphabet=alphabet)) total_tokens += len(seqs[-1]) if total_tokens > max_tokens: break # shuffle order and truncate to max tokens if shuffle: rng = ( np.random.default_rng(shuffle_seed) if shuffle_seed is not None else np.random ) final_permutation = rng.permutation(len(seqs)) else: final_permutation = np.arange(len(seqs)) final_seqs, total_tokens = [], 0 for seq in [seqs[i] for i in final_permutation]: if truncate and (total_tokens + len(seq) > max_tokens): seq = seq[: max_tokens - total_tokens] total_tokens += len(seq) final_seqs.append(seq) if total_tokens >= max_tokens: break return final_seqs def jit_warmup(embedding_model: PoET, alphabet: Uniprot21): x = b"$WAAAGH*$WAAGW*" segment_sizes = [8, 7] x = alphabet.encode(x) # encode x into the uniprot21 alphabet x = torch.from_numpy(x).long().cuda() segment_sizes = torch.tensor(segment_sizes).long().cuda() _ = embedding_model.embed(x.unsqueeze(0), segment_sizes.unsqueeze(0)) def _get_logps_tiered_fast( memory: Optional[list[PackedTensorSequences]], variants: Sequence[np.ndarray], model: PoET, batch_size: int, alphabet: Uniprot21, pbar_position: Optional[int] = None, ) -> np.ndarray: max_variant_length = max(len(v) for v in variants) memory = model.logits_allocate_memory( memory=memory, batch_size=batch_size, length=max_variant_length - 1, # discount stop token ) criteria = nn.CrossEntropyLoss(ignore_index=alphabet.mask_token, reduction="none") logps = [] if pbar_position is not None: pbar = trange( 0, len(variants), batch_size, desc=f"[{pbar_position}] decoding", leave=False, position=pbar_position, ) else: pbar = range(0, len(variants), batch_size) for start_idx in pbar: this_variants = variants[start_idx : start_idx + batch_size] this_variants = pad_sequence( [torch.from_numpy(v).long() for v in this_variants], batch_first=True, padding_value=alphabet.mask_token, ) if this_variants.size(1) < max_variant_length: this_variants = F.pad( this_variants, (0, max_variant_length - this_variants.size(1)), value=alphabet.mask_token, ) assert (this_variants == alphabet.gap_token).sum() == 0 this_variants = this_variants.cuda() logits = model.logits(this_variants[:, :-1], memory, preallocated_memory=True) targets = this_variants[:, 1:] score = -criteria.forward(logits.transpose(1, 2), targets).float().sum(dim=1) logps.append(score.cpu().numpy()) return np.hstack(logps) def get_logps_tiered_fast( msa_sequences: Sequence[np.ndarray], variants: Sequence[np.ndarray], model: PoET, batch_size: int, alphabet: Uniprot21, pbar_position: Optional[int] = None, ) -> np.ndarray: if len(msa_sequences) > 0: segment_sizes = torch.tensor([len(s) for s in msa_sequences]).cuda() msa_sequences: torch.Tensor = torch.cat( [torch.from_numpy(s).long() for s in msa_sequences] ).cuda() memory = model.embed( msa_sequences.unsqueeze(0), segment_sizes.unsqueeze(0), pbar_position=pbar_position, ) else: memory = None return _get_logps_tiered_fast( memory=memory, variants=variants, model=model, batch_size=batch_size, alphabet=alphabet, pbar_position=pbar_position, ) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--ckpt_path", type=str, default="data/poet.ckpt") parser.add_argument( "--msa_a3m_path", type=str, default="data/BLAT_ECOLX_ColabFold_2202.a3m" ) parser.add_argument( "--variants_fasta_path", type=str, default="data/BLAT_ECOLX_Jacquier_2013_variants.fasta", ) parser.add_argument( "--output_npy_path", type=str, default="data/BLAT_ECOLX_Jacquier_2013_variants.npy", ) parser.add_argument("--batch_size", type=int, default=8) parser.add_argument("--seed", type=int, default=188257) parser.add_argument( "--debug", action="store_true", help="run only 1/15 params from the msa sampling and filtering ensemble", ) args = parser.parse_args() args.msa_a3m_path = Path(args.msa_a3m_path) args.variants_fasta_path = Path(args.variants_fasta_path) args.output_npy_path = Path(args.output_npy_path) return args @torch.inference_mode() def main(): args = parse_args() # load model ckpt = torch.load(args.ckpt_path) model = PoET(**ckpt["hyper_parameters"]["model_spec"]["init_args"]) model.load_state_dict( {k.split(".", 1)[1]: v for k, v in ckpt["state_dict"].items()} ) del ckpt model = model.cuda().half().eval() alphabet = Uniprot21( include_gap=True, include_startstop=True, distinct_startstop=True ) jit_warmup(model, alphabet) # get variants to score variants = [ append_startstop(alphabet.encode(v), alphabet=alphabet) for v in get_seqs_from_fastalike(args.variants_fasta_path) ] # process msa msa_sequences = get_seqs_from_fastalike(args.msa_a3m_path) msa = get_encoded_msa_from_a3m_seqs(msa_sequences=msa_sequences, alphabet=alphabet) # score the variants logps = [] if not args.debug: params = list( itertools.product( [6144, 12288, 24576], [1.0, 0.95, 0.90, 0.70, 0.50], ) ) else: params = [(12288, 0.95)] for max_tokens, max_similarity in tqdm(params, desc="ensemble"):
sampler = MSASampler(
4
2023-10-28 01:30:26+00:00
16k
Transconnectome/SwiFT
interpretation/integrated_gradient.py
[ { "identifier": "SwinTransformer4D", "path": "project/module/models/swin4d_transformer_ver7.py", "snippet": "class SwinTransformer4D(nn.Module):\n \"\"\"\n Swin Transformer based on: \"Liu et al.,\n Swin Transformer: Hierarchical Vision Transformer using Shifted Windows\n <https://arxiv.org/...
import torch import torch.nn as nn import torch.nn.functional as F import os import json import numpy as np import torchvision import matplotlib.pyplot as plt from PIL import Image from tqdm import tqdm from matplotlib.colors import LinearSegmentedColormap from torchvision import models from torchvision import transforms from captum.attr import IntegratedGradients from captum.attr import GradientShap from captum.attr import Occlusion from captum.attr import NoiseTunnel from captum.attr import visualization as viz from matplotlib.colors import LogNorm from project.module.models.swin4d_transformer_ver7 import SwinTransformer4D from project.module.pl_classifier import LitClassifier from project.module.utils.data_module import fMRIDataModule from pathlib import Path
12,871
save_dir = # write path to save_dir jobid = # write project number neptune_project_id = # write project id. ex)user_id/project_name for i in Path(f'SwiFT/output/{neptune_project_id}/RSTOT-{jobid}/').glob('checkpt*'): ckpt_path = i ckpt = torch.load(ckpt_path, map_location='cuda:0' if torch.cuda.is_available() else 'cpu') ckpt['hyper_parameters']['image_path'] = # write path to MNI_to_TRs folder ckpt['hyper_parameters']['default_root_dir'] = # write path to use default_root_dir ckpt['hyper_parameters']['shuffle_time_sequence'] = False ckpt['hyper_parameters']['time_as_channel'] = False ckpt['hyper_parameters']['eval_batch_size'] = 1 args = ckpt['hyper_parameters']
save_dir = # write path to save_dir jobid = # write project number neptune_project_id = # write project id. ex)user_id/project_name for i in Path(f'SwiFT/output/{neptune_project_id}/RSTOT-{jobid}/').glob('checkpt*'): ckpt_path = i ckpt = torch.load(ckpt_path, map_location='cuda:0' if torch.cuda.is_available() else 'cpu') ckpt['hyper_parameters']['image_path'] = # write path to MNI_to_TRs folder ckpt['hyper_parameters']['default_root_dir'] = # write path to use default_root_dir ckpt['hyper_parameters']['shuffle_time_sequence'] = False ckpt['hyper_parameters']['time_as_channel'] = False ckpt['hyper_parameters']['eval_batch_size'] = 1 args = ckpt['hyper_parameters']
model = LitClassifier(**args)
1
2023-10-28 09:26:03+00:00
16k
TheCompAce/ShellSpeak
main.py
[ { "identifier": "VectorDatabase", "path": "modules/vectorDatabase.py", "snippet": "class VectorDatabase:\n def __init__(self, path, name):\n self.path = path\n self.name = name\n self.db_path = os.path.join(path, f'{name}.db')\n self.model_path = os.path.join(path, f'{name...
import json import os import sys import asyncio import json from modules.vectorDatabase import VectorDatabase from datetime import datetime from modules.menus.setup_menu import save_settings, setup_menu from modules.shellSpeak import ShellSpeak from modules.utils import load_settings
11,491
# from modules.vectors import load_faiss_index, build_and_save_faiss_index, load_index_data, needs_index_update def run_async_function(func, *args): asyncio.run(func(*args)) async def start_shell_speak(settings, base_path, vector_db): await main_start(settings, base_path, vector_db) async def main_start(settings, base_path, vector_db): # Initialize VectorDatabase here if needed globally shellSpeak = ShellSpeak(settings, base_path, vector_db) await shellSpeak.run() def main(): base_path = os.path.abspath(".") settings = load_settings(base_path) # FAISS Index check and build prompt if settings.get('use_indexing', False): system_folder_path = os.path.join(base_path, 'system') # history_json_path = os.path.join(system_folder_path, 'history.json') vector_db_path = os.path.join(system_folder_path, 'vector') vector_db = VectorDatabase(path=settings.get('vector_db_path', system_folder_path), name=settings.get('vector_db_name', vector_db_path)) if not os.path.exists(system_folder_path): os.makedirs(system_folder_path) # Check if 'system' folder and 'history.json' exist # if not os.path.exists(system_folder_path) or not os.path.exists(history_json_path): # settings['use_indexing'] = False if vector_db.needs_index_update(): user_decision = input("A new index needs to be built. Do you want to build it now? (yes/no): ") if user_decision.lower() in ['yes', 'y']: print("Building index... (Grab a Coffee.)") vector_db.train_untrained_responses() print("Index built and saved successfully.") settings['last_build_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') save_settings(settings, os.path.join(base_path, 'settings.json')) else: print("Skipping index building.") # Check for command-line arguments if len(sys.argv) > 1 and sys.argv[1] == '/start': run_async_function(start_shell_speak, settings, base_path, vector_db) return # Display menu while True: print("\nMenu:") print("1. Setup") print("2. Run") print("3. Exit") print("-----------------------------------------------------------------") print("(You can also start the script with /start to Start automaticly.)") print("-----------------------------------------------------------------") choice = input("Choose an option: ") if choice == '1':
# from modules.vectors import load_faiss_index, build_and_save_faiss_index, load_index_data, needs_index_update def run_async_function(func, *args): asyncio.run(func(*args)) async def start_shell_speak(settings, base_path, vector_db): await main_start(settings, base_path, vector_db) async def main_start(settings, base_path, vector_db): # Initialize VectorDatabase here if needed globally shellSpeak = ShellSpeak(settings, base_path, vector_db) await shellSpeak.run() def main(): base_path = os.path.abspath(".") settings = load_settings(base_path) # FAISS Index check and build prompt if settings.get('use_indexing', False): system_folder_path = os.path.join(base_path, 'system') # history_json_path = os.path.join(system_folder_path, 'history.json') vector_db_path = os.path.join(system_folder_path, 'vector') vector_db = VectorDatabase(path=settings.get('vector_db_path', system_folder_path), name=settings.get('vector_db_name', vector_db_path)) if not os.path.exists(system_folder_path): os.makedirs(system_folder_path) # Check if 'system' folder and 'history.json' exist # if not os.path.exists(system_folder_path) or not os.path.exists(history_json_path): # settings['use_indexing'] = False if vector_db.needs_index_update(): user_decision = input("A new index needs to be built. Do you want to build it now? (yes/no): ") if user_decision.lower() in ['yes', 'y']: print("Building index... (Grab a Coffee.)") vector_db.train_untrained_responses() print("Index built and saved successfully.") settings['last_build_date'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') save_settings(settings, os.path.join(base_path, 'settings.json')) else: print("Skipping index building.") # Check for command-line arguments if len(sys.argv) > 1 and sys.argv[1] == '/start': run_async_function(start_shell_speak, settings, base_path, vector_db) return # Display menu while True: print("\nMenu:") print("1. Setup") print("2. Run") print("3. Exit") print("-----------------------------------------------------------------") print("(You can also start the script with /start to Start automaticly.)") print("-----------------------------------------------------------------") choice = input("Choose an option: ") if choice == '1':
setup_menu()
1
2023-10-31 23:35:19+00:00
16k
qym7/SparseDiff
sparse_diffusion/diffusion_model_sparse.py
[ { "identifier": "utils", "path": "sparse_diffusion/utils.py", "snippet": "def setup_wandb(cfg):\ndef create_folders(args):\ndef to_dense(x, edge_index, edge_attr, batch, charge):\ndef to_dense_node(x, batch):\ndef to_dense_edge(edge_index, edge_attr, batch, max_num_nodes):\ndef encode_no_edge(E):\ndef t...
import time import os import math import pickle import json import torch import wandb import numpy as np import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl from tqdm import tqdm from models.conv_transformer_model import GraphTransformerConv from diffusion.noise_schedule import ( PredefinedNoiseScheduleDiscrete, MarginalUniformTransition, ) from metrics.train_metrics import TrainLossDiscrete from metrics.abstract_metrics import SumExceptBatchMetric, SumExceptBatchKL, NLL from analysis.visualization import Visualizer from sparse_diffusion import utils from sparse_diffusion.diffusion import diffusion_utils from sparse_diffusion.diffusion.sample_edges_utils import ( get_computational_graph, mask_query_graph_from_comp_graph, sample_non_existing_edge_attr, condensed_to_matrix_index_batch, ) from sparse_diffusion.diffusion.sample_edges import ( sample_query_edges, sample_non_existing_edges_batched, sampled_condensed_indices_uniformly, ) from sparse_diffusion.models.sign_pos_encoder import SignNetNodeEncoder
10,971
def sample_node_edge( self, pred, p_s_and_t_given_0_X, p_s_and_t_given_0_E, node_mask ): _, prob_X = self.sample_node(pred.X, p_s_and_t_given_0_X, node_mask) _, prob_E = self.sample_edge(pred.E, p_s_and_t_given_0_E, node_mask) sampled_s = diffusion_utils.sample_discrete_features( prob_X, prob_E, node_mask=node_mask ) return sampled_s def sample_sparse_node(self, pred_node, p_s_and_t_given_0_X): # Normalize predictions pred_X = F.softmax(pred_node, dim=-1) # N, dx # Dim of the second tensor: N, dx, dx weighted_X = pred_X.unsqueeze(-1) * p_s_and_t_given_0_X # N, dx, dx unnormalized_prob_X = weighted_X.sum(dim=1) # N, dx unnormalized_prob_X[ torch.sum(unnormalized_prob_X, dim=-1) == 0 ] = 1e-5 # TODO: delete/masking? prob_X = unnormalized_prob_X / torch.sum( unnormalized_prob_X, dim=-1, keepdim=True ) # N, dx assert ((prob_X.sum(dim=-1) - 1).abs() < 1e-4).all() X_t = prob_X.multinomial(1)[:, 0] return X_t def sample_sparse_edge(self, pred_edge, p_s_and_t_given_0_E): # Normalize predictions pred_E = F.softmax(pred_edge, dim=-1) # N, d0 # Dim of the second tensor: N, d0, dt-1 weighted_E = pred_E.unsqueeze(-1) * p_s_and_t_given_0_E # N, d0, dt-1 unnormalized_prob_E = weighted_E.sum(dim=1) # N, dt-1 unnormalized_prob_E[torch.sum(unnormalized_prob_E, dim=-1) == 0] = 1e-5 prob_E = unnormalized_prob_E / torch.sum( unnormalized_prob_E, dim=-1, keepdim=True ) assert ((prob_E.sum(dim=-1) - 1).abs() < 1e-4).all() E_t = prob_E.multinomial(1)[:, 0] return E_t def sample_sparse_node_edge( self, pred_node, pred_edge, p_s_and_t_given_0_X, p_s_and_t_given_0_E, pred_charge, p_s_and_t_given_0_charge, ): sampled_node = self.sample_sparse_node(pred_node, p_s_and_t_given_0_X).long() sampled_edge = self.sample_sparse_edge(pred_edge, p_s_and_t_given_0_E).long() if pred_charge.size(-1) > 0: sampled_charge = self.sample_sparse_node( pred_charge, p_s_and_t_given_0_charge ).long() else: sampled_charge = pred_charge return sampled_node, sampled_edge, sampled_charge def sample_p_zs_given_zt(self, s_float, t_float, data): """ Samples from zs ~ p(zs | zt). Only used during sampling. if last_step, return the graph prediction as well """ node = data.node edge_index = data.edge_index edge_attr = data.edge_attr y = data.y charge = data.charge ptr = data.ptr batch = data.batch beta_t = self.noise_schedule(t_normalized=t_float) # (bs, 1) alpha_s_bar = self.noise_schedule.get_alpha_bar(t_normalized=s_float) alpha_t_bar = self.noise_schedule.get_alpha_bar(t_normalized=t_float) # Retrieve transitions matrix Qtb = self.transition_model.get_Qt_bar(alpha_t_bar, self.device) Qsb = self.transition_model.get_Qt_bar(alpha_s_bar, self.device) Qt = self.transition_model.get_Qt(beta_t, self.device) # Prior distribution # (N, dx, dx) p_s_and_t_given_0_X = ( diffusion_utils.compute_sparse_batched_over0_posterior_distribution( input_data=node, batch=batch, Qt=Qt.X, Qsb=Qsb.X, Qtb=Qtb.X ) ) p_s_and_t_given_0_charge = None if self.use_charge: p_s_and_t_given_0_charge = ( diffusion_utils.compute_sparse_batched_over0_posterior_distribution( input_data=charge, batch=batch, Qt=Qt.charge, Qsb=Qsb.charge, Qtb=Qtb.charge, ) ) # prepare sparse information num_nodes = ptr.diff().long() num_edges = (num_nodes * (num_nodes - 1) / 2).long() # If we had one graph, we will iterate on all edges for each step # we also make sure that the non existing edge number remains the same with the training process ( all_condensed_index, all_edge_batch, all_edge_mask,
class DiscreteDenoisingDiffusion(pl.LightningModule): model_dtype = torch.float32 best_val_nll = 1e8 val_counter = 0 start_epoch_time = None val_iterations = None def __init__( self, cfg, dataset_infos, train_metrics, extra_features, domain_features, val_sampling_metrics, test_sampling_metrics, ): super().__init__() self.in_dims = dataset_infos.input_dims self.out_dims = dataset_infos.output_dims self.use_charge = cfg.model.use_charge and self.out_dims.charge > 1 self.node_dist = dataset_infos.nodes_dist self.extra_features = extra_features self.domain_features = domain_features self.sign_net = cfg.model.sign_net if not self.sign_net: cfg.model.sn_hidden_dim = 0 # sparse settings self.edge_fraction = cfg.model.edge_fraction self.autoregressive = cfg.model.autoregressive self.cfg = cfg self.test_variance = cfg.general.test_variance self.dataset_info = dataset_infos self.visualization_tools = Visualizer(dataset_infos) self.name = cfg.general.name self.T = cfg.model.diffusion_steps self.train_loss = TrainLossDiscrete(cfg.model.lambda_train, self.edge_fraction) self.train_metrics = train_metrics self.val_sampling_metrics = val_sampling_metrics self.test_sampling_metrics = test_sampling_metrics # TODO: transform to torchmetrics.MetricCollection self.val_nll = NLL() # self.val_metrics = torchmetrics.MetricCollection([]) self.val_X_kl = SumExceptBatchKL() self.val_E_kl = SumExceptBatchKL() self.val_X_logp = SumExceptBatchMetric() self.val_E_logp = SumExceptBatchMetric() self.best_nll = 1e8 self.best_epoch = 0 # TODO: transform to torchmetrics.MetricCollection self.test_nll = NLL() self.test_X_kl = SumExceptBatchKL() self.test_E_kl = SumExceptBatchKL() self.test_X_logp = SumExceptBatchMetric() self.test_E_logp = SumExceptBatchMetric() if self.use_charge: self.val_charge_kl = SumExceptBatchKL() self.val_charge_logp = SumExceptBatchMetric() self.test_charge_kl = SumExceptBatchKL() self.test_charge_logp = SumExceptBatchMetric() self.model = GraphTransformerConv( n_layers=cfg.model.n_layers, input_dims=self.in_dims, hidden_dims=cfg.model.hidden_dims, output_dims=self.out_dims, sn_hidden_dim=cfg.model.sn_hidden_dim, output_y=cfg.model.output_y, dropout=cfg.model.dropout ) # whether to use sign net if self.sign_net and cfg.model.extra_features == "all": self.sign_net = SignNetNodeEncoder( dataset_infos, cfg.model.sn_hidden_dim, cfg.model.num_eigenvectors ) # whether to use scale layers self.scaling_layer = cfg.model.scaling_layer ( self.node_scaling_layer, self.edge_scaling_layer, self.graph_scaling_layer, ) = self.get_scaling_layers() self.noise_schedule = PredefinedNoiseScheduleDiscrete( cfg.model.diffusion_noise_schedule, timesteps=cfg.model.diffusion_steps ) # Marginal transition node_types = self.dataset_info.node_types.float() x_marginals = node_types / torch.sum(node_types) edge_types = self.dataset_info.edge_types.float() e_marginals = edge_types / torch.sum(edge_types) if not self.use_charge: charge_marginals = node_types.new_zeros(0) else: charge_marginals = ( self.dataset_info.charge_types * node_types[:, None] ).sum(dim=0) print( f"Marginal distribution of the classes: {x_marginals} for nodes, {e_marginals} for edges" ) self.transition_model = MarginalUniformTransition( x_marginals=x_marginals, e_marginals=e_marginals, y_classes=self.out_dims.y, charge_marginals=charge_marginals, ) self.limit_dist = utils.PlaceHolder( X=x_marginals, E=e_marginals, y=torch.ones(self.out_dims.y) / self.out_dims.y, charge=charge_marginals, ) self.save_hyperparameters(ignore=["train_metrics", "sampling_metrics"]) self.log_every_steps = cfg.general.log_every_steps self.number_chain_steps = cfg.general.number_chain_steps def training_step(self, data, i): # The above code is using the Python debugger module `pdb` to set a breakpoint at a specific # line of code. When the code is executed, it will pause at that line and allow you to # interactively debug the program. if data.edge_index.numel() == 0: print("Found a batch with no edges. Skipping.") return # Map discrete classes to one hot encoding data = self.dataset_info.to_one_hot(data) start_time = time.time() sparse_noisy_data = self.apply_sparse_noise(data) if hasattr(self, "apply_noise_time"): self.apply_noise_time.append(round(time.time() - start_time, 2)) # Sample the query edges and build the computational graph = union(noisy graph, query edges) start_time = time.time() # print(data.ptr.diff()) triu_query_edge_index, _ = sample_query_edges( num_nodes_per_graph=data.ptr.diff(), edge_proportion=self.edge_fraction ) query_mask, comp_edge_index, comp_edge_attr = get_computational_graph( triu_query_edge_index=triu_query_edge_index, clean_edge_index=sparse_noisy_data["edge_index_t"], clean_edge_attr=sparse_noisy_data["edge_attr_t"], ) # pass sparse comp_graph to dense comp_graph for ease calculation sparse_noisy_data["comp_edge_index_t"] = comp_edge_index sparse_noisy_data["comp_edge_attr_t"] = comp_edge_attr self.sample_query_time.append(round(time.time() - start_time, 2)) sparse_pred = self.forward(sparse_noisy_data) # Compute the loss on the query edges only sparse_pred.edge_attr = sparse_pred.edge_attr[query_mask] sparse_pred.edge_index = comp_edge_index[:, query_mask] # mask true label for query edges # We have the true edge index at time 0, and the query edge index at time t. This function # merge the query edges and edge index at time 0, delete repeated one, and retune the mask # for the true attr of query edges start_time = time.time() ( query_mask2, true_comp_edge_attr, true_comp_edge_index, ) = mask_query_graph_from_comp_graph( triu_query_edge_index=triu_query_edge_index, edge_index=data.edge_index, edge_attr=data.edge_attr, num_classes=self.out_dims.E, ) query_true_edge_attr = true_comp_edge_attr[query_mask2] assert ( true_comp_edge_index[:, query_mask2] - sparse_pred.edge_index == 0 ).all() self.query_count.append(len(query_true_edge_attr)) true_data = utils.SparsePlaceHolder( node=data.x, charge=data.charge, edge_attr=query_true_edge_attr, edge_index=sparse_pred.edge_index, y=data.y, batch=data.batch, ) true_data.collapse() # Map one-hot to discrete class self.coalesce_time.append(round(time.time() - start_time, 2)) # Loss calculation start_time = time.time() loss = self.train_loss.forward( pred=sparse_pred, true_data=true_data, log=i % self.log_every_steps == 0 ) self.train_metrics( pred=sparse_pred, true_data=true_data, log=i % self.log_every_steps == 0 ) self.loss_time.append(round(time.time() - start_time, 2)) return {"loss": loss} def on_fit_start(self) -> None: print( f"Size of the input features:" f" X {self.in_dims.X}, E {self.in_dims.E}, charge {self.in_dims.charge}, y {self.in_dims.y}" ) if self.local_rank == 0: utils.setup_wandb( self.cfg ) # Initialize wandb only on one process to log metrics only once def on_train_epoch_start(self) -> None: self.print("Starting train epoch...") self.start_epoch_time = time.time() self.train_loss.reset() self.train_metrics.reset() self.query_count = [] self.apply_noise_time = [] self.extra_data_time = [] self.forward_time = [] self.sample_query_time = [] self.coalesce_time = [] self.loss_time = [] self.cycle_time = [] self.eigen_time = [] def on_train_epoch_end(self) -> None: epoch_loss = self.train_loss.log_epoch_metrics() self.print( f"Epoch {self.current_epoch} finished: X: {epoch_loss['train_epoch/x_CE'] :.2f} -- " f"E: {epoch_loss['train_epoch/E_CE'] :.2f} --" f"charge: {epoch_loss['train_epoch/charge_CE'] :.2f} --" f"y: {epoch_loss['train_epoch/y_CE'] :.2f}" ) self.train_metrics.log_epoch_metrics() if wandb.run: wandb.log({"epoch": self.current_epoch}, commit=False) def on_validation_epoch_start(self) -> None: val_metrics = [self.val_nll, self.val_X_kl, self.val_E_kl, self.val_X_logp, self.val_E_logp, self.val_sampling_metrics] if self.use_charge: val_metrics.extend([self.val_charge_kl, self.val_charge_logp]) for metric in val_metrics: metric.reset() def validation_step(self, data, i): data = self.dataset_info.to_one_hot(data) sparse_noisy_data = self.apply_sparse_noise(data) # Sample the query edges and build the computational graph = union(noisy graph, query edges) triu_query_edge_index, _ = sample_query_edges( num_nodes_per_graph=data.ptr.diff(), edge_proportion=self.edge_fraction ) _, comp_edge_index, comp_edge_attr = get_computational_graph( triu_query_edge_index=triu_query_edge_index, clean_edge_index=sparse_noisy_data["edge_index_t"], clean_edge_attr=sparse_noisy_data["edge_attr_t"] ) # pass sparse comp_graph to dense comp_graph for ease calculation sparse_noisy_data["comp_edge_index_t"] = comp_edge_index sparse_noisy_data["comp_edge_attr_t"] = comp_edge_attr sparse_pred = self.forward(sparse_noisy_data) # to dense dense_pred, node_mask = utils.to_dense( x=sparse_pred.node, edge_index=sparse_pred.edge_index, edge_attr=sparse_pred.edge_attr, batch=sparse_pred.batch, charge=sparse_pred.charge, ) dense_original, _ = utils.to_dense( x=data.x, edge_index=data.edge_index, edge_attr=data.edge_attr, batch=data.batch, charge=data.charge, ) noisy_data = utils.densify_noisy_data(sparse_noisy_data) nll = self.compute_val_loss( dense_pred, noisy_data, dense_original.X, dense_original.E, dense_original.y, node_mask, charge=dense_original.charge, test=False, ) return {"loss": nll} def on_validation_epoch_end(self) -> None: metrics = [ self.val_nll.compute(), self.val_X_kl.compute() * self.T, self.val_E_kl.compute() * self.T, self.val_X_logp.compute(), self.val_E_logp.compute(), ] if self.use_charge: metrics += [ self.val_charge_kl.compute() * self.T, self.val_charge_logp.compute(), ] else: metrics += [-1, -1] if self.val_nll.compute() < self.best_nll: self.best_epoch = self.current_epoch self.best_nll = self.val_nll.compute() metrics += [self.best_epoch, self.best_nll] if wandb.run: wandb.log( { "val/epoch_NLL": metrics[0], "val/X_kl": metrics[1], "val/E_kl": metrics[2], "val/X_logp": metrics[3], "val/E_logp": metrics[4], "val/charge_kl": metrics[5], "val/charge_logp": metrics[6], "val/best_nll_epoch": metrics[7], "val/best_nll": metrics[8], }, commit=False, ) self.print( f"Epoch {self.current_epoch}: Val NLL {metrics[0] :.2f} -- Val Atom type KL {metrics[1] :.2f} -- ", f"Val Edge type KL: {metrics[2] :.2f}", ) # Log val nll with default Lightning logger, so it can be monitored by checkpoint callback val_nll = metrics[0] self.log("val/epoch_NLL", val_nll, sync_dist=True) if val_nll < self.best_val_nll: self.best_val_nll = val_nll self.print( "Val loss: %.4f \t Best val loss: %.4f\n" % (val_nll, self.best_val_nll) ) self.val_counter += 1 print("Starting to sample") if self.val_counter % self.cfg.general.sample_every_val == 0: start = time.time() samples_left_to_generate = self.cfg.general.samples_to_generate samples_left_to_save = self.cfg.general.samples_to_save chains_left_to_save = self.cfg.general.chains_to_save # multi gpu operation samples_left_to_generate = math.ceil(samples_left_to_generate / max(self._trainer.num_devices, 1)) self.print( f"Samples to generate: {samples_left_to_generate} for each of the {max(self._trainer.num_devices, 1)} devices" ) print(f"Sampling start on GR{self.global_rank}") print('multi-gpu metrics for uniqueness is not accurate in the validation step.') generated_graphs = [] ident = 0 while samples_left_to_generate > 0: bs = self.cfg.train.batch_size * 2 to_generate = min(samples_left_to_generate, bs) to_save = min(samples_left_to_save, bs) chains_save = min(chains_left_to_save, bs) sampled_batch = self.sample_batch( batch_id=ident, batch_size=to_generate, save_final=to_save, keep_chain=chains_save, number_chain_steps=self.number_chain_steps, ) generated_graphs.append(sampled_batch) ident += to_generate samples_left_to_save -= to_save samples_left_to_generate -= to_generate chains_left_to_save -= chains_save generated_graphs = utils.concat_sparse_graphs(generated_graphs) print( f"Sampled {generated_graphs.batch.max().item()+1} batches on local rank {self.local_rank}. ", "Sampling took {time.time() - start:.2f} seconds\n" ) print("Computing sampling metrics...") self.val_sampling_metrics.compute_all_metrics( generated_graphs, self.current_epoch, local_rank=self.local_rank ) def on_test_epoch_start(self) -> None: print("Starting test...") if self.local_rank == 0: utils.setup_wandb( self.cfg ) # Initialize wandb only on one process to log metrics only once test_metrics = [self.test_nll, self.test_X_kl, self.test_E_kl, self.test_X_logp, self.test_E_logp, self.test_sampling_metrics] if self.use_charge: test_metrics.extend([self.test_charge_kl, self.test_charge_logp]) for metric in test_metrics: metric.reset() def test_step(self, data, i): pass def on_test_epoch_end(self) -> None: """Measure likelihood on a test set and compute stability metrics.""" if self.cfg.general.generated_path: self.print("Loading generated samples...") samples = np.load(self.cfg.general.generated_path) with open(self.cfg.general.generated_path, "rb") as f: samples = pickle.load(f) else: samples_left_to_generate = self.cfg.general.final_model_samples_to_generate samples_left_to_save = self.cfg.general.final_model_samples_to_save chains_left_to_save = self.cfg.general.final_model_chains_to_save # multi gpu operation samples_left_to_generate = math.ceil(samples_left_to_generate / max(self._trainer.num_devices, 1)) self.print( f"Samples to generate: {samples_left_to_generate} for each of the {max(self._trainer.num_devices, 1)} devices" ) print(f"Sampling start on GR{self.global_rank}") samples = [] id = 0 while samples_left_to_generate > 0: print( f"Samples left to generate: {samples_left_to_generate}/" f"{self.cfg.general.final_model_samples_to_generate}", end="", flush=True, ) bs = self.cfg.train.batch_size * 2 to_generate = min(samples_left_to_generate, bs) to_save = min(samples_left_to_save, bs) chains_save = min(chains_left_to_save, bs) sampled_batch = self.sample_batch( batch_id=id, batch_size=to_generate, num_nodes=None, save_final=to_save, keep_chain=chains_save, number_chain_steps=self.number_chain_steps, ) samples.append(sampled_batch) id += to_generate samples_left_to_save -= to_save samples_left_to_generate -= to_generate chains_left_to_save -= chains_save print("Saving the generated graphs") samples = utils.concat_sparse_graphs(samples) filename = f"generated_samples1.txt" # Save the samples list as pickle to a file that depends on the local rank # This is needed to avoid overwriting the same file on different GPUs with open(f"generated_samples_rank{self.local_rank}.pkl", "wb") as f: pickle.dump(samples, f) # This line is used to sync between gpus self._trainer.strategy.barrier() for i in range(2, 10): if os.path.exists(filename): filename = f"generated_samples{i}.txt" else: break with open(filename, "w") as f: for i in range(samples.batch.max().item() + 1): atoms = samples.node[samples.batch == i] f.write(f"N={atoms.shape[0]}\n") atoms = atoms.tolist() f.write("X: \n") for at in atoms: f.write(f"{at} ") f.write("\n") f.write("E: \n") bonds = samples.edge_attr[samples.batch[samples.edge_index[0]] == i] for bond in bonds: f.write(f"{bond} ") f.write("\n") print("Saved.") print("Computing sampling metrics...") # Load the pickles of the other GPUs samples = [] for i in range(self._trainer.num_devices): with open(f"generated_samples_rank{i}.pkl", "rb") as f: samples.append(pickle.load(f)) samples = utils.concat_sparse_graphs(samples) print('saving all samples') with open(f"generated_samples.pkl", "wb") as f: pickle.dump(samples, f) if self.test_variance == 1: to_log, _ = self.test_sampling_metrics.compute_all_metrics( samples, self.current_epoch, self.local_rank ) # save results for testing print('saving results for testing') current_path = os.getcwd() res_path = os.path.join( current_path, f"test_epoch{self.current_epoch}.json", ) with open(res_path, 'w') as file: # Convert the dictionary to a JSON string and write it to the file json.dump(to_log, file) else: to_log = {} for i in range(self.test_variance): start_idx = int(self.cfg.general.final_model_samples_to_generate / self.test_variance * i) end_idx = int(self.cfg.general.final_model_samples_to_generate / self.test_variance * (i + 1)) cur_samples = utils.split_samples(samples, start_idx, end_idx) cur_to_log, _ = self.test_sampling_metrics.compute_all_metrics(cur_samples, self.current_epoch, self.local_rank) if i == 0: to_log = {i: [cur_to_log[i]] for i in cur_to_log} else: to_log = {i: to_log[i].append(cur_to_log[i]) for i in cur_to_log} # get the variance and mean value of the metrics final_to_log = {i: [np.mean(i), np.var(i)] for i in to_log} to_log.update(final_to_log) # save results for testing print('saving results for testing') current_path = os.getcwd() res_path = os.path.join( current_path, f"test_epoch{self.current_epoch}_fold{self.test_variance}.json", ) with open(res_path, 'w') as file: # Convert the dictionary to a JSON string and write it to the file json.dump(to_log, file) print("Test sampling metrics computed.") def apply_sparse_noise(self, data): """Sample noise and apply it to the data.""" bs = int(data.batch.max() + 1) t_int = torch.randint( 1, self.T + 1, size=(bs, 1), device=self.device ).float() # (bs, 1) s_int = t_int - 1 t_float = t_int / self.T s_float = s_int / self.T # beta_t and alpha_s_bar are used for denoising/loss computation beta_t = self.noise_schedule(t_normalized=t_float) # (bs, 1) alpha_s_bar = self.noise_schedule.get_alpha_bar(t_normalized=s_float) # (bs, 1) alpha_t_bar = self.noise_schedule.get_alpha_bar(t_normalized=t_float) # (bs, 1) Qtb = self.transition_model.get_Qt_bar( alpha_t_bar, device=self.device ) # (bs, dx_in, dx_out), (bs, de_in, de_out) assert (abs(Qtb.X.sum(dim=2) - 1.0) < 1e-4).all(), Qtb.X.sum(dim=2) - 1 assert (abs(Qtb.E.sum(dim=2) - 1.0) < 1e-4).all() # Compute transition probabilities # get charge distribution if self.use_charge: prob_charge = data.charge.unsqueeze(1) @ Qtb.charge[data.batch] charge_t = prob_charge.squeeze(1).multinomial(1).flatten() # (N, ) charge_t = F.one_hot(charge_t, num_classes=self.out_dims.charge) else: charge_t = data.charge # Diffuse sparse nodes and sample sparse node labels probN = data.x.unsqueeze(1) @ Qtb.X[data.batch] # (N, dx) node_t = probN.squeeze(1).multinomial(1).flatten() # (N, ) # count node numbers and edge numbers for existing edges for each graph num_nodes = data.ptr.diff().long() batch_edge = data.batch[data.edge_index[0]] num_edges = torch.zeros(num_nodes.shape).to(self.device) unique, counts = torch.unique(batch_edge, sorted=True, return_counts=True) num_edges[unique] = counts.float() # count number of non-existing edges for each graph num_neg_edge = ((num_nodes - 1) * num_nodes - num_edges) / 2 # (bs, ) # Step1: diffuse on existing edges # get edges defined in the top triangle of the adjacency matrix dir_edge_index, dir_edge_attr = utils.undirected_to_directed( data.edge_index, data.edge_attr ) batch_edge = data.batch[dir_edge_index[0]] batch_Qtb = Qtb.E[batch_edge] probE = dir_edge_attr.unsqueeze(1) @ batch_Qtb dir_edge_attr = probE.squeeze(1).multinomial(1).flatten() # Step2: diffuse on non-existing edges # get number of new edges according to Qtb emerge_prob = Qtb.E[:, 0, 1:].sum(-1) # (bs, ) num_emerge_edges = ( torch.distributions.binomial.Binomial(num_neg_edge, emerge_prob) .sample() .int() ) # combine existing and non-existing edges (both are directed, i.e. triu) if num_emerge_edges.max() > 0: # sample non-existing edges neg_edge_index = sample_non_existing_edges_batched( num_edges_to_sample=num_emerge_edges, existing_edge_index=dir_edge_index, num_nodes=num_nodes, batch=data.batch, ) neg_edge_attr = sample_non_existing_edge_attr( query_edges_dist_batch=Qtb.E[:, 0, 1:], num_edges_to_sample=num_emerge_edges, ) E_t_attr = torch.hstack([dir_edge_attr, neg_edge_attr]) E_t_index = torch.hstack([dir_edge_index, neg_edge_index]) else: E_t_attr = dir_edge_attr E_t_index = dir_edge_index # mask non-existing edges mask = E_t_attr != 0 E_t_attr = E_t_attr[mask] E_t_index = E_t_index[:, mask] E_t_index, E_t_attr = utils.to_undirected(E_t_index, E_t_attr) E_t_attr = F.one_hot(E_t_attr, num_classes=self.out_dims.E) node_t = F.one_hot(node_t, num_classes=self.out_dims.X) sparse_noisy_data = { "t_int": t_int, "t_float": t_float, "beta_t": beta_t, "alpha_s_bar": alpha_s_bar, "alpha_t_bar": alpha_t_bar, "node_t": node_t, "edge_index_t": E_t_index, "edge_attr_t": E_t_attr, "comp_edge_index_t": None, "comp_edge_attr_t": None, # computational graph "y_t": data.y, "batch": data.batch, "ptr": data.ptr, "charge_t": charge_t, } return sparse_noisy_data def compute_val_loss(self, pred, noisy_data, X, E, y, node_mask, charge, test): """Computes an estimator for the variational lower bound. pred: (batch_size, n, total_features) noisy_data: dict X, E, y : (bs, n, dx), (bs, n, n, de), (bs, dy) node_mask : (bs, n) Output: nll (size 1) """ t = noisy_data["t_float"] # 1. N = node_mask.sum(1).long() log_pN = self.node_dist.log_prob(N) # 2. The KL between q(z_T | x) and p(z_T) = Uniform(1/num_classes). Should be close to zero. kl_prior = self.kl_prior(X, E, node_mask, charge=charge) # 3. Diffusion loss loss_all_t = self.compute_Lt( X, E, y, charge, pred, noisy_data, node_mask, test=test ) # Combine terms nlls = - log_pN + kl_prior + loss_all_t assert (~nlls.isnan()).all(), f"NLLs contain NaNs: {nlls}" assert len(nlls.shape) == 1, f"{nlls.shape} has more than only batch dim." # Update NLL metric object and return batch nll nll = (self.test_nll if test else self.val_nll)(nlls) # Average over the batch if wandb.run: wandb.log( { "kl prior": kl_prior.mean(), "Estimator loss terms": loss_all_t.mean(), "log_pn": log_pN.mean(), "val_nll": nll, "epoch": self.current_epoch }, commit=False, ) return nll def kl_prior(self, X, E, node_mask, charge): """Computes the KL between q(z1 | x) and the prior p(z1) = Normal(0, 1). This is essentially a lot of work for something that is in practice negligible in the loss. However, you compute it so that you see it when you've made a mistake in your noise schedule. """ # Compute the last alpha value, alpha_T. ones = torch.ones((X.size(0), 1), device=X.device) Ts = self.T * ones alpha_t_bar = self.noise_schedule.get_alpha_bar(t_int=Ts) # (bs, 1) Qtb = self.transition_model.get_Qt_bar(alpha_t_bar, self.device) # Compute transition probabilities probX = X @ Qtb.X # (bs, n, dx_out) probE = E @ Qtb.E.unsqueeze(1) # (bs, n, n, de_out) assert probX.shape == X.shape bs, n, _ = probX.shape limit_X = self.limit_dist.X[None, None, :].expand(bs, n, -1).type_as(probX) limit_E = ( self.limit_dist.E[None, None, None, :].expand(bs, n, n, -1).type_as(probE) ) if self.use_charge: prob_charge = charge @ Qtb.charge # (bs, n, de_out) limit_charge = ( self.limit_dist.charge[None, None, :] .expand(bs, n, -1) .type_as(prob_charge) ) limit_charge = limit_charge.clone() else: prob_charge = limit_charge = None # Make sure that masked rows do not contribute to the loss ( limit_dist_X, limit_dist_E, probX, probE, limit_dist_charge, prob_charge, ) = diffusion_utils.mask_distributions( true_X=limit_X.clone(), true_E=limit_E.clone(), pred_X=probX, pred_E=probE, node_mask=node_mask, true_charge=limit_charge, pred_charge=prob_charge, ) kl_distance_X = F.kl_div( input=probX.log(), target=limit_dist_X, reduction="none" ) kl_distance_E = F.kl_div( input=probE.log(), target=limit_dist_E, reduction="none" ) # not all edges are used for loss calculation E_mask = torch.logical_or( kl_distance_E.sum(-1).isnan(), kl_distance_E.sum(-1).isinf() ) kl_distance_E[E_mask] = 0 X_mask = torch.logical_or( kl_distance_X.sum(-1).isnan(), kl_distance_X.sum(-1).isinf() ) kl_distance_X[X_mask] = 0 loss = diffusion_utils.sum_except_batch( kl_distance_X ) + diffusion_utils.sum_except_batch(kl_distance_E) # The above code is using the Python debugger module `pdb` to set a breakpoint in the code. # When the code is executed, it will pause at this line and allow you to interactively debug # the program. if self.use_charge: kl_distance_charge = F.kl_div( input=prob_charge.log(), target=limit_dist_charge, reduction="none" ) kl_distance_charge[X_mask] = 0 loss = loss + diffusion_utils.sum_except_batch(kl_distance_charge) assert (~loss.isnan()).any() return loss def compute_Lt(self, X, E, y, charge, pred, noisy_data, node_mask, test): pred_probs_X = F.softmax(pred.X, dim=-1) pred_probs_E = F.softmax(pred.E, dim=-1) if self.use_charge: pred_probs_charge = F.softmax(pred.charge, dim=-1) else: pred_probs_charge = None charge = None Qtb = self.transition_model.get_Qt_bar(noisy_data["alpha_t_bar"], self.device) Qsb = self.transition_model.get_Qt_bar(noisy_data["alpha_s_bar"], self.device) Qt = self.transition_model.get_Qt(noisy_data["beta_t"], self.device) # Compute distributions to compare with KL bs, n, d = X.shape prob_true = diffusion_utils.posterior_distributions( X=X, E=E, X_t=noisy_data["X_t"], E_t=noisy_data["E_t"], charge=charge, charge_t=noisy_data["charge_t"], y_t=noisy_data["y_t"], Qt=Qt, Qsb=Qsb, Qtb=Qtb, ) prob_true.E = prob_true.E.reshape((bs, n, n, -1)) prob_pred = diffusion_utils.posterior_distributions( X=pred_probs_X, E=pred_probs_E, X_t=noisy_data["X_t"], E_t=noisy_data["E_t"], charge=pred_probs_charge, charge_t=noisy_data["charge_t"], y_t=noisy_data["y_t"], Qt=Qt, Qsb=Qsb, Qtb=Qtb, ) prob_pred.E = prob_pred.E.reshape((bs, n, n, -1)) # Reshape and filter masked rows ( prob_true_X, prob_true_E, prob_pred.X, prob_pred.E, prob_true.charge, prob_pred.charge, ) = diffusion_utils.mask_distributions( true_X=prob_true.X, true_E=prob_true.E, pred_X=prob_pred.X, pred_E=prob_pred.E, node_mask=node_mask, true_charge=prob_true.charge, pred_charge=prob_pred.charge, ) kl_x = (self.test_X_kl if test else self.val_X_kl)(prob_true_X, torch.log(prob_pred.X)) kl_e = (self.test_E_kl if test else self.val_E_kl)(prob_true_E, torch.log(prob_pred.E)) assert (~(kl_x + kl_e).isnan()).any() loss = kl_x + kl_e if self.use_charge: kl_charge = (self.test_charge_kl if test else self.val_charge_kl)( prob_true.charge, torch.log(prob_pred.charge) ) assert (~(kl_charge).isnan()).any() loss = loss + kl_charge return self.T * loss def reconstruction_logp(self, t, X, E, node_mask, charge): # Compute noise values for t = 0. t_zeros = torch.zeros_like(t) beta_0 = self.noise_schedule(t_zeros) Q0 = self.transition_model.get_Qt(beta_t=beta_0, device=self.device) probX0 = X @ Q0.X # (bs, n, dx_out) probE0 = E @ Q0.E.unsqueeze(1) # (bs, n, n, de_out) prob_charge0 = None if self.use_charge: prob_charge0 = charge @ Q0.charge sampled0 = diffusion_utils.sample_discrete_features( probX=probX0, probE=probE0, node_mask=node_mask, prob_charge=prob_charge0 ) X0 = F.one_hot(sampled0.X, num_classes=self.out_dims.X).float() E0 = F.one_hot(sampled0.E, num_classes=self.out_dims.E).float() y0 = sampled0.y assert (X.shape == X0.shape) and (E.shape == E0.shape) charge0 = X0.new_zeros((*X0.shape[:-1], 0)) if self.use_charge: charge0 = F.one_hot( sampled0.charge, num_classes=self.out_dims.charge ).float() sampled_0 = utils.PlaceHolder(X=X0, E=E0, y=y0, charge=charge0).mask(node_mask) # Predictions noisy_data = { "X_t": sampled_0.X, "E_t": sampled_0.E, "y_t": sampled_0.y, "node_mask": node_mask, "t_int": torch.zeros((X0.shape[0], 1), dtype=torch.long).to(self.device), "t_float": torch.zeros((X0.shape[0], 1), dtype=torch.float).to(self.device), "charge_t": sampled_0.charge, } sparse_noisy_data = utils.to_sparse( noisy_data["X_t"], noisy_data["E_t"], noisy_data["y_t"], node_mask, charge=noisy_data["charge_t"], ) noisy_data.update(sparse_noisy_data) noisy_data["comp_edge_index_t"] = sparse_noisy_data["edge_index_t"] noisy_data["comp_edge_attr_t"] = sparse_noisy_data["edge_attr_t"] pred0 = self.forward(noisy_data) pred0, _ = utils.to_dense( pred0.node, pred0.edge_index, pred0.edge_attr, pred0.batch, pred0.charge ) # Normalize predictions probX0 = F.softmax(pred0.X, dim=-1) probE0 = F.softmax(pred0.E, dim=-1) # Set masked rows to arbitrary values that don't contribute to loss probX0[~node_mask] = torch.ones(self.out_dims.X).type_as(probX0) probE0[~(node_mask.unsqueeze(1) * node_mask.unsqueeze(2))] = torch.ones( self.out_dims.E ).type_as(probE0) diag_mask = torch.eye(probE0.size(1)).type_as(probE0).bool() diag_mask = diag_mask.unsqueeze(0).expand(probE0.size(0), -1, -1) probE0[diag_mask] = torch.ones(self.out_dims.E).type_as(probE0) assert (~probX0.isnan()).any() assert (~probE0.isnan()).any() prob_charge0 = charge if self.use_charge: prob_charge0 = F.softmax(pred0.charge, dim=-1) prob_charge0[~node_mask] = torch.ones(self.out_dims.charge).type_as( prob_charge0 ) assert (~prob_charge0.isnan()).any() return utils.PlaceHolder(X=probX0, E=probE0, y=None, charge=prob_charge0) def forward_sparse(self, sparse_noisy_data): start_time = time.time() node = sparse_noisy_data["node_t"] edge_attr = sparse_noisy_data["edge_attr_t"].float() edge_index = sparse_noisy_data["edge_index_t"].to(torch.int64) y = sparse_noisy_data["y_t"] batch = sparse_noisy_data["batch"].long() if hasattr(self, "forward_time"): self.forward_time.append(round(time.time() - start_time, 2)) return self.model(node, edge_attr, edge_index, y, batch) def forward(self, noisy_data): """ noisy data contains: node_t, comp_edge_index_t, comp_edge_attr_t, batch """ # build the sparse_noisy_data for the forward function of the sparse model start_time = time.time() sparse_noisy_data = self.compute_extra_data(sparse_noisy_data=noisy_data) if self.sign_net and self.cfg.model.extra_features == "all": x = self.sign_net( sparse_noisy_data["node_t"], sparse_noisy_data["edge_index_t"], sparse_noisy_data["batch"], ) sparse_noisy_data["node_t"] = torch.hstack( [sparse_noisy_data["node_t"], x] ) if hasattr(self, "extra_data_time"): self.extra_data_time.append(round(time.time() - start_time, 2)) return self.forward_sparse(sparse_noisy_data) @torch.no_grad() def sample_batch( self, batch_id: int, batch_size: int, keep_chain: int, number_chain_steps: int, save_final: int, num_nodes=None, ): """ :param batch_id: int :param batch_size: int :param num_nodes: int, <int>tensor (batch_size) (optional) for specifying number of nodes :param save_final: int: number of predictions to save to file :param keep_chain: int: number of chains to save to file :param keep_chain_steps: number of timesteps to save for each chain :return: molecule_list. Each element of this list is a tuple (node_types, charge, positions) """ if num_nodes is None: num_nodes = self.node_dist.sample_n(batch_size, self.device) elif type(num_nodes) == int: num_nodes = num_nodes * torch.ones( batch_size, device=self.device, dtype=torch.int ) else: assert isinstance(num_nodes, torch.Tensor) num_nodes = num_nodes num_max = torch.max(num_nodes) # Build the masks arange = ( torch.arange(num_max, device=self.device) .unsqueeze(0) .expand(batch_size, -1) ) node_mask = arange < num_nodes.unsqueeze(1) # Sample noise -- z has size ( num_samples, num_nodes, num_features) sparse_sampled_data = diffusion_utils.sample_sparse_discrete_feature_noise( limit_dist=self.limit_dist, node_mask=node_mask ) assert number_chain_steps < self.T chain = utils.SparseChainPlaceHolder(keep_chain=keep_chain) # Iteratively sample p(z_s | z_t) for t = 1, ..., T, with s = t - 1. for s_int in tqdm(reversed(range(self.T)), total=self.T): s_array = (s_int * torch.ones((batch_size, 1))).to(self.device) t_array = s_array + 1 s_norm = s_array / self.T t_norm = t_array / self.T # Sample z_s sparse_sampled_data = self.sample_p_zs_given_zt( s_norm, t_norm, sparse_sampled_data ) # keep_chain can be very small, e.g., 1 if ((s_int * number_chain_steps) % self.T == 0) and (keep_chain != 0): chain.append(sparse_sampled_data) # get generated graphs generated_graphs = sparse_sampled_data.to_device("cpu") generated_graphs.edge_attr = sparse_sampled_data.edge_attr.argmax(-1) generated_graphs.node = sparse_sampled_data.node.argmax(-1) if self.use_charge: generated_graphs.charge = sparse_sampled_data.charge.argmax(-1) - 1 if self.visualization_tools is not None: current_path = os.getcwd() # Visualize chains if keep_chain > 0: print("Visualizing chains...") chain_path = os.path.join( current_path, f"chains/{self.cfg.general.name}/" f"epoch{self.current_epoch}/", ) try: _ = self.visualization_tools.visualize_chain( chain_path, batch_id, chain, local_rank=self.local_rank ) except OSError: print("Warn: image chains failed to be visualized ") # Visualize the final molecules print("\nVisualizing molecules...") result_path = os.path.join( current_path, f"graphs/{self.name}/epoch{self.current_epoch}_b{batch_id}/", ) try: self.visualization_tools.visualize( result_path, generated_graphs, save_final, local_rank=self.local_rank, ) except OSError: print("Warn: image failed to be visualized ") print("Done.") return generated_graphs def sample_node(self, pred_X, p_s_and_t_given_0_X, node_mask): # Normalize predictions pred_X = F.softmax(pred_X, dim=-1) # bs, n, d0 # Dim of these two tensors: bs, N, d0, d_t-1 weighted_X = pred_X.unsqueeze(-1) * p_s_and_t_given_0_X # bs, n, d0, d_t-1 unnormalized_prob_X = weighted_X.sum(dim=2) # bs, n, d_t-1 unnormalized_prob_X[torch.sum(unnormalized_prob_X, dim=-1) == 0] = 1e-5 prob_X = unnormalized_prob_X / torch.sum( unnormalized_prob_X, dim=-1, keepdim=True ) # bs, n, d_t assert ((prob_X.sum(dim=-1) - 1).abs() < 1e-4).all() X_t = diffusion_utils.sample_discrete_node_features(prob_X, node_mask) return X_t, prob_X def sample_edge(self, pred_E, p_s_and_t_given_0_E, node_mask): # Normalize predictions bs, n, n, de = pred_E.shape pred_E = F.softmax(pred_E, dim=-1) # bs, n, n, d0 pred_E = pred_E.reshape((bs, -1, pred_E.shape[-1])) weighted_E = pred_E.unsqueeze(-1) * p_s_and_t_given_0_E # bs, N, d0, d_t-1 unnormalized_prob_E = weighted_E.sum(dim=-2) unnormalized_prob_E[torch.sum(unnormalized_prob_E, dim=-1) == 0] = 1e-5 prob_E = unnormalized_prob_E / torch.sum( unnormalized_prob_E, dim=-1, keepdim=True ) prob_E = prob_E.reshape(bs, n, n, de) assert ((prob_E.sum(dim=-1) - 1).abs() < 1e-4).all() E_t = diffusion_utils.sample_discrete_edge_features(prob_E, node_mask) return E_t, prob_E def sample_node_edge( self, pred, p_s_and_t_given_0_X, p_s_and_t_given_0_E, node_mask ): _, prob_X = self.sample_node(pred.X, p_s_and_t_given_0_X, node_mask) _, prob_E = self.sample_edge(pred.E, p_s_and_t_given_0_E, node_mask) sampled_s = diffusion_utils.sample_discrete_features( prob_X, prob_E, node_mask=node_mask ) return sampled_s def sample_sparse_node(self, pred_node, p_s_and_t_given_0_X): # Normalize predictions pred_X = F.softmax(pred_node, dim=-1) # N, dx # Dim of the second tensor: N, dx, dx weighted_X = pred_X.unsqueeze(-1) * p_s_and_t_given_0_X # N, dx, dx unnormalized_prob_X = weighted_X.sum(dim=1) # N, dx unnormalized_prob_X[ torch.sum(unnormalized_prob_X, dim=-1) == 0 ] = 1e-5 # TODO: delete/masking? prob_X = unnormalized_prob_X / torch.sum( unnormalized_prob_X, dim=-1, keepdim=True ) # N, dx assert ((prob_X.sum(dim=-1) - 1).abs() < 1e-4).all() X_t = prob_X.multinomial(1)[:, 0] return X_t def sample_sparse_edge(self, pred_edge, p_s_and_t_given_0_E): # Normalize predictions pred_E = F.softmax(pred_edge, dim=-1) # N, d0 # Dim of the second tensor: N, d0, dt-1 weighted_E = pred_E.unsqueeze(-1) * p_s_and_t_given_0_E # N, d0, dt-1 unnormalized_prob_E = weighted_E.sum(dim=1) # N, dt-1 unnormalized_prob_E[torch.sum(unnormalized_prob_E, dim=-1) == 0] = 1e-5 prob_E = unnormalized_prob_E / torch.sum( unnormalized_prob_E, dim=-1, keepdim=True ) assert ((prob_E.sum(dim=-1) - 1).abs() < 1e-4).all() E_t = prob_E.multinomial(1)[:, 0] return E_t def sample_sparse_node_edge( self, pred_node, pred_edge, p_s_and_t_given_0_X, p_s_and_t_given_0_E, pred_charge, p_s_and_t_given_0_charge, ): sampled_node = self.sample_sparse_node(pred_node, p_s_and_t_given_0_X).long() sampled_edge = self.sample_sparse_edge(pred_edge, p_s_and_t_given_0_E).long() if pred_charge.size(-1) > 0: sampled_charge = self.sample_sparse_node( pred_charge, p_s_and_t_given_0_charge ).long() else: sampled_charge = pred_charge return sampled_node, sampled_edge, sampled_charge def sample_p_zs_given_zt(self, s_float, t_float, data): """ Samples from zs ~ p(zs | zt). Only used during sampling. if last_step, return the graph prediction as well """ node = data.node edge_index = data.edge_index edge_attr = data.edge_attr y = data.y charge = data.charge ptr = data.ptr batch = data.batch beta_t = self.noise_schedule(t_normalized=t_float) # (bs, 1) alpha_s_bar = self.noise_schedule.get_alpha_bar(t_normalized=s_float) alpha_t_bar = self.noise_schedule.get_alpha_bar(t_normalized=t_float) # Retrieve transitions matrix Qtb = self.transition_model.get_Qt_bar(alpha_t_bar, self.device) Qsb = self.transition_model.get_Qt_bar(alpha_s_bar, self.device) Qt = self.transition_model.get_Qt(beta_t, self.device) # Prior distribution # (N, dx, dx) p_s_and_t_given_0_X = ( diffusion_utils.compute_sparse_batched_over0_posterior_distribution( input_data=node, batch=batch, Qt=Qt.X, Qsb=Qsb.X, Qtb=Qtb.X ) ) p_s_and_t_given_0_charge = None if self.use_charge: p_s_and_t_given_0_charge = ( diffusion_utils.compute_sparse_batched_over0_posterior_distribution( input_data=charge, batch=batch, Qt=Qt.charge, Qsb=Qsb.charge, Qtb=Qtb.charge, ) ) # prepare sparse information num_nodes = ptr.diff().long() num_edges = (num_nodes * (num_nodes - 1) / 2).long() # If we had one graph, we will iterate on all edges for each step # we also make sure that the non existing edge number remains the same with the training process ( all_condensed_index, all_edge_batch, all_edge_mask,
) = sampled_condensed_indices_uniformly(
8
2023-10-30 12:12:16+00:00
16k
akekic/causal-component-analysis
experiments/cauca/main.py
[ { "identifier": "DGP", "path": "config.py", "snippet": "DGP = {\n \"graph-4-0\": {\n \"num_causal_variables\": 4, # N\n \"adj_matrix\": np.array(\n [[0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0]]\n ),\n \"int_targets\": torch.tensor(\n [[0, ...
import argparse import os import pytorch_lightning as pl from pathlib import Path from pytorch_lightning.loggers import WandbLogger from config import DGP from data_generator import MultiEnvDataModule, make_multi_env_dgp from model.cauca_model import LinearCauCAModel, NaiveNonlinearModel, NonlinearCauCAModel
12,283
) parser.add_argument( "--fix-mechanisms", type=bool, default=True, action=argparse.BooleanOptionalAction, help="Fix fixable mechanisms in latents.", ) parser.add_argument( "--fix-all-intervention-targets", type=bool, default=False, action=argparse.BooleanOptionalAction, help="Fix all intervention targets.", ) parser.add_argument( "--nonparametric-base-distr", type=bool, default=False, action=argparse.BooleanOptionalAction, help="Use nonparametric base distribution for flows.", ) parser.add_argument( "--wandb", type=bool, default=True, action=argparse.BooleanOptionalAction, help="Whether to log to weights and biases.", ) parser.add_argument( "--wandb-project", type=str, default="cauca", help="Weights & Biases project name.", ) args = parser.parse_args() if args.function_misspec: assert ( args.mixing == "nonlinear" and args.model == "linear" ), "Function not misspecified." if args.wandb: wandb_logger = WandbLogger(project=args.wandb_project) wandb_logger.experiment.config.update(args, allow_val_change=True) checkpoint_dir = ( Path(args.checkpoint_root_dir) / f"{wandb_logger.experiment.id}" ) logger = [wandb_logger] else: checkpoint_dir = Path(args.checkpoint_root_dir) / "default" logger = None checkpoint_callback = pl.callbacks.ModelCheckpoint( dirpath=checkpoint_dir, save_last=True, every_n_epochs=args.check_val_every_n_epoch, ) multi_env_dgp = make_multi_env_dgp( latent_dim=DGP[args.dgp]["num_causal_variables"], observation_dim=DGP[args.dgp]["observation_dim"], adjacency_matrix=DGP[args.dgp]["adj_matrix"], intervention_targets_per_env=DGP[args.dgp]["int_targets"], noise_shift_type=args.noise_shift_type, mixing=args.mixing, scm=args.scm, n_nonlinearities=args.n_nonlinearities, scm_coeffs_low=args.scm_coeffs_low, scm_coeffs_high=args.scm_coeffs_high, coeffs_min_abs_value=args.scm_coeffs_min_abs_value, edge_prob=DGP[args.dgp].get("edge_prob", None), snr=args.snr, ) data_module = MultiEnvDataModule( multi_env_dgp=multi_env_dgp, num_samples_per_env=DGP[args.dgp]["num_samples_per_env"], batch_size=args.batch_size, num_workers=os.cpu_count(), intervention_targets_per_env=DGP[args.dgp]["int_targets"], log_dir=checkpoint_dir / "data_stats", ) data_module.setup() pl.seed_everything(args.training_seed, workers=True) intervention_targets_per_env = DGP[args.dgp]["int_targets"] # Model Initialization if args.model == "nonlinear": model = NonlinearCauCAModel( latent_dim=DGP[args.dgp]["num_causal_variables"], adjacency_matrix=data_module.medgp.adjacency_matrix, k_flows=args.k_flows, lr=args.lr, intervention_targets_per_env=intervention_targets_per_env, lr_scheduler=args.lr_scheduler, lr_min=args.lr_min, adjacency_misspecified=args.adjacency_misspec, net_hidden_dim=args.net_hidden_dim, net_hidden_layers=args.net_hidden_layers, fix_mechanisms=args.fix_mechanisms, fix_all_intervention_targets=args.fix_all_intervention_targets, nonparametric_base_distr=args.nonparametric_base_distr, K_cbn=args.k_flows_cbn, net_hidden_dim_cbn=args.net_hidden_dim_cbn, net_hidden_layers_cbn=args.net_hidden_layers_cbn, ) elif args.model == "linear": model = LinearCauCAModel( latent_dim=DGP[args.dgp]["num_causal_variables"], adjacency_matrix=data_module.medgp.adjacency_matrix, lr=args.lr, intervention_targets_per_env=intervention_targets_per_env, lr_scheduler=args.lr_scheduler, lr_min=args.lr_min, adjacency_misspecified=args.adjacency_misspec, fix_mechanisms=args.fix_mechanisms, nonparametric_base_distr=args.nonparametric_base_distr, ) elif args.model == "naive":
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Run experiment for Causal Component Analysis (CauCA)." ) parser.add_argument( "--max-epochs", type=int, default=10, help="Number of epochs to train for.", ) parser.add_argument( "--accelerator", type=str, default="gpu", help="Accelerator to use for training.", ) parser.add_argument( "--batch-size", type=int, default=1024, help="Number of samples per batch.", ) parser.add_argument( "--lr", type=float, default=1e-4, help="Learning rate for Adam optimizer.", ) parser.add_argument( "--checkpoint-root-dir", type=str, default="checkpoints", help="Checkpoint root directory.", ) parser.add_argument( "--noise-shift-type", type=str, default="mean", choices=["mean", "std"], help="Property of noise distribution that is shifted between environments.", ) parser.add_argument( "--check-val-every-n-epoch", type=int, default=1, help="Check validation loss every n epochs.", ) parser.add_argument( "--dgp", type=str, default="graph-4-0", help="Data generation process to use.", ) parser.add_argument( "--k-flows", type=int, default=1, help="Number of flows to use in nonlinear ICA model.", ) parser.add_argument( "--k-flows-cbn", type=int, default=3, help="Number of flows to use in nonlinear latent CBN model.", ) parser.add_argument( "--model", type=str, default="nonlinear", help="Type of encoder to use.", choices=["linear", "nonlinear", "naive"], ) parser.add_argument( "--seed", type=int, default=42, ) parser.add_argument( "--training-seed", type=int, default=42, ) parser.add_argument( "--mixing", type=str, default="nonlinear", help="Type of mixing function to use.", choices=["linear", "nonlinear"], ) parser.add_argument( "--scm", type=str, default="linear", help="Type of SCM to use.", choices=["linear", "location-scale"], ) parser.add_argument( "--n-nonlinearities", type=int, default=1, help="Number of nonlinearities to use in nonlinear mixing function.", ) parser.add_argument( "--learn-scm-params", type=bool, default=True, action=argparse.BooleanOptionalAction, help="Whether to learn SCM parameters.", ) parser.add_argument( "--lr-scheduler", type=str, default=None, help="Learning rate scheduler.", choices=[None, "cosine"], ) parser.add_argument( "--lr-min", type=float, default=0.0, help="Minimum learning rate for cosine learning rate scheduler.", ) parser.add_argument( "--scm-coeffs-low", type=float, default=-1, help="Lower bound for SCM coefficients.", ) parser.add_argument( "--scm-coeffs-high", type=float, default=1, help="Upper bound for SCM coefficients.", ) parser.add_argument( "--scm-coeffs-min-abs-value", type=float, default=None, help="Minimum absolute value for SCM coefficients.", ) parser.add_argument( "--snr", type=float, default=1.0, help="Signal-to-noise ratio in latent SCM.", ) parser.add_argument( "--adjacency-misspec", type=bool, default=False, action=argparse.BooleanOptionalAction, help="Misspecify adjacency matrix - assume ICA.", ) parser.add_argument( "--function-misspec", type=bool, default=False, action=argparse.BooleanOptionalAction, help="Misspecify function class - assume linear.", ) parser.add_argument( "--net-hidden-layers", type=int, default=3, help="Number of hidden layers in nonlinear encoder.", ) parser.add_argument( "--net-hidden-layers-cbn", type=int, default=3, help="Number of hidden layers in latent CBN model.", ) parser.add_argument( "--net-hidden-dim", type=int, default=128, help="Number of hidden dimensions in nonlinear encoder.", ) parser.add_argument( "--net-hidden-dim-cbn", type=int, default=128, help="Number of hidden dimensions in latent CBN model.", ) parser.add_argument( "--fix-mechanisms", type=bool, default=True, action=argparse.BooleanOptionalAction, help="Fix fixable mechanisms in latents.", ) parser.add_argument( "--fix-all-intervention-targets", type=bool, default=False, action=argparse.BooleanOptionalAction, help="Fix all intervention targets.", ) parser.add_argument( "--nonparametric-base-distr", type=bool, default=False, action=argparse.BooleanOptionalAction, help="Use nonparametric base distribution for flows.", ) parser.add_argument( "--wandb", type=bool, default=True, action=argparse.BooleanOptionalAction, help="Whether to log to weights and biases.", ) parser.add_argument( "--wandb-project", type=str, default="cauca", help="Weights & Biases project name.", ) args = parser.parse_args() if args.function_misspec: assert ( args.mixing == "nonlinear" and args.model == "linear" ), "Function not misspecified." if args.wandb: wandb_logger = WandbLogger(project=args.wandb_project) wandb_logger.experiment.config.update(args, allow_val_change=True) checkpoint_dir = ( Path(args.checkpoint_root_dir) / f"{wandb_logger.experiment.id}" ) logger = [wandb_logger] else: checkpoint_dir = Path(args.checkpoint_root_dir) / "default" logger = None checkpoint_callback = pl.callbacks.ModelCheckpoint( dirpath=checkpoint_dir, save_last=True, every_n_epochs=args.check_val_every_n_epoch, ) multi_env_dgp = make_multi_env_dgp( latent_dim=DGP[args.dgp]["num_causal_variables"], observation_dim=DGP[args.dgp]["observation_dim"], adjacency_matrix=DGP[args.dgp]["adj_matrix"], intervention_targets_per_env=DGP[args.dgp]["int_targets"], noise_shift_type=args.noise_shift_type, mixing=args.mixing, scm=args.scm, n_nonlinearities=args.n_nonlinearities, scm_coeffs_low=args.scm_coeffs_low, scm_coeffs_high=args.scm_coeffs_high, coeffs_min_abs_value=args.scm_coeffs_min_abs_value, edge_prob=DGP[args.dgp].get("edge_prob", None), snr=args.snr, ) data_module = MultiEnvDataModule( multi_env_dgp=multi_env_dgp, num_samples_per_env=DGP[args.dgp]["num_samples_per_env"], batch_size=args.batch_size, num_workers=os.cpu_count(), intervention_targets_per_env=DGP[args.dgp]["int_targets"], log_dir=checkpoint_dir / "data_stats", ) data_module.setup() pl.seed_everything(args.training_seed, workers=True) intervention_targets_per_env = DGP[args.dgp]["int_targets"] # Model Initialization if args.model == "nonlinear": model = NonlinearCauCAModel( latent_dim=DGP[args.dgp]["num_causal_variables"], adjacency_matrix=data_module.medgp.adjacency_matrix, k_flows=args.k_flows, lr=args.lr, intervention_targets_per_env=intervention_targets_per_env, lr_scheduler=args.lr_scheduler, lr_min=args.lr_min, adjacency_misspecified=args.adjacency_misspec, net_hidden_dim=args.net_hidden_dim, net_hidden_layers=args.net_hidden_layers, fix_mechanisms=args.fix_mechanisms, fix_all_intervention_targets=args.fix_all_intervention_targets, nonparametric_base_distr=args.nonparametric_base_distr, K_cbn=args.k_flows_cbn, net_hidden_dim_cbn=args.net_hidden_dim_cbn, net_hidden_layers_cbn=args.net_hidden_layers_cbn, ) elif args.model == "linear": model = LinearCauCAModel( latent_dim=DGP[args.dgp]["num_causal_variables"], adjacency_matrix=data_module.medgp.adjacency_matrix, lr=args.lr, intervention_targets_per_env=intervention_targets_per_env, lr_scheduler=args.lr_scheduler, lr_min=args.lr_min, adjacency_misspecified=args.adjacency_misspec, fix_mechanisms=args.fix_mechanisms, nonparametric_base_distr=args.nonparametric_base_distr, ) elif args.model == "naive":
model = NaiveNonlinearModel(
4
2023-10-25 09:25:26+00:00
16k
endo-yuki-t/MAG
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
11,199
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema:
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, reset_ema=False, reset_num_ema_updates=False, ): super().__init__() assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema:
self.model_ema = LitEma(self.model)
8
2023-10-27 06:56:37+00:00
16k
Gene-Weaver/VoucherVision
vouchervision/VoucherVision_GUI.py
[ { "identifier": "write_config_file", "path": "vouchervision/LeafMachine2_Config_Builder.py", "snippet": "def write_config_file(config_data, dir_home, filename=\"LeafMachine2.yaml\"):\n file_path = os.path.join(dir_home, filename)\n\n # Write the data to a YAML file\n with open(file_path, \"w\")...
import streamlit as st import yaml, os, json, random, time, re import matplotlib.pyplot as plt import plotly.graph_objs as go import numpy as np import pandas as pd from itertools import chain from PIL import Image from typing import Union from streamlit_extras.let_it_rain import rain from vouchervision.LeafMachine2_Config_Builder import write_config_file from vouchervision.VoucherVision_Config_Builder import build_VV_config, run_demo_tests_GPT, run_demo_tests_Palm , TestOptionsGPT, TestOptionsPalm, check_if_usable, run_api_tests from vouchervision.vouchervision_main import voucher_vision, voucher_vision_OCR_test from vouchervision.general_utils import test_GPU, get_cfg_from_full_path, summarize_expense_report, create_google_ocr_yaml_config, validate_dir
10,839
if st.session_state.config['leafmachine']['project']['prompt_version'] in PROMPTS_THAT_NEED_DOMAIN_KNOWLEDGE: st.session_state.config['leafmachine']['project']['use_domain_knowledge'] = st.checkbox("Use domain knowledge", True, disabled=True) else: st.session_state.config['leafmachine']['project']['use_domain_knowledge'] = st.checkbox("Use domain knowledge", False, disabled=True) st.write("") if st.session_state.config['leafmachine']['project']['use_domain_knowledge']: st.session_state.config['leafmachine']['project']['embeddings_database_name'] = st.text_input("Embeddings database name (only use underscores)", st.session_state.config['leafmachine']['project'].get('embeddings_database_name', '')) st.session_state.config['leafmachine']['project']['build_new_embeddings_database'] = st.checkbox("Build *new* embeddings database", st.session_state.config['leafmachine']['project'].get('build_new_embeddings_database', False)) st.session_state.config['leafmachine']['project']['path_to_domain_knowledge_xlsx'] = st.text_input("Path to domain knowledge CSV file (will be used to create new embeddings database)", st.session_state.config['leafmachine']['project'].get('path_to_domain_knowledge_xlsx', '')) else: st.session_state.config['leafmachine']['project']['embeddings_database_name'] = st.text_input("Embeddings database name (only use underscores)", st.session_state.config['leafmachine']['project'].get('embeddings_database_name', ''), disabled=True) st.session_state.config['leafmachine']['project']['build_new_embeddings_database'] = st.checkbox("Build *new* embeddings database", st.session_state.config['leafmachine']['project'].get('build_new_embeddings_database', False), disabled=True) st.session_state.config['leafmachine']['project']['path_to_domain_knowledge_xlsx'] = st.text_input("Path to domain knowledge CSV file (will be used to create new embeddings database)", st.session_state.config['leafmachine']['project'].get('path_to_domain_knowledge_xlsx', ''), disabled=True) def render_expense_report_summary(): expense_summary = st.session_state.expense_summary expense_report = st.session_state.expense_report st.header('Expense Report Summary') if expense_summary: st.metric(label="Total Cost", value=f"${round(expense_summary['total_cost_sum'], 4):,}") col1, col2 = st.columns(2) # Run count and total costs with col1: st.metric(label="Run Count", value=expense_summary['run_count']) st.metric(label="Tokens In", value=f"{expense_summary['tokens_in_sum']:,}") # Token information with col2: st.metric(label="Total Images", value=expense_summary['n_images_sum']) st.metric(label="Tokens Out", value=f"{expense_summary['tokens_out_sum']:,}") # Calculate cost proportion per image for each API version st.subheader('Average Cost per Image by API Version') cost_labels = [] cost_values = [] total_images = 0 cost_per_image_dict = {} # Iterate through the expense report to accumulate costs and image counts for index, row in expense_report.iterrows(): api_version = row['api_version'] total_cost = row['total_cost'] n_images = row['n_images'] total_images += n_images # Keep track of total images processed if api_version not in cost_per_image_dict: cost_per_image_dict[api_version] = {'total_cost': 0, 'n_images': 0} cost_per_image_dict[api_version]['total_cost'] += total_cost cost_per_image_dict[api_version]['n_images'] += n_images api_versions = list(cost_per_image_dict.keys()) colors = [COLORS_EXPENSE_REPORT[version] if version in COLORS_EXPENSE_REPORT else '#DDDDDD' for version in api_versions] # Calculate the cost per image for each API version for version, cost_data in cost_per_image_dict.items(): total_cost = cost_data['total_cost'] n_images = cost_data['n_images'] # Calculate the cost per image for this version cost_per_image = total_cost / n_images if n_images > 0 else 0 cost_labels.append(version) cost_values.append(cost_per_image) # Generate the pie chart cost_pie_chart = go.Figure(data=[go.Pie(labels=cost_labels, values=cost_values, hole=.3)]) # Update traces for custom text in hoverinfo, displaying cost with a dollar sign and two decimal places cost_pie_chart.update_traces( marker=dict(colors=colors), text=[f"${value:.2f}" for value in cost_values], # Formats the cost as a string with a dollar sign and two decimals textinfo='percent+label', hoverinfo='label+percent+text' # Adds custom text (formatted cost) to the hover information ) st.plotly_chart(cost_pie_chart, use_container_width=True) st.subheader('Proportion of Total Cost by API Version') cost_labels = [] cost_proportions = [] total_cost_by_version = {} # Sum the total cost for each API version for index, row in expense_report.iterrows(): api_version = row['api_version'] total_cost = row['total_cost'] if api_version not in total_cost_by_version: total_cost_by_version[api_version] = 0 total_cost_by_version[api_version] += total_cost # Calculate the combined total cost for all versions combined_total_cost = sum(total_cost_by_version.values()) # Calculate the proportion of total cost for each API version for version, total_cost in total_cost_by_version.items(): proportion = (total_cost / combined_total_cost) * 100 if combined_total_cost > 0 else 0 cost_labels.append(version) cost_proportions.append(proportion) # Generate the pie chart cost_pie_chart = go.Figure(data=[go.Pie(labels=cost_labels, values=cost_proportions, hole=.3)]) # Update traces for custom text in hoverinfo cost_pie_chart.update_traces( marker=dict(colors=colors), text=[f"${cost:.2f}" for cost in total_cost_by_version.values()], # This will format the cost to 2 decimal places textinfo='percent+label', hoverinfo='label+percent+text' # This tells Plotly to show the label, percent, and custom text (cost) on hover ) st.plotly_chart(cost_pie_chart, use_container_width=True) # API version usage percentages pie chart st.subheader('Runs by API Version') api_versions = list(expense_summary['api_version_percentages'].keys()) percentages = [expense_summary['api_version_percentages'][version] for version in api_versions] pie_chart = go.Figure(data=[go.Pie(labels=api_versions, values=percentages, hole=.3)]) pie_chart.update_layout(margin=dict(t=0, b=0, l=0, r=0)) pie_chart.update_traces(marker=dict(colors=colors),) st.plotly_chart(pie_chart, use_container_width=True) else: st.error('No expense report data available.') def sidebar_content(): if not os.path.exists(os.path.join(st.session_state.dir_home,'expense_report')):
PROMPTS_THAT_NEED_DOMAIN_KNOWLEDGE = ["Version 1","Version 1 PaLM 2"] COLORS_EXPENSE_REPORT = { 'GPT_4': '#8fff66', # Bright Green 'GPT_3_5': '#006400', # Dark Green 'PALM2': '#66a8ff' # blue } class ProgressReport: def __init__(self, overall_bar, batch_bar, text_overall, text_batch): self.overall_bar = overall_bar self.batch_bar = batch_bar self.text_overall = text_overall self.text_batch = text_batch self.current_overall_step = 0 self.total_overall_steps = 20 # number of major steps in machine function self.current_batch = 0 self.total_batches = 20 def update_overall(self, step_name=""): self.current_overall_step += 1 self.overall_bar.progress(self.current_overall_step / self.total_overall_steps) self.text_overall.text(step_name) def update_batch(self, step_name=""): self.current_batch += 1 self.batch_bar.progress(self.current_batch / self.total_batches) self.text_batch.text(step_name) def set_n_batches(self, n_batches): self.total_batches = n_batches def set_n_overall(self, total_overall_steps): self.current_overall_step = 0 self.overall_bar.progress(0) self.total_overall_steps = total_overall_steps def reset_batch(self, step_name): self.current_batch = 0 self.batch_bar.progress(0) self.text_batch.text(step_name) def reset_overall(self, step_name): self.current_overall_step = 0 self.overall_bar.progress(0) self.text_overall.text(step_name) def get_n_images(self): return self.n_images def get_n_overall(self): return self.total_overall_steps def does_private_file_exist(): dir_home = os.path.dirname(os.path.dirname(__file__)) path_cfg_private = os.path.join(dir_home, 'PRIVATE_DATA.yaml') return os.path.exists(path_cfg_private) def setup_streamlit_config(dir_home): # Define the directory path and filename dir_path = os.path.join(dir_home, ".streamlit") file_path = os.path.join(dir_path, "config.toml") # Check if directory exists, if not create it if not os.path.exists(dir_path): os.makedirs(dir_path) # Create or modify the file with the provided content config_content = f""" [theme] base = "dark" primaryColor = "#00ff00" [server] enableStaticServing = false runOnSave = true port = 8524 """ with open(file_path, "w") as f: f.write(config_content.strip()) def display_scrollable_results(JSON_results, test_results, OPT2, OPT3): """ Display the results from JSON_results in a scrollable container. """ # Initialize the container con_results = st.empty() with con_results.container(): # Start the custom container for all the results results_html = """<div class='scrollable-results-container'>""" for idx, (test_name, _) in enumerate(sorted(test_results.items())): _, ind_opt1, ind_opt2, ind_opt3 = test_name.split('__') opt2_readable = "Use LeafMachine2" if OPT2[int(ind_opt2.split('-')[1])] else "Don't use LeafMachine2" opt3_readable = f"{OPT3[int(ind_opt3.split('-')[1])]}" if JSON_results[idx] is None: results_html += f"<p>None</p>" else: formatted_json = json.dumps(JSON_results[idx], indent=4, sort_keys=False) results_html += f"<pre>[{opt2_readable}] + [{opt3_readable}]<br/>{formatted_json}</pre>" # End the custom container results_html += """</div>""" # The CSS to make this container scrollable css = """ <style> .scrollable-results-container { overflow-y: auto; height: 600px; width: 100%; white-space: pre-wrap; # To wrap the content font-family: monospace; # To give the JSON a code-like appearance } </style> """ # Apply the CSS and then the results st.markdown(css, unsafe_allow_html=True) st.markdown(results_html, unsafe_allow_html=True) def refresh(): st.write('') def display_test_results(test_results, JSON_results, llm_version): if llm_version == 'gpt': OPT1, OPT2, OPT3 = TestOptionsGPT.get_options() elif llm_version == 'palm': OPT1, OPT2, OPT3 = TestOptionsPalm.get_options() else: raise widths = [1] * (len(OPT1) + 2) + [2] columns = st.columns(widths) with columns[0]: st.write("LeafMachine2") with columns[1]: st.write("Prompt") with columns[len(OPT1) + 2]: st.write("Scroll to See Last Transcription in Each Test") already_written = set() for test_name, result in sorted(test_results.items()): _, ind_opt1, _, _ = test_name.split('__') option_value = OPT1[int(ind_opt1.split('-')[1])] if option_value not in already_written: with columns[int(ind_opt1.split('-')[1]) + 2]: st.write(option_value) already_written.add(option_value) printed_options = set() with columns[-1]: display_scrollable_results(JSON_results, test_results, OPT2, OPT3) # Close the custom container st.write('</div>', unsafe_allow_html=True) for idx, (test_name, result) in enumerate(sorted(test_results.items())): _, ind_opt1, ind_opt2, ind_opt3 = test_name.split('__') opt2_readable = "Use LeafMachine2" if OPT2[int(ind_opt2.split('-')[1])] else "Don't use LeafMachine2" opt3_readable = f"{OPT3[int(ind_opt3.split('-')[1])]}" if (opt2_readable, opt3_readable) not in printed_options: with columns[0]: st.info(f"{opt2_readable}") st.write('---') with columns[1]: st.info(f"{opt3_readable}") st.write('---') printed_options.add((opt2_readable, opt3_readable)) with columns[int(ind_opt1.split('-')[1]) + 2]: if result: st.success(f"Test Passed") else: st.error(f"Test Failed") st.write('---') # success_count = sum(1 for result in test_results.values() if result) # failure_count = len(test_results) - success_count # proportional_rain("🥇", success_count, "💔", failure_count, font_size=72, falling_speed=5, animation_length="infinite") rain_emojis(test_results) def add_emoji_delay(): time.sleep(0.3) def rain_emojis(test_results): # test_results = { # 'test1': True, # Test passed # 'test2': True, # Test passed # 'test3': True, # Test passed # 'test4': False, # Test failed # 'test5': False, # Test failed # 'test6': False, # Test failed # 'test7': False, # Test failed # 'test8': False, # Test failed # 'test9': False, # Test failed # 'test10': False, # Test failed # } success_emojis = ["🥇", "🏆", "🍾", "🙌"] failure_emojis = ["💔", "😭"] success_count = sum(1 for result in test_results.values() if result) failure_count = len(test_results) - success_count chosen_emoji = random.choice(success_emojis) for _ in range(success_count): rain( emoji=chosen_emoji, font_size=72, falling_speed=4, animation_length=2, ) add_emoji_delay() chosen_emoji = random.choice(failure_emojis) for _ in range(failure_count): rain( emoji=chosen_emoji, font_size=72, falling_speed=5, animation_length=1, ) add_emoji_delay() def get_prompt_versions(LLM_version): yaml_files = [f for f in os.listdir(os.path.join(st.session_state.dir_home, 'custom_prompts')) if f.endswith('.yaml')] if LLM_version in ["gpt-4-1106-preview", "GPT 4", "GPT 3.5", "Azure GPT 4", "Azure GPT 3.5"]: versions = ["Version 1", "Version 1 No Domain Knowledge", "Version 2"] return (versions + yaml_files, "Version 2") elif LLM_version in ["PaLM 2",]: versions = ["Version 1 PaLM 2", "Version 1 PaLM 2 No Domain Knowledge", "Version 2 PaLM 2"] return (versions + yaml_files, "Version 2 PaLM 2") else: # Handle other cases or raise an error return (yaml_files, None) def get_private_file(): dir_home = os.path.dirname(os.path.dirname(__file__)) path_cfg_private = os.path.join(dir_home, 'PRIVATE_DATA.yaml') return get_cfg_from_full_path(path_cfg_private) def create_space_saver(): st.subheader("Space Saving Options") col_ss_1, col_ss_2 = st.columns([2,2]) with col_ss_1: st.write("Several folders are created and populated with data during the VoucherVision transcription process.") st.write("Below are several options that will allow you to automatically delete temporary files that you may not need for everyday operations.") st.write("VoucherVision creates the following folders. Folders marked with a :star: are required if you want to use VoucherVisionEditor for quality control.") st.write("`../[Run Name]/Archival_Components`") st.write("`../[Run Name]/Config_File`") st.write("`../[Run Name]/Cropped_Images` :star:") st.write("`../[Run Name]/Logs`") st.write("`../[Run Name]/Original_Images` :star:") st.write("`../[Run Name]/Transcription` :star:") with col_ss_2: st.session_state.config['leafmachine']['project']['delete_temps_keep_VVE'] = st.checkbox("Delete Temporary Files (KEEP files required for VoucherVisionEditor)", st.session_state.config['leafmachine']['project'].get('delete_temps_keep_VVE', False)) st.session_state.config['leafmachine']['project']['delete_all_temps'] = st.checkbox("Keep only the final transcription file", st.session_state.config['leafmachine']['project'].get('delete_all_temps', False),help="*WARNING:* This limits your ability to do quality assurance. This will delete all folders created by VoucherVision, leaving only the `transcription.xlsx` file.") # def create_private_file(): # st.session_state.proceed_to_main = False # if st.session_state.private_file: # cfg_private = get_private_file() # create_private_file_0(cfg_private) # else: # st.title("VoucherVision") # create_private_file_0() def create_private_file(): st.session_state.proceed_to_main = False st.title("VoucherVision") col_private,_= st.columns([12,2]) if st.session_state.private_file: cfg_private = get_private_file() else: cfg_private = {} cfg_private['openai'] = {} cfg_private['openai']['OPENAI_API_KEY'] ='' cfg_private['openai_azure'] = {} cfg_private['openai_azure']['openai_api_key'] = '' cfg_private['openai_azure']['api_version'] = '' cfg_private['openai_azure']['openai_api_base'] ='' cfg_private['openai_azure']['openai_organization'] ='' cfg_private['openai_azure']['openai_api_type'] ='' cfg_private['google_cloud'] = {} cfg_private['google_cloud']['path_json_file'] ='' cfg_private['google_palm'] = {} cfg_private['google_palm']['google_palm_api'] ='' with col_private: st.header("Set API keys") st.info("***Note:*** There is a known bug with tabs in Streamlit. If you update an input field it may take you back to the 'Project Settings' tab. Changes that you made are saved, it's just an annoying glitch. We are aware of this issue and will fix it as soon as we can.") st.warning("To commit changes to API keys you must press the 'Set API Keys' button at the bottom of the page.") st.write("Before using VoucherVision you must set your API keys. All keys are stored locally on your computer and are never made public.") st.write("API keys are stored in `../VoucherVision/PRIVATE_DATA.yaml`.") st.write("Deleting this file will allow you to reset API keys. Alternatively, you can edit the keys in the user interface.") st.write("Leave keys blank if you do not intend to use that service.") st.write("---") st.subheader("Google Vision (*Required*)") st.markdown("VoucherVision currently uses [Google Vision API](https://cloud.google.com/vision/docs/ocr) for OCR. Generating an API key for this is more involved than the others. [Please carefully follow the instructions outlined here to create and setup your account.](https://cloud.google.com/vision/docs/setup) ") st.markdown(""" Once your account is created, [visit this page](https://console.cloud.google.com) and create a project. Then follow these instructions: - **Select your Project**: If you have multiple projects, ensure you select the one where you've enabled the Vision API. - **Open the Navigation Menu**: Click on the hamburger menu (three horizontal lines) in the top left corner. - **Go to IAM & Admin**: In the navigation pane, hover over "IAM & Admin" and then click on "Service accounts." - **Locate Your Service Account**: Find the service account for which you wish to download the JSON key. If you haven't created a service account yet, you'll need to do so by clicking the "CREATE SERVICE ACCOUNT" button at the top. - **Download the JSON Key**: - Click on the three dots (actions menu) on the right side of your service account name. - Select "Manage keys." - In the pop-up window, click on the "ADD KEY" button and select "JSON." - The JSON key file will automatically be downloaded to your computer. - **Store Safely**: This file contains sensitive data that can be used to authenticate and bill your Google Cloud account. Never commit it to public repositories or expose it in any way. Always keep it safe and secure. """) with st.container(): c_in_ocr, c_button_ocr = st.columns([10,2]) with c_in_ocr: google_vision = st.text_input(label = 'Full path to Google Cloud JSON API key file', value = cfg_private['google_cloud'].get('path_json_file', ''), placeholder = 'e.g. C:/Documents/Secret_Files/google_API/application_default_credentials.json', help ="This API Key is in the form of a JSON file. Please save the JSON file in a safe directory. DO NOT store the JSON key inside of the VoucherVision directory.", type='password',key='924857298734590283750932809238') with c_button_ocr: st.empty() st.write("---") st.subheader("OpenAI") st.markdown("API key for first-party OpenAI API. Create an account with OpenAI [here](https://platform.openai.com/signup), then create an API key [here](https://platform.openai.com/account/api-keys).") with st.container(): c_in_openai, c_button_openai = st.columns([10,2]) with c_in_openai: openai_api_key = st.text_input("openai_api_key", cfg_private['openai'].get('OPENAI_API_KEY', ''), help='The actual API key. Likely to be a string of 2 character, a dash, and then a 48-character string: sk-XXXXXXXX...', placeholder = 'e.g. sk-XXXXXXXX...', type='password') with c_button_openai: st.empty() st.write("---") st.subheader("OpenAI - Azure") st.markdown("This version OpenAI relies on Azure servers directly as is intended for private enterprise instances of OpenAI's services, such as [UM-GPT](https://its.umich.edu/computing/ai). Administrators will provide you with the following information.") azure_openai_api_version = st.text_input("azure_openai_api_version", cfg_private['openai_azure'].get('api_version', ''), help='API Version e.g. "2023-05-15"', placeholder = 'e.g. 2023-05-15', type='password') azure_openai_api_key = st.text_input("azure_openai_api_key", cfg_private['openai_azure'].get('openai_api_key', ''), help='The actual API key. Likely to be a 32-character string', placeholder = 'e.g. 12333333333333333333333333333332', type='password') azure_openai_api_base = st.text_input("azure_openai_api_base", cfg_private['openai_azure'].get('openai_api_base', ''), help='The base url for the API e.g. "https://api.umgpt.umich.edu/azure-openai-api"', placeholder = 'e.g. https://api.umgpt.umich.edu/azure-openai-api', type='password') azure_openai_organization = st.text_input("azure_openai_organization", cfg_private['openai_azure'].get('openai_organization', ''), help='Your organization code. Likely a short string', placeholder = 'e.g. 123456', type='password') azure_openai_api_type = st.text_input("azure_openai_api_type", cfg_private['openai_azure'].get('openai_api_type', ''), help='The API type. Typically "azure"', placeholder = 'e.g. azure', type='password') with st.container(): c_in_azure, c_button_azure = st.columns([10,2]) with c_button_azure: st.empty() st.write("---") st.subheader("Google PaLM 2") st.markdown('Follow these [instructions](https://developers.generativeai.google/tutorials/setup) to generate an API key for PaLM 2. You may need to also activate an account with [MakerSuite](https://makersuite.google.com/app/apikey) and enable "early access."') with st.container(): c_in_palm, c_button_palm = st.columns([10,2]) with c_in_palm: google_palm = st.text_input("Google PaLM 2 API Key", cfg_private['google_palm'].get('google_palm_api', ''), help='The MakerSuite API key e.g. a 32-character string', placeholder='e.g. SATgthsykuE64FgrrrrEervr3S4455t_geyDeGq', type='password') with st.container(): with c_button_ocr: st.write("##") st.button("Test OCR", on_click=test_API, args=['google_vision',c_in_ocr, cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key, azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm]) with st.container(): with c_button_openai: st.write("##") st.button("Test OpenAI", on_click=test_API, args=['openai',c_in_openai, cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key, azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm]) with st.container(): with c_button_azure: st.write("##") st.button("Test Azure OpenAI", on_click=test_API, args=['azure_openai',c_in_azure, cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key, azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm]) with st.container(): with c_button_palm: st.write("##") st.button("Test PaLM 2", on_click=test_API, args=['palm',c_in_palm, cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key, azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm]) st.button("Set API Keys",type='primary', on_click=save_changes_to_API_keys, args=[cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key, azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm]) if st.button('Proceed to VoucherVision'): st.session_state.proceed_to_private = False st.session_state.proceed_to_main = True def test_API(api, message_loc, cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key, azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm): # Save the API keys save_changes_to_API_keys(cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key,azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm) with st.spinner('Performing validation checks...'): if api == 'google_vision': print("*** Google Vision OCR API Key ***") try: demo_config_path = os.path.join(st.session_state.dir_home,'demo','validation_configs','google_vision_ocr_test.yaml') demo_images_path = os.path.join(st.session_state.dir_home, 'demo', 'demo_images') demo_out_path = os.path.join(st.session_state.dir_home, 'demo', 'demo_output','run_name') create_google_ocr_yaml_config(demo_config_path, demo_images_path, demo_out_path) voucher_vision_OCR_test(demo_config_path, st.session_state.dir_home, None, demo_images_path) with message_loc: st.success("Google Vision OCR API Key Valid :white_check_mark:") return True except Exception as e: with message_loc: st.error(f"Google Vision OCR API Key Failed! {e}") return False elif api == 'openai': print("*** OpenAI API Key ***") try: if run_api_tests('openai'): with message_loc: st.success("OpenAI API Key Valid :white_check_mark:") else: with message_loc: st.error("OpenAI API Key Failed:exclamation:") return False except Exception as e: with message_loc: st.error(f"OpenAI API Key Failed:exclamation: {e}") elif api == 'azure_openai': print("*** Azure OpenAI API Key ***") try: if run_api_tests('azure_openai'): with message_loc: st.success("Azure OpenAI API Key Valid :white_check_mark:") else: with message_loc: st.error(f"Azure OpenAI API Key Failed:exclamation:") return False except Exception as e: with message_loc: st.error(f"Azure OpenAI API Key Failed:exclamation: {e}") elif api == 'palm': print("*** Google PaLM 2 API Key ***") try: if run_api_tests('palm'): with message_loc: st.success("Google PaLM 2 API Key Valid :white_check_mark:") else: with message_loc: st.error("Google PaLM 2 API Key Failed:exclamation:") return False except Exception as e: with message_loc: st.error(f"Google PaLM 2 API Key Failed:exclamation: {e}") def save_changes_to_API_keys(cfg_private,openai_api_key,azure_openai_api_version,azure_openai_api_key, azure_openai_api_base,azure_openai_organization,azure_openai_api_type,google_vision,google_palm): # Update the configuration dictionary with the new values cfg_private['openai']['OPENAI_API_KEY'] = openai_api_key cfg_private['openai_azure']['api_version'] = azure_openai_api_version cfg_private['openai_azure']['openai_api_key'] = azure_openai_api_key cfg_private['openai_azure']['openai_api_base'] = azure_openai_api_base cfg_private['openai_azure']['openai_organization'] = azure_openai_organization cfg_private['openai_azure']['openai_api_type'] = azure_openai_api_type cfg_private['google_cloud']['path_json_file'] = google_vision cfg_private['google_palm']['google_palm_api'] = google_palm # Call the function to write the updated configuration to the YAML file write_config_file(cfg_private, st.session_state.dir_home, filename="PRIVATE_DATA.yaml") st.session_state.private_file = does_private_file_exist() # Function to load a YAML file and update session_state def load_prompt_yaml(filename): with open(filename, 'r') as file: st.session_state['prompt_info'] = yaml.safe_load(file) st.session_state['prompt_author'] = st.session_state['prompt_info'].get('prompt_author', st.session_state['default_prompt_author']) st.session_state['prompt_author_institution'] = st.session_state['prompt_info'].get('prompt_author_institution', st.session_state['default_prompt_author_institution']) st.session_state['prompt_description'] = st.session_state['prompt_info'].get('prompt_description', st.session_state['default_prompt_description']) st.session_state['instructions'] = st.session_state['prompt_info'].get('instructions', st.session_state['default_instructions']) st.session_state['json_formatting_instructions'] = st.session_state['prompt_info'].get('json_formatting_instructions', st.session_state['default_json_formatting_instructions'] ) st.session_state['rules'] = st.session_state['prompt_info'].get('rules', {}) st.session_state['mapping'] = st.session_state['prompt_info'].get('mapping', {}) st.session_state['LLM'] = st.session_state['prompt_info'].get('LLM', 'gpt') # Placeholder: st.session_state['assigned_columns'] = list(chain.from_iterable(st.session_state['mapping'].values())) def save_prompt_yaml(filename): yaml_content = { 'prompt_author': st.session_state['prompt_author'], 'prompt_author_institution': st.session_state['prompt_author_institution'], 'prompt_description': st.session_state['prompt_description'], 'LLM': st.session_state['LLM'], 'instructions': st.session_state['instructions'], 'json_formatting_instructions': st.session_state['json_formatting_instructions'], 'rules': st.session_state['rules'], 'mapping': st.session_state['mapping'], } dir_prompt = os.path.join(st.session_state.dir_home, 'custom_prompts') filepath = os.path.join(dir_prompt, f"{filename}.yaml") with open(filepath, 'w') as file: yaml.safe_dump(dict(yaml_content), file, sort_keys=False) st.success(f"Prompt saved as '{filename}.yaml'.") def check_unique_mapping_assignments(): if len(st.session_state['assigned_columns']) != len(set(st.session_state['assigned_columns'])): st.error("Each column name must be assigned to only one category.") return False else: st.success("Mapping confirmed.") return True def check_prompt_yaml_filename(fname): # Check if the filename only contains letters, numbers, underscores, and dashes pattern = r'^[\w-]+$' # The \w matches any alphanumeric character and is equivalent to the character class [a-zA-Z0-9_]. # The hyphen - is literally matched. if re.match(pattern, fname): return True else: return False def btn_load_prompt(selected_yaml_file, dir_prompt): if selected_yaml_file: yaml_file_path = os.path.join(dir_prompt, selected_yaml_file) load_prompt_yaml(yaml_file_path) elif not selected_yaml_file: # Directly assigning default values since no file is selected st.session_state['prompt_info'] = {} st.session_state['prompt_author'] = st.session_state['default_prompt_author'] st.session_state['prompt_author_institution'] = st.session_state['default_prompt_author_institution'] st.session_state['prompt_description'] = st.session_state['default_prompt_description'] st.session_state['instructions'] = st.session_state['default_instructions'] st.session_state['json_formatting_instructions'] = st.session_state['default_json_formatting_instructions'] st.session_state['rules'] = {} st.session_state['LLM'] = 'gpt' st.session_state['assigned_columns'] = [] st.session_state['prompt_info'] = { 'prompt_author': st.session_state['prompt_author'], 'prompt_author_institution': st.session_state['prompt_author_institution'], 'prompt_description': st.session_state['prompt_description'], 'instructions': st.session_state['instructions'], 'json_formatting_instructions': st.session_state['json_formatting_instructions'], 'rules': st.session_state['rules'], 'mapping': st.session_state['mapping'], 'LLM': st.session_state['LLM'] } def build_LLM_prompt_config(): st.session_state['assigned_columns'] = [] st.session_state['default_prompt_author'] = 'unknown' st.session_state['default_prompt_author_institution'] = 'unknown' st.session_state['default_prompt_description'] = 'unknown' st.session_state['default_instructions'] = """1. Refactor the unstructured OCR text into a dictionary based on the JSON structure outlined below. 2. You should map the unstructured OCR text to the appropriate JSON key and then populate the field based on its rules. 3. Some JSON key fields are permitted to remain empty if the corresponding information is not found in the unstructured OCR text. 4. Ignore any information in the OCR text that doesn't fit into the defined JSON structure. 5. Duplicate dictionary fields are not allowed. 6. Ensure that all JSON keys are in lowercase. 7. Ensure that new JSON field values follow sentence case capitalization. 8. Ensure all key-value pairs in the JSON dictionary strictly adhere to the format and data types specified in the template. 9. Ensure the output JSON string is valid JSON format. It should not have trailing commas or unquoted keys. 10. Only return a JSON dictionary represented as a string. You should not explain your answer.""" st.session_state['default_json_formatting_instructions'] = """The next section of instructions outlines how to format the JSON dictionary. The keys are the same as those of the final formatted JSON object. For each key there is a format requirement that specifies how to transcribe the information for that key. The possible formatting options are: 1. "verbatim transcription" - field is populated with verbatim text from the unformatted OCR. 2. "spell check transcription" - field is populated with spelling corrected text from the unformatted OCR. 3. "boolean yes no" - field is populated with only yes or no. 4. "boolean 1 0" - field is populated with only 1 or 0. 5. "integer" - field is populated with only an integer. 6. "[list]" - field is populated from one of the values in the list. 7. "yyyy-mm-dd" - field is populated with a date in the format year-month-day. The desired null value is also given. Populate the field with the null value of the information for that key is not present in the unformatted OCR text.""" # Start building the Streamlit app col_prompt_main_left, ___, col_prompt_main_right = st.columns([6,1,3]) with col_prompt_main_left: st.title("Custom LLM Prompt Builder") st.subheader('About') st.write("This form allows you to craft a prompt for your specific task.") st.subheader('How it works') st.write("1. Edit this page until you are happy with your instructions. We recommend looking at the basic structure, writing down your prompt inforamtion in a Word document so that it does not randomly disappear, and then copying and pasting that info into this form once your whole prompt structure is defined.") st.write("2. After you enter all of your prompt instructions, click 'Save' and give your file a name.") st.write("3. This file will be saved as a yaml configuration file in the `..VoucherVision/custom_prompts` folder.") st.write("4. When you go back the main VoucherVision page you will now see your custom prompt available in the 'Prompt Version' dropdown menu.") st.write("5. Select your custom prompt. Note, your prompt will only be available for the LLM that you set when filling out the form below.") dir_prompt = os.path.join(st.session_state.dir_home, 'custom_prompts') yaml_files = [f for f in os.listdir(dir_prompt) if f.endswith('.yaml')] col_load_text, col_load_btn = st.columns([8,2]) with col_load_text: # Dropdown for selecting a YAML file selected_yaml_file = st.selectbox('Select a prompt YAML file to load:', [''] + yaml_files) with col_load_btn: st.write('##') # Button to load the selected prompt st.button('Load Prompt', on_click=btn_load_prompt, args=[selected_yaml_file, dir_prompt]) # Prompt Author Information st.header("Prompt Author Information") st.write("We value community contributions! Please provide your name(s) (or pseudonym if you prefer) for credit. If you leave this field blank, it will say 'unknown'.") st.session_state['prompt_author'] = st.text_input("Enter names of prompt author(s)", value=st.session_state['default_prompt_author']) st.write("Please provide your institution name. If you leave this field blank, it will say 'unknown'.") st.session_state['prompt_author_institution'] = st.text_input("Enter name of institution", value=st.session_state['default_prompt_author_institution']) st.write("Please provide a description of your prompt and its intended task. Is it designed for a specific collection? Taxa? Database structure?") st.session_state['prompt_description'] = st.text_input("Enter description of prompt", value=st.session_state['default_prompt_description']) st.write('---') st.header("Set LLM Model Type") # Define the options for the dropdown llm_options = ['gpt', 'palm'] # Create the dropdown and set the value to session_state['LLM'] st.write("Which LLM is this prompt designed for? This will not restrict its use to a specific LLM, but some prompts will behave in different ways across models.") st.write("For example, VoucherVision will automatically add multiple JSON formatting blocks to all PaLM 2 prompts to coax PaLM 2 to return a valid JSON object.") st.session_state['LLM'] = st.selectbox('Set LLM', llm_options, index=llm_options.index(st.session_state.get('LLM', 'gpt'))) st.write('---') # Instructions Section st.header("Instructions") st.write("These are the general instructions that guide the LLM through the transcription task. We recommend using the default instructions unless you have a specific reason to change them.") st.session_state['instructions'] = st.text_area("Enter instructions", value=st.session_state['default_instructions'].strip(), height=350, disabled=True) st.write('---') # Column Instructions Section st.header("JSON Formatting Instructions") st.write("The following section tells the LLM how we want to structure the JSON dictionary. We do not recommend changing this section because it would likely result in unstable and inconsistent behavior.") st.session_state['json_formatting_instructions'] = st.text_area("Enter column instructions", value=st.session_state['default_json_formatting_instructions'], height=350, disabled=True) st.write('---') col_left, col_right = st.columns([6,4]) with col_left: st.subheader('Add/Edit Columns') # Initialize rules in session state if not already present if 'rules' not in st.session_state or not st.session_state['rules']: st.session_state['rules']['Dictionary'] = { "catalog_number": { "format": "verbatim transcription", "null_value": "", "description": "The barcode identifier, typically a number with at least 6 digits, but fewer than 30 digits." } } st.session_state['rules']['SpeciesName'] = { "taxonomy": ["Genus_species"] } # Layout for adding a new column name # col_text, col_textbtn = st.columns([8, 2]) # with col_text: new_column_name = st.text_input("Enter a new column name:") # with col_textbtn: # st.write('##') if st.button("Add New Column") and new_column_name: if new_column_name not in st.session_state['rules']['Dictionary']: st.session_state['rules']['Dictionary'][new_column_name] = {"format": "", "null_value": "", "description": ""} st.success(f"New column '{new_column_name}' added. Now you can edit its properties.") else: st.error("Column name already exists. Please enter a unique column name.") # Get columns excluding the protected "catalog_number" st.write('#') editable_columns = [col for col in st.session_state['rules']['Dictionary'] if col != "catalog_number"] column_name = st.selectbox("Select a column to edit:", [""] + editable_columns) # Handle rules editing current_rule = st.session_state['rules']['Dictionary'].get(column_name, { "format": "", "null_value": "", "description": "" }) if 'selected_column' not in st.session_state: st.session_state['selected_column'] = column_name # Form for input fields with st.form(key='rule_form'): format_options = ["verbatim transcription", "spell check transcription", "boolean yes no", "boolean 1 0", "integer", "[list]", "yyyy-mm-dd"] current_rule["format"] = st.selectbox("Format:", format_options, index=format_options.index(current_rule["format"]) if current_rule["format"] else 0) current_rule["null_value"] = st.text_input("Null value:", value=current_rule["null_value"]) current_rule["description"] = st.text_area("Description:", value=current_rule["description"]) commit_button = st.form_submit_button("Commit Column") default_rule = { "format": format_options[0], # default format "null_value": "", # default null value "description": "", # default description } if st.session_state['selected_column'] != column_name: # Column has changed. Update the session_state selected column. st.session_state['selected_column'] = column_name # Reset the current rule to the default for this new column, or a blank rule if not set. current_rule = st.session_state['rules']['Dictionary'].get(column_name, default_rule.copy()) # Handle commit action if commit_button and column_name: # Commit the rules to the session state. st.session_state['rules']['Dictionary'][column_name] = current_rule.copy() st.success(f"Column '{column_name}' added/updated in rules.") # Force the form to reset by clearing the fields from the session state st.session_state.pop('selected_column', None) # Clear the selected column to force reset # st.session_state['rules'][column_name] = current_rule # st.success(f"Column '{column_name}' added/updated in rules.") # # Reset current_rule to default values for the next input # current_rule["format"] = default_rule["format"] # current_rule["null_value"] = default_rule["null_value"] # current_rule["description"] = default_rule["description"] # # To ensure that the form fields are reset, we can clear them from the session state # for key in current_rule.keys(): # st.session_state[key] = default_rule[key] # Layout for removing an existing column # del_col, del_colbtn = st.columns([8, 2]) # with del_col: delete_column_name = st.selectbox("Select a column to delete:", [""] + editable_columns, key='delete_column') # with del_colbtn: # st.write('##') if st.button("Delete Column") and delete_column_name: del st.session_state['rules'][delete_column_name] st.success(f"Column '{delete_column_name}' removed from rules.") with col_right: # Display the current state of the JSON rules st.subheader('Formatted Columns') st.json(st.session_state['rules']['Dictionary']) # st.subheader('All Prompt Info') # st.json(st.session_state['prompt_info']) st.write('---') col_left_mapping, col_right_mapping = st.columns([6,4]) with col_left_mapping: st.header("Mapping") st.write("Assign each column name to a single category.") st.session_state['refresh_mapping'] = False # Dynamically create a list of all column names that can be assigned # This assumes that the column names are the keys in the dictionary under 'rules' all_column_names = list(st.session_state['rules']['Dictionary'].keys()) categories = ['TAXONOMY', 'GEOGRAPHY', 'LOCALITY', 'COLLECTING', 'MISCELLANEOUS'] if ('mapping' not in st.session_state) or (st.session_state['mapping'] == {}): st.session_state['mapping'] = {category: [] for category in categories} for category in categories: # Filter out the already assigned columns available_columns = [col for col in all_column_names if col not in st.session_state['assigned_columns'] or col in st.session_state['mapping'].get(category, [])] # Ensure the current mapping is a subset of the available options current_mapping = [col for col in st.session_state['mapping'].get(category, []) if col in available_columns] # Provide a safe default if the current mapping is empty or contains invalid options safe_default = current_mapping if all(col in available_columns for col in current_mapping) else [] # Create a multi-select widget for the category with a safe default selected_columns = st.multiselect( f"Select columns for {category}:", available_columns, default=safe_default, key=f"mapping_{category}" ) # Update the assigned_columns based on the selections for col in current_mapping: if col not in selected_columns and col in st.session_state['assigned_columns']: st.session_state['assigned_columns'].remove(col) st.session_state['refresh_mapping'] = True for col in selected_columns: if col not in st.session_state['assigned_columns']: st.session_state['assigned_columns'].append(col) st.session_state['refresh_mapping'] = True # Update the mapping in session state when there's a change st.session_state['mapping'][category] = selected_columns if st.session_state['refresh_mapping']: st.session_state['refresh_mapping'] = False # Button to confirm and save the mapping configuration if st.button('Confirm Mapping'): if check_unique_mapping_assignments(): # Proceed with further actions since the mapping is confirmed and unique pass with col_right_mapping: # Display the current state of the JSON rules st.subheader('Formatted Column Maps') st.json(st.session_state['mapping']) col_left_save, col_right_save = st.columns([6,4]) with col_left_save: # Input for new file name new_filename = st.text_input("Enter filename to save your prompt as a configuration YAML:",placeholder='my_prompt_name') # Button to save the new YAML file if st.button('Save YAML', type='primary'): if new_filename: if check_unique_mapping_assignments(): if check_prompt_yaml_filename(new_filename): save_prompt_yaml(new_filename) else: st.error("File name can only contain letters, numbers, underscores, and dashes. Cannot contain spaces.") else: st.error("Mapping contains an error. Make sure that each column is assigned to only ***one*** category.") else: st.error("Please enter a filename.") if st.button('Exit'): st.session_state.proceed_to_build_llm_prompt = False st.session_state.proceed_to_main = True st.rerun() with col_prompt_main_right: st.subheader('All Prompt Components') st.session_state['prompt_info'] = { 'prompt_author': st.session_state['prompt_author'], 'prompt_author_institution': st.session_state['prompt_author_institution'], 'prompt_description': st.session_state['prompt_description'], 'LLM': st.session_state['LLM'], 'instructions': st.session_state['instructions'], 'json_formatting_instructions': st.session_state['json_formatting_instructions'], 'rules': st.session_state['rules'], 'mapping': st.session_state['mapping'], } st.json(st.session_state['prompt_info']) def show_header_welcome(): st.session_state.logo_path = os.path.join(st.session_state.dir_home, 'img','logo.png') st.session_state.logo = Image.open(st.session_state.logo_path) st.image(st.session_state.logo, width=250) def determine_n_images(): try: # Check if 'dir_uploaded_images' key exists and it is not empty if 'dir_uploaded_images' in st and st['dir_uploaded_images']: dir_path = st['dir_uploaded_images'] # This would be the path to the directory return len([f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]) else: return None except: return None def content_header(): col_run_1, col_run_2, col_run_3 = st.columns([4,4,2]) col_test = st.container() st.write("") st.write("") st.write("") st.write("") st.subheader("Overall Progress") col_run_info_1 = st.columns([1])[0] st.write("") st.write("") st.write("") st.write("") st.header("Configuration Settings") with col_run_info_1: # Progress # Progress # st.subheader('Project') # bar = st.progress(0) # new_text = st.empty() # Placeholder for current step name # progress_report = ProgressReportVV(bar, new_text, n_images=10) # Progress overall_progress_bar = st.progress(0) text_overall = st.empty() # Placeholder for current step name st.subheader('Transcription Progress') batch_progress_bar = st.progress(0) text_batch = st.empty() # Placeholder for current step name progress_report = ProgressReport(overall_progress_bar, batch_progress_bar, text_overall, text_batch) st.info("***Note:*** There is a known bug with tabs in Streamlit. If you update an input field it may take you back to the 'Project Settings' tab. Changes that you made are saved, it's just an annoying glitch. We are aware of this issue and will fix it as soon as we can.") st.write("If you use VoucherVision frequently, you can change the default values that are auto-populated in the form below. In a text editor or IDE, edit the first few rows in the file `../VoucherVision/vouchervision/VoucherVision_Config_Builder.py`") with col_run_1: show_header_welcome() st.subheader('Run VoucherVision') N_STEPS = 6 if determine_n_images(): st.session_state['processing_add_on'] = f" {determine_n_images()} Images" else: st.session_state['processing_add_on'] = '' if check_if_usable(): if st.button(f"Start Processing{st.session_state['processing_add_on']}", type='primary'): # Define number of overall steps progress_report.set_n_overall(N_STEPS) progress_report.update_overall(f"Starting VoucherVision...") # First, write the config file. write_config_file(st.session_state.config, st.session_state.dir_home, filename="VoucherVision.yaml") path_custom_prompts = os.path.join(st.session_state.dir_home,'custom_prompts',st.session_state.config['leafmachine']['project']['prompt_version']) # Call the machine function. last_JSON_response, total_cost = voucher_vision(None, st.session_state.dir_home, path_custom_prompts, None, progress_report,path_api_cost=os.path.join(st.session_state.dir_home,'api_cost','api_cost.yaml'), is_real_run=True) if total_cost: st.success(f":money_with_wings: This run cost :heavy_dollar_sign:{total_cost:.4f}") # Format the JSON string for display. if last_JSON_response is None: st.markdown(f"Last JSON object in the batch: NONE") else: try: formatted_json = json.dumps(json.loads(last_JSON_response), indent=4, sort_keys=False) except: formatted_json = json.dumps(last_JSON_response, indent=4, sort_keys=False) st.markdown(f"Last JSON object in the batch:\n```\n{formatted_json}\n```") st.balloons() else: st.button("Start Processing", type='primary', disabled=True) st.error(":heavy_exclamation_mark: Required API keys not set. Please visit the 'API Keys' tab and set the Google Vision OCR API key and at least one LLM key.") st.button("Refresh", on_click=refresh) with col_run_2: if st.button("Test GPT"): progress_report.set_n_overall(TestOptionsGPT.get_length()) test_results, JSON_results = run_demo_tests_GPT(progress_report) with col_test: display_test_results(test_results, JSON_results, 'gpt') st.balloons() if st.button("Test PaLM2"): progress_report.set_n_overall(TestOptionsPalm.get_length()) test_results, JSON_results = run_demo_tests_Palm(progress_report) with col_test: display_test_results(test_results, JSON_results, 'palm') st.balloons() with col_run_3: st.subheader('Check GPU') if st.button("GPU"): success, info = test_GPU() if success: st.balloons() for message in info: st.success(message) else: for message in info: st.error(message) def content_tab_settings(): st.header('Project') col_project_1, col_project_2 = st.columns([4,2]) st.write("---") st.header('Input Images') col_local_1, col_local_2 = st.columns([4,2]) st.write("---") st.header('LeafMachine2 Label Collage') col_cropped_1, col_cropped_2 = st.columns([4,4]) st.write("---") st.header('OCR Overlay Image') col_ocr_1, col_ocr_2 = st.columns([4,4]) os.path.join(st.session_state.dir_home, ) ### Project with col_project_1: st.session_state.config['leafmachine']['project']['run_name'] = st.text_input("Run name", st.session_state.config['leafmachine']['project'].get('run_name', '')) st.session_state.config['leafmachine']['project']['dir_output'] = st.text_input("Output directory", st.session_state.config['leafmachine']['project'].get('dir_output', '')) ### Input Images Local with col_local_1: st.session_state.config['leafmachine']['project']['dir_images_local'] = st.text_input("Input images directory", st.session_state.config['leafmachine']['project'].get('dir_images_local', '')) st.session_state.config['leafmachine']['project']['continue_run_from_partial_xlsx'] = st.text_input("Continue run from partially completed project XLSX", st.session_state.config['leafmachine']['project'].get('continue_run_from_partial_xlsx', ''), disabled=True) st.write("---") st.subheader('LLM Version') st.markdown( """ ***Note:*** GPT-4 is 20x more expensive than GPT-3.5 """ ) st.session_state.config['leafmachine']['LLM_version'] = st.selectbox("LLM version", ["gpt-4-1106-preview", "GPT 4", "GPT 3.5", "Azure GPT 4", "Azure GPT 3.5", "PaLM 2"], index=["gpt-4-1106-preview", "GPT 4", "GPT 3.5", "Azure GPT 4", "Azure GPT 3.5", "PaLM 2"].index(st.session_state.config['leafmachine'].get('LLM_version', 'Azure GPT 4'))) st.write("---") st.subheader('Prompt Version') versions, default_version = get_prompt_versions(st.session_state.config['leafmachine']['LLM_version']) if versions: selected_version = st.session_state.config['leafmachine']['project'].get('prompt_version', default_version) if selected_version not in versions: selected_version = default_version st.session_state.config['leafmachine']['project']['prompt_version'] = st.selectbox("Prompt Version", versions, index=versions.index(selected_version)) with col_cropped_1: default_crops = st.session_state.config['leafmachine']['cropped_components'].get('save_cropped_annotations', ['leaf_whole']) st.write("Prior to transcription, use LeafMachine2 to crop all labels from input images to create label collages for each specimen image. (Requires GPU)") st.session_state.config['leafmachine']['use_RGB_label_images'] = st.checkbox("Use LeafMachine2 label collage for transcriptions", st.session_state.config['leafmachine'].get('use_RGB_label_images', False)) st.session_state.config['leafmachine']['cropped_components']['save_cropped_annotations'] = st.multiselect("Components to crop", ['ruler', 'barcode','label', 'colorcard','map','envelope','photo','attached_item','weights', 'leaf_whole', 'leaf_partial', 'leaflet', 'seed_fruit_one', 'seed_fruit_many', 'flower_one', 'flower_many', 'bud','specimen','roots','wood'],default=default_crops) with col_cropped_2: ba = os.path.join(st.session_state.dir_home,'demo', 'ba','ba2.png') image = Image.open(ba) st.image(image, caption='LeafMachine2 Collage', output_format = "PNG") with col_ocr_1: st.write('This will plot bounding boxes around all text that Google Vision was able to detect. If there are no boxes around text, then the OCR failed, so that missing text will not be seen by the LLM when it is creating the JSON object. The created image will be viewable in the VoucherVisionEditor.') st.session_state.config['leafmachine']['do_create_OCR_helper_image'] = st.checkbox("Create image showing an overlay of the OCR detections", st.session_state.config['leafmachine'].get('do_create_OCR_helper_image', False)) with col_ocr_2: ocr = os.path.join(st.session_state.dir_home,'demo', 'ba','ocr.png') image_ocr = Image.open(ocr) st.image(image_ocr, caption='OCR Overlay Images', output_format = "PNG") def content_tab_component(): st.header('Archival Components') ACD_version = st.selectbox("Archival Component Detector (ACD) Version", ["Version 2.1", "Version 2.2"]) ACD_confidence_default = int(st.session_state.config['leafmachine']['archival_component_detector']['minimum_confidence_threshold'] * 100) ACD_confidence = st.number_input("ACD Confidence Threshold (%)", min_value=0, max_value=100,value=ACD_confidence_default) st.session_state.config['leafmachine']['archival_component_detector']['minimum_confidence_threshold'] = float(ACD_confidence/100) st.session_state.config['leafmachine']['archival_component_detector']['do_save_prediction_overlay_images'] = st.checkbox("Save Archival Prediction Overlay Images", st.session_state.config['leafmachine']['archival_component_detector'].get('do_save_prediction_overlay_images', True)) st.session_state.config['leafmachine']['archival_component_detector']['ignore_objects_for_overlay'] = st.multiselect("Hide Archival Components in Prediction Overlay Images", ['ruler', 'barcode','label', 'colorcard','map','envelope','photo','attached_item','weights',], default=[]) # Depending on the selected version, set the configuration if ACD_version == "Version 2.1": st.session_state.config['leafmachine']['archival_component_detector']['detector_type'] = 'Archival_Detector' st.session_state.config['leafmachine']['archival_component_detector']['detector_version'] = 'PREP_final' st.session_state.config['leafmachine']['archival_component_detector']['detector_iteration'] = 'PREP_final' st.session_state.config['leafmachine']['archival_component_detector']['detector_weights'] = 'best.pt' elif ACD_version == "Version 2.2": #TODO update this to version 2.2 st.session_state.config['leafmachine']['archival_component_detector']['detector_type'] = 'Archival_Detector' st.session_state.config['leafmachine']['archival_component_detector']['detector_version'] = 'PREP_final' st.session_state.config['leafmachine']['archival_component_detector']['detector_iteration'] = 'PREP_final' st.session_state.config['leafmachine']['archival_component_detector']['detector_weights'] = 'best.pt' def content_tab_processing(): st.header('Processing Options') col_processing_1, col_processing_2 = st.columns([2,2,]) with col_processing_1: st.subheader('Compute Options') st.session_state.config['leafmachine']['project']['num_workers'] = st.number_input("Number of CPU workers", value=st.session_state.config['leafmachine']['project'].get('num_workers', 1), disabled=True) st.session_state.config['leafmachine']['project']['batch_size'] = st.number_input("Batch size", value=st.session_state.config['leafmachine']['project'].get('batch_size', 500), help='Sets the batch size for the LeafMachine2 cropping. If computer RAM is filled, lower this value to ~100.') with col_processing_2: st.subheader('Misc') st.session_state.config['leafmachine']['project']['prefix_removal'] = st.text_input("Remove prefix from catalog number", st.session_state.config['leafmachine']['project'].get('prefix_removal', '')) st.session_state.config['leafmachine']['project']['suffix_removal'] = st.text_input("Remove suffix from catalog number", st.session_state.config['leafmachine']['project'].get('suffix_removal', '')) st.session_state.config['leafmachine']['project']['catalog_numerical_only'] = st.checkbox("Require 'Catalog Number' to be numerical only", st.session_state.config['leafmachine']['project'].get('catalog_numerical_only', True)) ### Logging and Image Validation - col_v1 st.header('Logging and Image Validation') col_v1, col_v2 = st.columns(2) with col_v1: st.session_state.config['leafmachine']['do']['check_for_illegal_filenames'] = st.checkbox("Check for illegal filenames", st.session_state.config['leafmachine']['do'].get('check_for_illegal_filenames', True)) st.session_state.config['leafmachine']['do']['check_for_corrupt_images_make_vertical'] = st.checkbox("Check for corrupt images", st.session_state.config['leafmachine']['do'].get('check_for_corrupt_images_make_vertical', True)) st.session_state.config['leafmachine']['print']['verbose'] = st.checkbox("Print verbose", st.session_state.config['leafmachine']['print'].get('verbose', True)) st.session_state.config['leafmachine']['print']['optional_warnings'] = st.checkbox("Show optional warnings", st.session_state.config['leafmachine']['print'].get('optional_warnings', True)) with col_v2: log_level = st.session_state.config['leafmachine']['logging'].get('log_level', None) log_level_display = log_level if log_level is not None else 'default' selected_log_level = st.selectbox("Logging Level", ['default', 'DEBUG', 'INFO', 'WARNING', 'ERROR'], index=['default', 'DEBUG', 'INFO', 'WARNING', 'ERROR'].index(log_level_display)) if selected_log_level == 'default': st.session_state.config['leafmachine']['logging']['log_level'] = None else: st.session_state.config['leafmachine']['logging']['log_level'] = selected_log_level def content_tab_domain(): st.header('Embeddings Database') col_emb_1, col_emb_2 = st.columns([4,2]) with col_emb_1: st.markdown( """ VoucherVision includes the option of using domain knowledge inside of the dynamically generated prompts. The OCR text is queried against a database of existing label transcriptions. The most similar existing transcriptions act as an example of what the LLM should emulate and are shown to the LLM as JSON objects. VoucherVision uses cosine similarity search to return the most similar existing transcription. - Note: Using domain knowledge may increase the chance that foreign text is included in the final transcription - Disabling this feature will show the LLM multiple examples of an empty JSON skeleton structure instead - Enabling this option requires a GPU with at least 8GB of VRAM - The domain knowledge files can be located in the directory "../VoucherVision/domain_knowledge". On first run the embeddings database must be created, which takes time. If the database creation runs each time you use VoucherVision, then something is wrong. """ ) st.write(f"Domain Knowledge is only available for the following prompts:") for available_prompts in PROMPTS_THAT_NEED_DOMAIN_KNOWLEDGE: st.markdown(f"- {available_prompts}") if st.session_state.config['leafmachine']['project']['prompt_version'] in PROMPTS_THAT_NEED_DOMAIN_KNOWLEDGE: st.session_state.config['leafmachine']['project']['use_domain_knowledge'] = st.checkbox("Use domain knowledge", True, disabled=True) else: st.session_state.config['leafmachine']['project']['use_domain_knowledge'] = st.checkbox("Use domain knowledge", False, disabled=True) st.write("") if st.session_state.config['leafmachine']['project']['use_domain_knowledge']: st.session_state.config['leafmachine']['project']['embeddings_database_name'] = st.text_input("Embeddings database name (only use underscores)", st.session_state.config['leafmachine']['project'].get('embeddings_database_name', '')) st.session_state.config['leafmachine']['project']['build_new_embeddings_database'] = st.checkbox("Build *new* embeddings database", st.session_state.config['leafmachine']['project'].get('build_new_embeddings_database', False)) st.session_state.config['leafmachine']['project']['path_to_domain_knowledge_xlsx'] = st.text_input("Path to domain knowledge CSV file (will be used to create new embeddings database)", st.session_state.config['leafmachine']['project'].get('path_to_domain_knowledge_xlsx', '')) else: st.session_state.config['leafmachine']['project']['embeddings_database_name'] = st.text_input("Embeddings database name (only use underscores)", st.session_state.config['leafmachine']['project'].get('embeddings_database_name', ''), disabled=True) st.session_state.config['leafmachine']['project']['build_new_embeddings_database'] = st.checkbox("Build *new* embeddings database", st.session_state.config['leafmachine']['project'].get('build_new_embeddings_database', False), disabled=True) st.session_state.config['leafmachine']['project']['path_to_domain_knowledge_xlsx'] = st.text_input("Path to domain knowledge CSV file (will be used to create new embeddings database)", st.session_state.config['leafmachine']['project'].get('path_to_domain_knowledge_xlsx', ''), disabled=True) def render_expense_report_summary(): expense_summary = st.session_state.expense_summary expense_report = st.session_state.expense_report st.header('Expense Report Summary') if expense_summary: st.metric(label="Total Cost", value=f"${round(expense_summary['total_cost_sum'], 4):,}") col1, col2 = st.columns(2) # Run count and total costs with col1: st.metric(label="Run Count", value=expense_summary['run_count']) st.metric(label="Tokens In", value=f"{expense_summary['tokens_in_sum']:,}") # Token information with col2: st.metric(label="Total Images", value=expense_summary['n_images_sum']) st.metric(label="Tokens Out", value=f"{expense_summary['tokens_out_sum']:,}") # Calculate cost proportion per image for each API version st.subheader('Average Cost per Image by API Version') cost_labels = [] cost_values = [] total_images = 0 cost_per_image_dict = {} # Iterate through the expense report to accumulate costs and image counts for index, row in expense_report.iterrows(): api_version = row['api_version'] total_cost = row['total_cost'] n_images = row['n_images'] total_images += n_images # Keep track of total images processed if api_version not in cost_per_image_dict: cost_per_image_dict[api_version] = {'total_cost': 0, 'n_images': 0} cost_per_image_dict[api_version]['total_cost'] += total_cost cost_per_image_dict[api_version]['n_images'] += n_images api_versions = list(cost_per_image_dict.keys()) colors = [COLORS_EXPENSE_REPORT[version] if version in COLORS_EXPENSE_REPORT else '#DDDDDD' for version in api_versions] # Calculate the cost per image for each API version for version, cost_data in cost_per_image_dict.items(): total_cost = cost_data['total_cost'] n_images = cost_data['n_images'] # Calculate the cost per image for this version cost_per_image = total_cost / n_images if n_images > 0 else 0 cost_labels.append(version) cost_values.append(cost_per_image) # Generate the pie chart cost_pie_chart = go.Figure(data=[go.Pie(labels=cost_labels, values=cost_values, hole=.3)]) # Update traces for custom text in hoverinfo, displaying cost with a dollar sign and two decimal places cost_pie_chart.update_traces( marker=dict(colors=colors), text=[f"${value:.2f}" for value in cost_values], # Formats the cost as a string with a dollar sign and two decimals textinfo='percent+label', hoverinfo='label+percent+text' # Adds custom text (formatted cost) to the hover information ) st.plotly_chart(cost_pie_chart, use_container_width=True) st.subheader('Proportion of Total Cost by API Version') cost_labels = [] cost_proportions = [] total_cost_by_version = {} # Sum the total cost for each API version for index, row in expense_report.iterrows(): api_version = row['api_version'] total_cost = row['total_cost'] if api_version not in total_cost_by_version: total_cost_by_version[api_version] = 0 total_cost_by_version[api_version] += total_cost # Calculate the combined total cost for all versions combined_total_cost = sum(total_cost_by_version.values()) # Calculate the proportion of total cost for each API version for version, total_cost in total_cost_by_version.items(): proportion = (total_cost / combined_total_cost) * 100 if combined_total_cost > 0 else 0 cost_labels.append(version) cost_proportions.append(proportion) # Generate the pie chart cost_pie_chart = go.Figure(data=[go.Pie(labels=cost_labels, values=cost_proportions, hole=.3)]) # Update traces for custom text in hoverinfo cost_pie_chart.update_traces( marker=dict(colors=colors), text=[f"${cost:.2f}" for cost in total_cost_by_version.values()], # This will format the cost to 2 decimal places textinfo='percent+label', hoverinfo='label+percent+text' # This tells Plotly to show the label, percent, and custom text (cost) on hover ) st.plotly_chart(cost_pie_chart, use_container_width=True) # API version usage percentages pie chart st.subheader('Runs by API Version') api_versions = list(expense_summary['api_version_percentages'].keys()) percentages = [expense_summary['api_version_percentages'][version] for version in api_versions] pie_chart = go.Figure(data=[go.Pie(labels=api_versions, values=percentages, hole=.3)]) pie_chart.update_layout(margin=dict(t=0, b=0, l=0, r=0)) pie_chart.update_traces(marker=dict(colors=colors),) st.plotly_chart(pie_chart, use_container_width=True) else: st.error('No expense report data available.') def sidebar_content(): if not os.path.exists(os.path.join(st.session_state.dir_home,'expense_report')):
validate_dir(os.path.join(st.session_state.dir_home,'expense_report'))
14
2023-10-30 23:25:20+00:00
16k
medsagou/massar-direction-sagoubot
main.py
[ { "identifier": "C_File", "path": "utilities/Class_Files.py", "snippet": "class C_File():\n #____________________________________________________________________________________________________________________________________________________________\n # Le constructeur d'une instance d'un fichier\...
import tkinter as tk import customtkinter import time import os import threading import logging import sys from tkinter import filedialog from PIL import Image from validate_email import validate_email from utilities import C_File, C_Dossier from dotenv import set_key, load_dotenv from absence_app import Read_Db from absence_app import Absence from Interaction_browser import Massar_Direction_Sagou
13,411
self.run_bot = customtkinter.CTkButton(self.tabview_fill_bot.tab("Review & Submit"), text="Run", command=self.run_bot_interaction, width=50) self.run_bot.grid(row=6, column=5, padx=10, pady=(5, 5)) self.return_btn5 = customtkinter.CTkButton(self.tabview_fill_bot.tab("Review & Submit"), text="Back", command=self.back2, width=50, fg_color="gray30") self.return_btn5.grid(row=6, column=4, padx=10, pady=(5, 5)) if self.about_us_text is not None: self.about_us_text.grid_remove() self.about_us_logo.grid_remove() self.console_text.grid() self.try_again_fill = True self.select_frame_by_name("Fill Absence Bot") else: self.tabview_generate_lists.grid_remove() self.tabview_fill_bot.grid() self.console_text.grid() if self.about_us_text is not None: self.about_us_text.grid_remove() self.about_us_logo.grid_remove() self.select_frame_by_name("Fill Absence Bot") def about_us_button_event(self): if self.tabview_generate_lists.grid_info(): self.tabview_generate_lists.grid_remove() if self.tabview_fill_bot is not None: if self.tabview_fill_bot.grid_info(): self.tabview_fill_bot.grid_remove() if self.about_us_text is not None: self.about_us_text.grid() self.about_us_logo.grid() self.console_text.grid_remove() self.select_frame_by_name("About us") else: self.about_us_logo = customtkinter.CTkLabel(self, text="", image=self.about_us_image) self.about_us_logo.grid(row=0, column=1, padx=10, pady=10) self.about_us_text = customtkinter.CTkTextbox(self, height=200, wrap="word", font=("Arial", 18)) self.about_us_text.grid(row=1, column=1,rowspan=3, columnspan=6, padx=(20, 20), pady = (15, 20), sticky = "nsew") self.console_text.grid_remove() self.about_us_text.tag_config("Title", foreground="gray92") self.about_us_text.tag_config("subTitle", foreground="gray65") self.about_us_text.tag_config("Paragraph", foreground="gray50") # Content to be displayed # Insert the formatted text into the Text widget self.about_us_text.insert("end", "\n About Us", "LargeText") self.about_us_text.insert("end", "\n\nMassar Direction Sagoubot is a cutting-edge automation project designed to streamline and simplify the process of managing absence data for multiple classes within a web application. Our solution is meticulously crafted using modern technologies and software tools to optimize efficiency and save valuable time for teachers and administrators.\n", "Paragraph") self.about_us_text.insert("end", "\n\n Terms and Privacy", "Title") self.about_us_text.insert("end", "\n\nAccount Access", "subTitle") self.about_us_text.insert("end", "\nTo enhance your experience with Massar Direction Sagoubot, the application utilizes your account credentials to securely log in to the Massar website. Your privacy and security are of utmost importance to us. We ensure that your login information is encrypted and used solely for the purpose of automating absence data management.\n", "Paragraph") self.about_us_text.insert("end", "\n\nData Handling", "subTitle") self.about_us_text.insert("end", "\nYour data, specifically related to absence records and class information, is processed within the confines of the application to facilitate automation. We do not store or retain any of your personal data beyond the scope of improving application functionality.\n", "Paragraph") self.about_us_text.insert("end", "\n\nSecurity Measures", "subTitle") self.about_us_text.insert("end", "\nWe employ industry-standard security measures to safeguard your account information. This includes encryption protocols and best practices to prevent unauthorized access or misuse of your credentials.\n", "Paragraph") self.about_us_text.insert("end", "\n\nUser Consent", "subTitle") self.about_us_text.insert("end", "\nBy using Massar Direction Sagoubot, you consent to the utilization of your Massar account credentials for the sole purpose of automating absence data management. We prioritize transparency and security in handling your login information.\n", "Paragraph") self.about_us_text.insert("end", "\n\nQuestions or Concerns", "subTitle") self.about_us_text.insert("end", "\nIf you have any questions, concerns, or require further clarification regarding our terms, privacy practices, or the usage of your account information, please feel free to reach out to us at sakou81833@gmail.com. Your satisfaction and trust are our top priorities.\n", "Paragraph") self.about_us_text.configure(state="disabled") self.select_frame_by_name("About us") def exit(self): result = tk.messagebox.askokcancel("Confirmation", "Are you sure you want to exit?") if result: # If the user confirms app.quit() # backend functions def generate_absence_file(self): self.generate_progress_bar() self.submit3.configure(state="disabled") self.return_btn3.configure(state="disabled") self.console_text.configure(state="normal") self.label_all_review1.configure(text_color="gray35") def run_fill_all_class_sheets(): reader = Read_Db(input_file=self.entry_path.get(), template_file=self.entry_path2.get(), output_file=str(self.output_path.get()) + "\\absence.xlsx", required_classes=self.selected_classes, progress_bar=self.progressbar_1, console=self.console_text) reader.fill_all_class_sheets() time.sleep(3) self.submit3.configure(state="normal") self.return_btn3.configure(state="normal") self.progressbar_1.grid_remove() self.console_text.configure(state="disabled") self.label_all_review1.configure(text_color="gray70") thread = threading.Thread(target=run_fill_all_class_sheets) thread.start() return def run_bot_interaction(self): self.generate_progress_bar(determinate=False) self.console_text.configure(state="normal") self.run_bot.configure(state="disabled") self.return_btn5.configure(state="disabled") self.label_all_review2.configure(text_color="gray35") def run_fill_absence(): # loading the class here because of the .env file not getting refreshed interaction_object = Massar_Direction_Sagou(console=self.console_text) driver_test = interaction_object.main_interaction() if driver_test: interaction_object.get_list_page()
# https://stackoverflow.com/questions/31836104/pyinstaller-and-onefile-how-to-include-an-image-in-the-exe-file def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS2 except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) logging.basicConfig(filename='app.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') customtkinter.set_appearance_mode("Dark") # Modes: "System" (standard), "Dark", "Light" customtkinter.set_default_color_theme("dark-blue") # Themes: "blue" (standard), "green", "dark-blue" dirPath = os.path.dirname(os.path.realpath(__file__)) class App(customtkinter.CTk): def __init__(self): super().__init__() self.tabview_generate_lists = None self.tabview_fill_bot= None self.generate_list_menu = None self.about_us_text = None self.fill_absence_menu = None self.try_again_generate = False self.try_again_fill = False self.progressbar_1 = None image_path = resource_path("images") self.main_logo_image = customtkinter.CTkImage( light_image=Image.open(os.path.join(image_path, "logo_black.png")), dark_image=Image.open(os.path.join(image_path, "logo_white.png")), size=(200,200)) self.about_us_image = customtkinter.CTkImage( light_image=Image.open(os.path.join(image_path, "logo_black.png")), dark_image=Image.open(os.path.join(image_path, "logo_white.png")), size=(150, 150)) # self.main_logo_photo = ImageTk.PhotoImage(self.main_logo_image) # configure window self.title("SagouBot Massar Direction") self.iconbitmap(resource_path("icon.ico")) self.geometry(f"{1100}x{580}") # configure grid layout (4x4) self.grid_columnconfigure(1, weight=1) self.grid_columnconfigure((2, 3), weight=0) self.grid_rowconfigure((0, 1, 2), weight=1) # create sidebar frame with widgets self.sidebar_frame = customtkinter.CTkFrame(self, width=200, corner_radius=0) self.sidebar_frame.grid(row=0, column=0, rowspan=4, sticky="nsew") self.sidebar_frame.grid_rowconfigure(5, weight=1) self.sidebar_frame.grid(row=0, column=0) self.sideBar_logo = customtkinter.CTkLabel(self.sidebar_frame, text="", image=self.main_logo_image) self.sideBar_logo.grid(row=5, column=0, padx=20, pady=20) self.entry_default_bordercolor = customtkinter.CTkEntry(self).cget("border_color") # self.logo_label = customtkinter.CTkLabel(self.sidebar_frame, text="SagouBot", font=customtkinter.CTkFont(size=40, weight="bold")) # self.logo_label.grid(row=1, column=0, padx=20, pady=(20, 10)) self.generate_list_menu_button_event() # Console (Text area) self.console_text = customtkinter.CTkTextbox(self, height=200, width=400, fg_color="gray1") self.console_text.insert("0.0", "CONSOLE") self.console_text.insert(F"{len('CONSOLE')}.0", "--------" * 28) self.console_text.configure(state="disabled") self.console_text.grid(row=1, column=1, padx=(20, 20), pady=(5, 15), sticky="nsew") self.console_text.tag_config("error", foreground="red") self.console_text.tag_config("note", foreground="orange") self.console_text.tag_config("successes", foreground="blue") # self.generate_progress_bar() # Progress Bar # progress_bar = customtkinter.CTkProgressBar(self, mode='determinate') # progress_bar.grid(row=1, column=1, padx=(20, 20), pady=(5, 0), sticky="nsew") # # Button to trigger updates # update_button = customtkinter.CTkButton(self, text="Start Processing", command=()) # update_button.grid(row=1, column=1, padx=(20, 20), pady=(5, 0), sticky="nsew") def high_school_switch(self): state = self.high_school_options.get() options = [self.TCS, self.TCSF, self.TCLSH, self.BACSC, self.BACSH, self.BACSE, self.BACSVT, self.BACSH2] if state: for option in options: option.configure(state="normal") else: for option in options: option.configure(state="disabled") return def college_switch(self): state = self.college_options.get() if state: self.college_generale.configure(state="normal") self.college_aspeb.configure(state="normal") self.college_inter.configure(state="normal") else: self.college_generale.configure(state="disabled") self.college_aspeb.configure(state="disabled") self.college_inter.configure(state="disabled") def college_label_error(self): current_text = self.label_college.cget("text") self.label_college.configure(text=current_text.replace("*", "") + "*", text_color="red") return def high_school_label_eroor(self): current_text = self.label_high_school.cget("text") self.label_high_school.configure(text=current_text.replace("*", "") + "*", text_color="red") return def reset_label_high_college(self): current_text1 = self.label_college.cget("text") current_text = self.label_high_school.cget("text") self.label_high_school.configure(text=current_text.replace("*", ""), text_color="gray90") self.label_college.configure(text=current_text1.replace("*", ""), text_color="gray90") def label_data_file_error(self): current_text = self.label_data_file.cget("text") self.label_data_file.configure(text=current_text.replace("*", "") + "*", text_color="red") return def label_template_file_error(self): current_text = self.label_template_entry.cget("text") self.label_template_entry.configure(text=current_text.replace("*", "") + "*", text_color="red") return def reset_error1(self): current_text = self.label_data_file.cget("text") self.label_data_file.configure(text=current_text.replace("*", ""), text_color="gray90") return def reset_error2(self): current_text = self.label_template_entry.cget("text") self.label_template_entry.configure(text=current_text.replace("*", ""), text_color="gray90") return def directory_error(self): current_text = self.label_output_folder.cget("text") self.label_output_folder.configure(text=current_text + "*", text_color="red") return def reset_error3(self): current_text = self.label_output_folder.cget("text") self.label_output_folder.configure(text=current_text.replace("*", ""), text_color="gray90") return def go_to_review2(self): if self.email_entry.get() == "" or self.password_entry.get() == "" or not self.validate_path(self.entry_path_absence) or not self.check_terms_and_condition.get(): if self.email_entry.get() == "": self.error_label(self.label_email_entry) self.entry_error(self.email_entry) if len(self.password_entry.get()) < 8: self.error_label(self.label_password_entry) self.entry_error(self.password_entry) if not self.validate_path(self.entry_path_absence): self.error_label(self.label_absence_data_file) self.entry_error(self.entry_path_absence) if not self.check_terms_and_condition.get(): self.check_terms_and_condition.configure(border_color="red", text_color="red") self.error_label(self.label_terms) else: paths = C_File(resource_path("db/paths.txt")) L = paths.fichier_to_Liste() L[3] = "ABSENCE_FILE" + "=" + self.entry_path_absence.get() +"\n" L[4] = "EMAIL" + "=" + self.email_entry.get() +"\n" paths.Liste_to_Fichier(L) set_key(dotenv_path=os.path.join(dirPath,".env"), key_to_set="EMAIL", value_to_set=self.email_entry.get()) set_key(dotenv_path=os.path.join(dirPath,".env"), key_to_set="PASSWORD", value_to_set=self.password_entry.get()) load_dotenv(dotenv_path=os.path.join(dirPath,".env")) self.tabview_fill_bot.set("Review & Submit") self.label_all_review2 = customtkinter.CTkTextbox(self.tabview_fill_bot.tab("Review & Submit")) self.label_all_review2.grid(row=0, column=0, columnspan=6, sticky="nsew") # self.label_all_review2.insert("1.0", text) text = f"Email:" text += " " * (30 - len("Email:")) text += str(self.email_entry.get()) + "\n\n" self.label_all_review2.insert("end", text) text = "Absence Excel File:" text += " " * (30 - len("Absence Excel File:")) text += str(self.entry_path_absence.get())+ "\n\n" self.label_all_review2.insert("end", text) text = "Browser:" text += " " * (30 - len("Browser:")) if self.browser_type.get() == 2: text += "FireFox" else: text += "Chrome" self.label_all_review2.insert("end", text) self.label_all_review2.configure(state="disabled", text_color="gray70") return def go_to_output_location(self): if self.tabview_generate_lists.grid_info(): tabview = self.tabview_generate_lists tab = tabview.get() optionsHighSchool = [self.TCS, self.TCSF, self.TCLSH, self.BACSC, self.BACSH, self.BACSE, self.BACSVT, self.BACSH2] optionsCollege = [ self.college_inter, self.college_aspeb, self.college_generale ] selected_classes = [] paths = C_File(resource_path("db/paths.txt")) if tab == "Setup": # path validation if self.validate_path(self.entry_path) and self.validate_path(self.entry_path2) and ( self.college_options.get() or self.high_school_options.get()): if self.high_school_options.get(): for option in optionsHighSchool: if option.get(): selected_classes.append((option.cget("text"))) if self.college_options.get(): for option in optionsCollege: if option.get(): selected_classes.append((option.cget("text"))) if len(selected_classes) == 0: self.college_label_error() self.high_school_label_eroor() else: self.selected_classes = selected_classes self.tabview_generate_lists.set("Output Location") L = paths.fichier_to_Liste() L[0] = "DATA" + "=" + self.entry_path.get() + "\n" L[1] = "TEMPLATE" + "=" + self.entry_path2.get() + "\n" paths.Liste_to_Fichier(L) else: if not self.validate_path(self.entry_path): self.label_data_file_error() if not self.validate_path(self.entry_path2): self.label_template_file_error() if self.high_school_options.get(): for option in optionsHighSchool: if option.get(): selected_classes.append((option.cget("text"))) if self.college_options.get(): for option in optionsCollege: if option.get(): selected_classes.append((option.cget("text"))) if len(selected_classes) == 0: self.college_label_error() self.high_school_label_eroor() if tab == "Output Location": if self.validate_dir(self.output_path): self.tabview_generate_lists.set("Review & Submit") L = paths.fichier_to_Liste() L[-1] = "DIR" + "=" + self.output_path.get() paths.Liste_to_Fichier(L) self.label_all_review1 = customtkinter.CTkTextbox(self.tabview_generate_lists.tab("Review & Submit")) self.label_all_review1.grid(row=0, column=0, columnspan=6, sticky="nsew") # self.label_all_review2.insert("1.0", text) text = f"Data file path:" text += " " * (30 - len("Data file path:")) text += str(self.entry_path.get()) + "\n\n" self.label_all_review1.insert("end", text) text = "Template file path:" text += " " * (30 - len("Template file path:")) text += str(self.entry_path2.get()) + "\n\n" self.label_all_review1.insert("end", text) text = "Classes:" text += " " * (30 - len("Classes:")) for c in self.selected_classes: text = text + c + ",\t" self.label_all_review1.insert("end", text + "\n\n") text = "Output directory:" text += " " * (30 - len("Output directory:")) text += str(self.output_path.get()) + "\n\n" self.label_all_review1.insert("end", text) self.label_all_review1.configure(state="disabled", text_color="gray70") else: self.directory_error() return def browse_path(self): filetypes = ( ("Text files", "*.xls"), # Display only .txt files ("All files", "*.*") # Display all files ) path = filedialog.askopenfilename(filetypes=filetypes, initialdir=os.path.dirname(self.path["DATA"]) if self.path["DATA"] != "" else os.path.join(os.path.expanduser('~'), 'Documents')) if path == "": return self.entry_path.delete(0, tk.END) # Clear the entry self.entry_path.insert(0, os.path.abspath(path)) self.path["DATA"] = path file = C_File(file_name=path) if file.existe_fichier(): self.reset_error1() def browse_path2(self): filetypes = ( ("Text files", "*.xlsx"), # Display only .txt files ("All files", "*.*") # Display all files ) path = filedialog.askopenfilename(filetypes=filetypes, initialdir=os.path.dirname(self.path["TEMPLATE"]) if self.path["TEMPLATE"] != "" else os.path.join(os.path.expanduser('~'), 'Documents')) if path == "": return self.entry_path2.delete(0, tk.END) # Clear the entry self.entry_path2.insert(0, os.path.abspath(path)) self.path["TEMPLATE"] = path file = C_File(file_name=path) if file.existe_fichier(): self.reset_error2() def browser_path3(self): filetypes = ( ("Text files", "*.xlsx"), # Display only .txt files ("All files", "*.*") # Display all files ) path = filedialog.askopenfilename(filetypes=filetypes, initialdir=os.path.dirname(self.path["ABSENCE_FILE"]) if self.path["ABSENCE_FILE"] != "" else os.path.join(os.path.expanduser('~'), 'Documents')) if path == "": return self.path["ABSENCE_FILE"] = path self.entry_path_absence.delete(0, tk.END) # Clear the entry self.entry_path_absence.insert(0, os.path.abspath(path)) file = C_File(file_name=path) if file.existe_fichier(): self.reset_label(self.label_absence_data_file) self.entry_reset(self.entry_path_absence) def browse_folder(self): path = filedialog.askdirectory(initialdir=self.path["DIR"] if self.path["DIR"] != "" else os.path.join(os.path.expanduser('~'), 'Documents')) if path == "": return self.output_path.delete(0, tk.END) self.output_path.insert(0, os.path.abspath(path)) self.path["DIR"] = path dir = C_Dossier() if dir.existe_dossier(Chemin=path): self.reset_error3() return # Function to validate the path entry def validate_path(self, path): if path.get() == "": return False file = C_File(file_name=path.get()) return file.existe_fichier() def validate_dir(self, path): if path.get() == "": return False dir = C_Dossier() return dir.existe_dossier(Chemin=path.get()) def back(self): if self.tabview_generate_lists.grid_info(): tab = self.tabview_generate_lists else: tab = self.tabview_fill_bot if tab.get() == "Review & Submit": tab.set("Output Location") elif tab.get() == "Output Location": tab.set("Setup") return def back2(self): self.tabview_fill_bot.set("Setup") if self.tabview_fill_bot.grid_info() else self.tabview_generate_lists.set("Setup") return def select_frame_by_name(self, name): # set button color for selected button self.generate_list_menu.configure(fg_color=("gray75", "gray25") if name == "Generate Lists" else "transparent") self.fill_absence_menu.configure(fg_color=("gray75", "gray25") if name == "Fill Absence Bot" else "transparent") self.about_us_menu.configure(fg_color=("gray75", "gray25") if name == "About us" else "transparent") def generate_progress_bar(self, determinate=True): if self.progressbar_1 is None: self.progressbar_1 = customtkinter.CTkProgressBar(self.sidebar_frame, mode="determinate" if determinate == True else "indeterminate") state = True else: self.progressbar_1.configure(mode="determinate" if determinate == True else "indeterminate") state = False if determinate: self.progressbar_1.set(0) else: self.progressbar_1.start() if state: self.progressbar_1.grid(row=6, column=0, padx=20, pady=20, sticky="ew") else: self.progressbar_1.grid() def generate_list_menu_button_event(self): if self.try_again_generate != False: test = self.generate_list_menu.cget("fg_color") if test == ("gray75", "gray25"): self.tabview_generate_lists.set("Setup") return if self.try_again_generate == False: self.generate_list_menu = customtkinter.CTkButton(self.sidebar_frame, corner_radius=0, height=40, border_spacing=10, text="Generate Lists", fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"), anchor="w", command=self.generate_list_menu_button_event) self.generate_list_menu.grid(row=1, column=0, sticky="ew", pady=(20, 0)) self.fill_absence_menu = customtkinter.CTkButton(self.sidebar_frame, corner_radius=0, height=40, border_spacing=10, text="Fill Absence Bot", fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"), anchor="w", command=self.fill_absence_button_event ) self.fill_absence_menu.grid(row=2, column=0, sticky="ew") self.about_us_menu = customtkinter.CTkButton(self.sidebar_frame, corner_radius=0, height=40, border_spacing=10, text="About us", fg_color="transparent", text_color=("gray10", "gray90"), hover_color=("gray70", "gray30"), anchor="w", command=self.about_us_button_event ) self.about_us_menu.grid(row=3, column=0, sticky="ew") # end of side bar # generate lists page self.tabview_generate_lists = customtkinter.CTkTabview(self, width=250, state='disabled', text_color_disabled='white', height=250) self.tabview_generate_lists.grid(row=0, column=1, padx=(20, 20), pady=(5, 0), sticky="nsew") self.tabview_generate_lists.add("Setup") self.tabview_generate_lists.add("Output Location") self.tabview_generate_lists.add("Review & Submit") self.tabview_generate_lists.tab("Setup").grid_columnconfigure(0, weight=1) # setup tab self.tabview_generate_lists.tab("Setup").grid_rowconfigure(0, weight=1) self.tabview_generate_lists.tab("Setup").grid_columnconfigure(0, weight=1) # data entry # check if file exist paths = C_File(file_name=resource_path("db/paths.txt")) self.path={} if paths.existe_fichier(): self.paths = paths.fichier_to_Liste() for path in self.paths: path_splited = path.split("=") self.path[path_splited[0]]=path_splited[-1].strip() self.data_entry_frame = customtkinter.CTkFrame(self.tabview_generate_lists.tab("Setup")) self.data_entry_frame.grid(sticky='nw', row=0, column=0, padx=5, pady=(0, 0)) self.label_data_file = customtkinter.CTkLabel(self.data_entry_frame, text="Data File (.xls):", text_color="gray90") self.label_data_file.grid(row=0, column=0, padx=(0, 5), pady=(15, 0)) self.entry_path = customtkinter.CTkEntry(self.data_entry_frame, placeholder_text="C:\\", validate='focusout', validatecommand=((), '%P'), width=250) self.entry_path.grid(row=0, column=1, padx=(100, 5), pady=(15, 0)) self.browse_button = customtkinter.CTkButton(self.data_entry_frame, text="Browse", command=self.browse_path, width=50) self.browse_button.grid(row=0, column=2, padx=(0, 5), pady=(15, 0)) self.label_template_entry = customtkinter.CTkLabel(self.data_entry_frame, text="Template file (.xlsx):") self.label_template_entry.grid(row=1, column=0, padx=(0, 5), pady=(15, 0)) self.entry_path2 = customtkinter.CTkEntry(self.data_entry_frame, placeholder_text="C:\\", validate='focusout', width=250) self.entry_path2.grid(row=1, column=1, padx=(100, 5), pady=(15, 10)) self.browse_button2 = customtkinter.CTkButton(self.data_entry_frame, text="Browse", command=self.browse_path2, width=50) self.browse_button2.grid(row=1, column=2, padx=(0, 5), pady=(15, 10)) if self.path["DATA"] != "": self.entry_path.insert(0, self.path["DATA"]) if self.path["TEMPLATE"] != "": self.entry_path2.insert(0, self.path["TEMPLATE"]) self.class_type_options_frame = customtkinter.CTkFrame(self.tabview_generate_lists.tab("Setup"), fg_color="gray25", height=100) self.class_type_options_frame.grid(sticky="nsew", row=2, column=0, columnspan=6, padx=10, pady=(20, 20)) # self.error_label = customtkinter.CTkLabel(self.class_type_options_frame, text="You have to choose atlease one class", text_color="black") # self.error_label.grid(row=0, column=0, padx=(0,0)) self.label_college = customtkinter.CTkLabel(self.class_type_options_frame, text="College Classes") self.label_college.grid(row=0, column=0, padx=(0, 0)) self.college_options = customtkinter.CTkSwitch(self.class_type_options_frame, text="College", state="switched", command=self.college_switch) self.college_options.select() self.college_options.grid(row=1, column=0, padx=(0, 0)) self.college_inter = customtkinter.CTkCheckBox(self.class_type_options_frame, text="APIC", state="normal", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.college_inter.grid(row=2, column=0, padx=(20, 0), pady=(10, 0), sticky="n") self.college_generale = customtkinter.CTkCheckBox(self.class_type_options_frame, text="ASCG", state="normal", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.college_generale.grid(row=2, column=1, padx=(0, 0), pady=(10, 0), sticky="n") self.college_aspeb = customtkinter.CTkCheckBox(self.class_type_options_frame, text="ASCPEB", state="normal", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.college_aspeb.grid(row=3, column=0, padx=(20, 0), pady=(5, 5), sticky="n") self.label_high_school = customtkinter.CTkLabel(self.class_type_options_frame, text="High School Classes", anchor="e") self.label_high_school.grid(row=0, column=2, padx=(100, 0)) self.high_school_options = customtkinter.CTkSwitch(self.class_type_options_frame, text="High School", state="switched", command=self.high_school_switch) # self.high_school_options.select() self.high_school_options.grid(row=1, column=2, padx=(80, 0)) self.TCS = customtkinter.CTkCheckBox(self.class_type_options_frame, text="TCS", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.TCS.grid(row=2, column=2, padx=(100, 0), pady=(5, 0), sticky="nsew") self.TCSF = customtkinter.CTkCheckBox(self.class_type_options_frame, text="TCSF", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.TCSF.grid(row=2, column=3, padx=(0, 0), pady=(5, 0), sticky="nsew") self.TCLSH = customtkinter.CTkCheckBox(self.class_type_options_frame, text="TCLSH", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.TCLSH.grid(row=3, column=2, padx=(100, 0), pady=(5, 5), sticky="nsew") self.BACSE = customtkinter.CTkCheckBox(self.class_type_options_frame, text="1BACSE", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.BACSE.grid(row=3, column=3, padx=(0, 0), pady=(5, 5), sticky="nsew") self.BACSH = customtkinter.CTkCheckBox(self.class_type_options_frame, text="1BACSH", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.BACSH.grid(row=3, column=4, padx=(0, 0), pady=(5, 5), sticky="nsew") self.BACSC = customtkinter.CTkCheckBox(self.class_type_options_frame, text="2BACSC", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.BACSC.grid(row=3, column=5, padx=(0, 0), pady=(5, 5), sticky="nsew") self.BACSH2 = customtkinter.CTkCheckBox(self.class_type_options_frame, text="2BACSH", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.BACSH2.grid(row=2, column=4, padx=(0, 0), pady=(5, 0), sticky="nsew") self.BACSVT = customtkinter.CTkCheckBox(self.class_type_options_frame, text="2BACSVT", state="disabled", checkbox_width=20, checkbox_height=20, command=self.reset_label_high_college) self.BACSVT.grid(row=2, column=5, padx=(0, 0), pady=(5, 0), sticky="nsew") self.submit = customtkinter.CTkButton(self.tabview_generate_lists.tab("Setup"), text="Next", command=self.go_to_output_location, width=50) self.submit.grid(row=6, column=5, padx=10, pady=(5, 5)) self.return_btn = customtkinter.CTkButton(self.tabview_generate_lists.tab("Setup"), text="Exit", width=50, fg_color="gray30", command=self.exit) self.return_btn.grid(row=6, column=4, padx=10, pady=(5, 5)) # output location tab self.tabview_generate_lists.tab("Output Location").grid_rowconfigure(0, weight=1) self.tabview_generate_lists.tab("Output Location").grid_columnconfigure((0, 1, 2), weight=1) self.output_location_frame = customtkinter.CTkFrame(self.tabview_generate_lists.tab("Output Location"), height=200) self.output_location_frame.grid(sticky='nw', row=0, column=0, padx=5, pady=(20, 0)) self.label_output_folder = customtkinter.CTkLabel(self.output_location_frame, text="Output Folder") self.label_output_folder.grid(row=0, column=0, padx=(0, 5), pady=(15, 0)) self.output_path = customtkinter.CTkEntry(self.output_location_frame, placeholder_text=self.path["DIR"] if self.path["DIR"] != "" else os.path.join(os.path.expanduser('~'), 'Documents'), validate='focusout', width=250) self.output_path.insert("0", str(self.path["DIR"] if self.path["DIR"] != "" else os.path.join(os.path.expanduser('~'), 'Documents'))) self.output_path.grid(row=0, column=1, padx=(100, 5), pady=(15, 0)) self.browse_button3 = customtkinter.CTkButton(self.output_location_frame, text="Browse", command=self.browse_folder, width=50) self.browse_button3.grid(row=0, column=2, padx=(0, 5), pady=(15, 0)) self.submit2 = customtkinter.CTkButton(self.tabview_generate_lists.tab("Output Location"), text="Next", command=self.go_to_output_location, width=50) self.submit2.grid(row=3, column=5, padx=10, pady=(5, 5)) self.return_btn2 = customtkinter.CTkButton(self.tabview_generate_lists.tab("Output Location"), text="Back", command=self.back, width=50, fg_color="gray30") self.return_btn2.grid(row=3, column=4, padx=10, pady=(5, 5)) # review tab self.tabview_generate_lists.tab("Review & Submit").grid_rowconfigure(0, weight=1) self.tabview_generate_lists.tab("Review & Submit").grid_columnconfigure((0, 1, 2), weight=1) self.submit3 = customtkinter.CTkButton(self.tabview_generate_lists.tab("Review & Submit"), text="Submit", command=self.generate_absence_file, width=60) self.submit3.grid(row=4, column=5, padx=10, pady=(5, 5)) self.return_btn3 = customtkinter.CTkButton(self.tabview_generate_lists.tab("Review & Submit"), text="Back", command=self.back, width=50, fg_color="gray30") self.return_btn3.grid(row=4, column=4, padx=10, pady=(5, 5)) self.select_frame_by_name("Generate Lists") self.try_again_generate = True else: self.tabview_fill_bot.grid_remove() self.tabview_generate_lists.grid() if not self.console_text.grid_info(): self.console_text.grid() if self.about_us_text is not None: self.about_us_text.grid_remove() self.about_us_logo.grid_remove() self.select_frame_by_name("Generate Lists") def entry_error(self, entry): entry.configure(border_color="red") def entry_reset(self, entry): entry.configure(border_color=self.entry_default_bordercolor) def error_label(self, label): current_text = label.cget("text") label.configure(text=current_text.replace("*", "") + "*", text_color="red") return def reset_label(self, label): current_text = label.cget("text") label.configure(text=current_text.replace("*", ""), text_color="gray90") return def validate_email_entry(self): email = self.email_entry.get() is_valid = validate_email(email) if is_valid: self.reset_label(self.label_email_entry) self.entry_reset(self.email_entry) else: self.error_label(self.label_email_entry) self.entry_error(self.email_entry) def check_terms_box(self): if self.check_terms_and_condition.get(): self.check_terms_and_condition.configure(border_color="gray72", text_color="gray72") self.reset_label(self.label_terms) else: self.check_terms_and_condition.configure(border_color="red", text_color="red") self.error_label(self.label_terms) def fill_absence_button_event(self): test = self.fill_absence_menu.cget("fg_color") if test == ("gray75", "gray25"): self.tabview_fill_bot.set("Setup") return if self.try_again_fill == False: self.tabview_fill_bot = customtkinter.CTkTabview(self, width=250, state='disabled', text_color_disabled='white', height=250) self.tabview_fill_bot.grid(row=0, column=1, padx=(20, 20), pady=(5, 0), sticky="nsew") self.tabview_fill_bot.add("Setup") self.tabview_fill_bot.add("Review & Submit") # setup tab self.tabview_fill_bot.tab("Setup").grid_rowconfigure(0, weight=1) self.tabview_fill_bot.tab("Setup").grid_columnconfigure(0, weight=1) self.tabview_fill_bot.tab("Review & Submit").grid_rowconfigure(0, weight=1) self.tabview_fill_bot.tab("Review & Submit").grid_columnconfigure((0, 1, 2), weight=1) # self.generate_list_menu_button_event() self.tabview_fill_bot.set("Setup") # self.submit.destroy() # self.return_btn.destroy() self.data_entry_frame = customtkinter.CTkFrame(self.tabview_fill_bot.tab("Setup")) self.data_entry_frame.grid(sticky='nw', row=0, column=0, padx=5, pady=(0, 0)) self.label_email_entry = customtkinter.CTkLabel(self.data_entry_frame, text="Email:", text_color="gray90") self.label_email_entry.grid(row=0, column=0, padx=(0, 5), pady=(15, 0)) self.email_entry = customtkinter.CTkEntry(self.data_entry_frame, placeholder_text="email@taalim.ma", width=250) self.email_entry.grid(row=0, column=1, padx=(100, 5), pady=(15, 0)) if self.path["EMAIL"] != "": self.email_entry.insert(0, self.path["EMAIL"]) self.email_entry.bind("<KeyRelease>", lambda _ : self.validate_email_entry()) self.label_password_entry = customtkinter.CTkLabel(self.data_entry_frame, text="Password:") self.label_password_entry.grid(row=1, column=0, padx=(0, 5), pady=(15, 0)) self.password_entry = customtkinter.CTkEntry(self.data_entry_frame, show="*" ,placeholder_text="Your Password", width=250) self.password_entry.grid(row=1, column=1, padx=(100, 5), pady=(15, 0)) self.password_entry.bind("<KeyRelease>", lambda _ : (self.reset_label(self.label_password_entry), self.entry_reset(self.password_entry)) if len(self.password_entry.get()) > 8 else (self.error_label(self.label_password_entry), self.entry_error(self.password_entry))) self.label_absence_data_file = customtkinter.CTkLabel(self.data_entry_frame, text="Absence File (.xlsx):", text_color="gray90") self.label_absence_data_file.grid(row=2, column=0, padx=(0, 5), pady=(15, 0)) self.entry_path_absence = customtkinter.CTkEntry(self.data_entry_frame, placeholder_text=self.path["ABSENCE_FILE"] if self.path["ABSENCE_FILE"] != "" else "C://", validate='focusout', validatecommand=((), '%P'), width=250) self.entry_path_absence.grid(row=2, column=1, padx=(100, 5), pady=(15, 0)) if self.path["ABSENCE_FILE"] != "": self.entry_path_absence.insert(0, self.path["ABSENCE_FILE"]) self.browse_button_absence = customtkinter.CTkButton(self.data_entry_frame, text="Browse", command=self.browser_path3, width=50) self.browse_button_absence.grid(row=2, column=2, padx=(0, 5), pady=(15,0)) self.label_browser_chrome_firefox = customtkinter.CTkLabel(self.data_entry_frame, text="Browser:", text_color="gray90") self.label_browser_chrome_firefox.grid(row=3, column=0, padx=(0, 5), pady=(15, 0)) self.browser_type = customtkinter.IntVar() self.chrome_radio = customtkinter.CTkRadioButton(self.data_entry_frame, text="Chrome", variable=self.browser_type, value=1, state="disabled") self.chrome_radio.grid(row=3, column=1, padx=(10, 5), pady=(15, 0)) self.firefox_radio = customtkinter.CTkRadioButton(self.data_entry_frame, text="Firefox", variable=self.browser_type, value=2) self.firefox_radio.grid(row=3, column=2, padx=(10, 5), pady=(15,0)) self.firefox_radio.select() self.label_terms = customtkinter.CTkLabel(self.data_entry_frame, text="Terms and conditions:", text_color="gray90") self.label_terms.grid(row=4, column=0, padx=(0, 5), pady=(20, 0)) self.check_terms_and_condition = customtkinter.CTkCheckBox(self.data_entry_frame, text="I accept the Terms and the Conditions", state="normal",checkbox_width=20, checkbox_height=20, command=self.check_terms_box) self.check_terms_and_condition.grid(row=4, column=1, padx=(0, 0), pady=(20,0), sticky="ne") self.submit4 = customtkinter.CTkButton(self.tabview_fill_bot.tab("Setup"), text="Next", command=self.go_to_review2, width=50) self.submit4.grid(row=6, column=5, padx=10, pady=(5, 5)) self.return_btn4 = customtkinter.CTkButton(self.tabview_fill_bot.tab("Setup"), text="Exit", width=50, fg_color="gray30", command=self.exit) self.return_btn4.grid(row=6, column=4, padx=10, pady=(5, 5)) self.run_bot = customtkinter.CTkButton(self.tabview_fill_bot.tab("Review & Submit"), text="Run", command=self.run_bot_interaction, width=50) self.run_bot.grid(row=6, column=5, padx=10, pady=(5, 5)) self.return_btn5 = customtkinter.CTkButton(self.tabview_fill_bot.tab("Review & Submit"), text="Back", command=self.back2, width=50, fg_color="gray30") self.return_btn5.grid(row=6, column=4, padx=10, pady=(5, 5)) if self.about_us_text is not None: self.about_us_text.grid_remove() self.about_us_logo.grid_remove() self.console_text.grid() self.try_again_fill = True self.select_frame_by_name("Fill Absence Bot") else: self.tabview_generate_lists.grid_remove() self.tabview_fill_bot.grid() self.console_text.grid() if self.about_us_text is not None: self.about_us_text.grid_remove() self.about_us_logo.grid_remove() self.select_frame_by_name("Fill Absence Bot") def about_us_button_event(self): if self.tabview_generate_lists.grid_info(): self.tabview_generate_lists.grid_remove() if self.tabview_fill_bot is not None: if self.tabview_fill_bot.grid_info(): self.tabview_fill_bot.grid_remove() if self.about_us_text is not None: self.about_us_text.grid() self.about_us_logo.grid() self.console_text.grid_remove() self.select_frame_by_name("About us") else: self.about_us_logo = customtkinter.CTkLabel(self, text="", image=self.about_us_image) self.about_us_logo.grid(row=0, column=1, padx=10, pady=10) self.about_us_text = customtkinter.CTkTextbox(self, height=200, wrap="word", font=("Arial", 18)) self.about_us_text.grid(row=1, column=1,rowspan=3, columnspan=6, padx=(20, 20), pady = (15, 20), sticky = "nsew") self.console_text.grid_remove() self.about_us_text.tag_config("Title", foreground="gray92") self.about_us_text.tag_config("subTitle", foreground="gray65") self.about_us_text.tag_config("Paragraph", foreground="gray50") # Content to be displayed # Insert the formatted text into the Text widget self.about_us_text.insert("end", "\n About Us", "LargeText") self.about_us_text.insert("end", "\n\nMassar Direction Sagoubot is a cutting-edge automation project designed to streamline and simplify the process of managing absence data for multiple classes within a web application. Our solution is meticulously crafted using modern technologies and software tools to optimize efficiency and save valuable time for teachers and administrators.\n", "Paragraph") self.about_us_text.insert("end", "\n\n Terms and Privacy", "Title") self.about_us_text.insert("end", "\n\nAccount Access", "subTitle") self.about_us_text.insert("end", "\nTo enhance your experience with Massar Direction Sagoubot, the application utilizes your account credentials to securely log in to the Massar website. Your privacy and security are of utmost importance to us. We ensure that your login information is encrypted and used solely for the purpose of automating absence data management.\n", "Paragraph") self.about_us_text.insert("end", "\n\nData Handling", "subTitle") self.about_us_text.insert("end", "\nYour data, specifically related to absence records and class information, is processed within the confines of the application to facilitate automation. We do not store or retain any of your personal data beyond the scope of improving application functionality.\n", "Paragraph") self.about_us_text.insert("end", "\n\nSecurity Measures", "subTitle") self.about_us_text.insert("end", "\nWe employ industry-standard security measures to safeguard your account information. This includes encryption protocols and best practices to prevent unauthorized access or misuse of your credentials.\n", "Paragraph") self.about_us_text.insert("end", "\n\nUser Consent", "subTitle") self.about_us_text.insert("end", "\nBy using Massar Direction Sagoubot, you consent to the utilization of your Massar account credentials for the sole purpose of automating absence data management. We prioritize transparency and security in handling your login information.\n", "Paragraph") self.about_us_text.insert("end", "\n\nQuestions or Concerns", "subTitle") self.about_us_text.insert("end", "\nIf you have any questions, concerns, or require further clarification regarding our terms, privacy practices, or the usage of your account information, please feel free to reach out to us at sakou81833@gmail.com. Your satisfaction and trust are our top priorities.\n", "Paragraph") self.about_us_text.configure(state="disabled") self.select_frame_by_name("About us") def exit(self): result = tk.messagebox.askokcancel("Confirmation", "Are you sure you want to exit?") if result: # If the user confirms app.quit() # backend functions def generate_absence_file(self): self.generate_progress_bar() self.submit3.configure(state="disabled") self.return_btn3.configure(state="disabled") self.console_text.configure(state="normal") self.label_all_review1.configure(text_color="gray35") def run_fill_all_class_sheets(): reader = Read_Db(input_file=self.entry_path.get(), template_file=self.entry_path2.get(), output_file=str(self.output_path.get()) + "\\absence.xlsx", required_classes=self.selected_classes, progress_bar=self.progressbar_1, console=self.console_text) reader.fill_all_class_sheets() time.sleep(3) self.submit3.configure(state="normal") self.return_btn3.configure(state="normal") self.progressbar_1.grid_remove() self.console_text.configure(state="disabled") self.label_all_review1.configure(text_color="gray70") thread = threading.Thread(target=run_fill_all_class_sheets) thread.start() return def run_bot_interaction(self): self.generate_progress_bar(determinate=False) self.console_text.configure(state="normal") self.run_bot.configure(state="disabled") self.return_btn5.configure(state="disabled") self.label_all_review2.configure(text_color="gray35") def run_fill_absence(): # loading the class here because of the .env file not getting refreshed interaction_object = Massar_Direction_Sagou(console=self.console_text) driver_test = interaction_object.main_interaction() if driver_test: interaction_object.get_list_page()
absence = Absence(driver=interaction_object.driver, console=self.console_text)
3
2023-10-29 18:10:27+00:00
16k
hsma-programme/Teaching_DES_Concepts_Streamlit
pages/4_🏥_The_Full_Model.py
[ { "identifier": "add_logo", "path": "helper_functions.py", "snippet": "def add_logo():\n '''\n Add a logo at the top of the page navigation sidebar\n\n Approach written by blackary on\n https://discuss.streamlit.io/t/put-logo-and-title-above-on-top-of-page-navigation-in-sidebar-of-multipage-...
import gc import asyncio import pandas as pd import plotly.express as px import plotly.graph_objects as go import streamlit as st import numpy as np from helper_functions import add_logo, mermaid, center_running from model_classes import Scenario, multiple_replications from output_animation_functions import reshape_for_animations, animate_activity_log
11,011
st.subheader("Non-Trauma Treatment") n_cubicles_1 = st.slider("👨‍⚕️👩‍⚕️ Number of Treatment Cubicles for Non-Trauma", 1, 10, step=1, value=2) non_trauma_treat_p = st.slider("🤕 Probability that a non-trauma patient will need treatment", 0.0, 1.0, step=0.01, value=0.7, help="0 = No non-trauma patients need treatment\n\n1 = All non-trauma patients need treatment") col5, col6 = st.columns(2) with col5: st.write("Total rooms in use is {}".format(n_cubicles_1+n_cubicles_2+n_exam+n_trauma+n_triage+n_reg)) with col6: with st.expander("Advanced Parameters"): seed = st.slider("🎲 Set a random number for the computer to start from", 1, 1000, step=1, value=42) n_reps = st.slider("🔁 How many times should the simulation run? WARNING: Fast/modern computer required to take this above 5 replications.", 1, 10, step=1, value=3) run_time_days = st.slider("🗓️ How many days should we run the simulation for each time?", 1, 60, step=1, value=5) args = Scenario( random_number_set=seed, n_triage=n_triage, n_reg=n_reg, n_exam=n_exam, n_trauma=n_trauma, n_cubicles_1=n_cubicles_1, n_cubicles_2=n_cubicles_2, non_trauma_treat_p=non_trauma_treat_p, prob_trauma=prob_trauma) # A user must press a streamlit button to run the model button_run_pressed = st.button("Run simulation") if button_run_pressed: # add a spinner and then display success box with st.spinner('Simulating the minor injuries unit...'): await asyncio.sleep(0.1) my_bar = st.progress(0, text="Simulating the minor injuries unit...") # run multiple replications of experment detailed_outputs = multiple_replications( args, n_reps=n_reps, rc_period=run_time_days*60*24, return_detailed_logs=True ) my_bar.progress(40, text="Collating Simulation Outputs...") results = pd.concat([detailed_outputs[i]['results']['summary_df'].assign(rep= i+1) for i in range(n_reps)]).set_index('rep') full_event_log = pd.concat([detailed_outputs[i]['results']['full_event_log'].assign(rep= i+1) for i in range(n_reps)]) del detailed_outputs gc.collect() my_bar.progress(60, text="Logging Results...") # print(len(st.session_state['session_results'])) # results_for_state = pd.DataFrame(results.median()).T.drop(['Rep'], axis=1) results_for_state = results original_cols = results_for_state.columns.values results_for_state['Triage\nCubicles'] = args.n_triage results_for_state['Registration\nClerks'] = args.n_reg results_for_state['Examination\nRooms'] = args.n_exam results_for_state['Non-Trauma\nTreatment Cubicles'] = args.n_cubicles_1 results_for_state['Trauma\nStabilisation Bays'] = args.n_trauma results_for_state['Trauma\nTreatment Cubicles'] = args.n_cubicles_2 results_for_state['Probability patient\nis a trauma patient'] = args.prob_trauma results_for_state['Probability non-trauma patients\nrequire treatment'] = args.non_trauma_treat_p results_for_state['Model Run'] = len(st.session_state['session_results']) + 1 results_for_state['Random Seed'] = seed # Reorder columns column_order = ['Model Run', 'Triage\nCubicles', 'Registration\nClerks', 'Examination\nRooms', 'Non-Trauma\nTreatment Cubicles', 'Trauma\nStabilisation Bays', 'Trauma\nTreatment Cubicles', 'Probability patient\nis a trauma patient', 'Probability non-trauma patients\nrequire treatment', 'Random Seed' ] + list(original_cols) results_for_state = results_for_state[column_order] current_state = st.session_state['session_results'] current_state.append(results_for_state) del results_for_state gc.collect() st.session_state['session_results'] = current_state del current_state gc.collect() # print(len(st.session_state['session_results'])) # UTILISATION AUDIT - BRING BACK WHEN NEEDED # full_utilisation_audit = pd.concat([detailed_outputs[i]['results']['utilisation_audit'].assign(Rep= i+1) # for i in range(n_reps)]) # animation_dfs_queue = reshape_for_animations( # full_event_log[ # (full_event_log['rep']==1) & # ((full_event_log['event_type']=='queue') | (full_event_log['event_type']=='arrival_departure')) # ] # ) my_bar.progress(80, text="Creating Animations...")
''' A Streamlit application based on Monks and Allows users to interact with an increasingly more complex treatment simulation ''' st.set_page_config( page_title="The Full Model", layout="wide", initial_sidebar_state="expanded", ) # Initialise session state if 'session_results' not in st.session_state: st.session_state['session_results'] = [] add_logo() center_running() with open("style.css") as css: st.markdown( f'<style>{css.read()}</style>' , unsafe_allow_html= True) ## We add in a title for our web app's page st.title("Discrete Event Simulation Playground") st.subheader("How can we optimise the full system?") st.markdown("Once you have run more than one scenario, try out the new tab 'compare scenario outputs'.") gc.collect() # tab1, tab2, tab3, tab4 = st.tabs(["Introduction", "Exercises", "Playground", "Compare Scenario Outputs"]) tab1, tab2, tab3, tab4 = st.tabs(["Playground", "Exercise", "Compare Scenario Outputs", "Information"]) with tab4: st.markdown(""" So now we have explored every component of the model: - Generating arrivals - Generating and using resources - Sending people down different paths So now let's create a version of the model that uses all of these aspects. For now, we won't consider nurses separately - we will assume that each nurse on shift has one room that is theirs to always use. """ ) mermaid(height=600, code= """ %%{ init: { 'flowchart': { 'curve': 'step' } } }%% %%{ init: { 'theme': 'base', 'themeVariables': {'lineColor': '#b4b4b4'} } }%% flowchart LR A[Arrival] --> BX[Triage] BX -.-> T([Triage Bay\n<b>RESOURCE</b>]) T -.-> BX BX --> BY{Trauma or non-trauma} BY ----> B1{Trauma Pathway} BY ----> B2{Non-Trauma Pathway} B1 --> C[Stabilisation] C --> E[Treatment] B2 --> D[Registration] D --> G[Examination] G --> H[Treat?] H ----> F H --> I[Non-Trauma Treatment] I --> F C -.-> Z([Trauma Room\n<b>RESOURCE</b>]) Z -.-> C E -.-> Y([Cubicle - 1\n<b>RESOURCE</b>]) Y -.-> E D -.-> X([Clerks\n<b>RESOURCE</b>]) X -.-> D G -.-> W([Exam Room\n<b>RESOURCE</b>]) W -.-> G I -.-> V([Cubicle - 2\n<b>RESOURCE</b>]) V -.-> I E ----> F[Discharge] classDef ZZ1 fill:#8B5E0F,font-family:lexend, color:#FFF classDef ZZ2 fill:#5DFDA0,font-family:lexend classDef ZZ2a fill:#02CD55,font-family:lexend, color:#FFF classDef ZZ3 fill: #D45E5E,font-family:lexend classDef ZZ3a fill: #932727,font-family:lexend, color:#FFF classDef ZZ4 fill: #611D67,font-family:lexend, color:#FFF classDef ZZ5 fill:#47D7FF,font-family:lexend classDef ZZ5a fill:#00AADA,font-family:lexend class A ZZ1 class C,E ZZ2 class D,G ZZ3 class X,W ZZ3a class Z,Y ZZ2a class I,V ZZ4 class BX ZZ5 class T ZZ5a ; """ ) with tab2: st.header("Things to Try") st.markdown( """ - First, just run the model with the default settings. - Look at the graphs and animated patient log. What is the performance of the system like? - Are the queues consistent throughout the day? --- - Due to building work taking place, the hospital will temporarily need to close several bays. It will be possible to have a maximum of 20 bays/cubicles/rooms in total across the whole system. - What is the best configuration you can find to keep the average wait times as low as possible across both trauma and non-trauma pathways? *Make sure you are using the default probabilities for trauma/non-trauma patients (0.3) and treatment of non-trauma patients (0.7)* """ ) with tab1: # n_triage: int # The number of triage cubicles # n_reg: int # The number of registration clerks # n_exam: int # The number of examination rooms # n_trauma: int # The number of trauma bays for stablisation # n_cubicles_1: int # The number of non-trauma treatment cubicles # n_cubicles_2: int # The number of trauma treatment cubicles # non_trauma_treat_p: float # Probability non trauma patient requires treatment # prob_trauma: float # probability that a new arrival is a trauma patient. col1, col2, col3, col4 = st.columns(4) with col1: st.subheader("Triage") n_triage = st.slider("👨‍⚕️👩‍⚕️ Number of Triage Cubicles", 1, 10, step=1, value=4) prob_trauma = st.slider("🚑 Probability that a new arrival is a trauma patient", 0.0, 1.0, step=0.01, value=0.3, help="0 = No arrivals are trauma patients\n\n1 = All arrivals are trauma patients") with col2: st.subheader("Trauma Pathway") n_trauma = st.slider("👨‍⚕️👩‍⚕️ Number of Trauma Bays for Stabilisation", 1, 10, step=1, value=6) n_cubicles_2 = st.slider("👨‍⚕️👩‍⚕️ Number of Treatment Cubicles for Trauma", 1, 10, step=1, value=6) with col3: st.subheader("Non-Trauma Pathway") n_reg = st.slider("👨‍⚕️👩‍⚕️ Number of Registration Cubicles", 1, 10, step=1, value=3) n_exam = st.slider("👨‍⚕️👩‍⚕️ Number of Examination Rooms for non-trauma patients", 1, 10, step=1, value=3) with col4: st.subheader("Non-Trauma Treatment") n_cubicles_1 = st.slider("👨‍⚕️👩‍⚕️ Number of Treatment Cubicles for Non-Trauma", 1, 10, step=1, value=2) non_trauma_treat_p = st.slider("🤕 Probability that a non-trauma patient will need treatment", 0.0, 1.0, step=0.01, value=0.7, help="0 = No non-trauma patients need treatment\n\n1 = All non-trauma patients need treatment") col5, col6 = st.columns(2) with col5: st.write("Total rooms in use is {}".format(n_cubicles_1+n_cubicles_2+n_exam+n_trauma+n_triage+n_reg)) with col6: with st.expander("Advanced Parameters"): seed = st.slider("🎲 Set a random number for the computer to start from", 1, 1000, step=1, value=42) n_reps = st.slider("🔁 How many times should the simulation run? WARNING: Fast/modern computer required to take this above 5 replications.", 1, 10, step=1, value=3) run_time_days = st.slider("🗓️ How many days should we run the simulation for each time?", 1, 60, step=1, value=5) args = Scenario( random_number_set=seed, n_triage=n_triage, n_reg=n_reg, n_exam=n_exam, n_trauma=n_trauma, n_cubicles_1=n_cubicles_1, n_cubicles_2=n_cubicles_2, non_trauma_treat_p=non_trauma_treat_p, prob_trauma=prob_trauma) # A user must press a streamlit button to run the model button_run_pressed = st.button("Run simulation") if button_run_pressed: # add a spinner and then display success box with st.spinner('Simulating the minor injuries unit...'): await asyncio.sleep(0.1) my_bar = st.progress(0, text="Simulating the minor injuries unit...") # run multiple replications of experment detailed_outputs = multiple_replications( args, n_reps=n_reps, rc_period=run_time_days*60*24, return_detailed_logs=True ) my_bar.progress(40, text="Collating Simulation Outputs...") results = pd.concat([detailed_outputs[i]['results']['summary_df'].assign(rep= i+1) for i in range(n_reps)]).set_index('rep') full_event_log = pd.concat([detailed_outputs[i]['results']['full_event_log'].assign(rep= i+1) for i in range(n_reps)]) del detailed_outputs gc.collect() my_bar.progress(60, text="Logging Results...") # print(len(st.session_state['session_results'])) # results_for_state = pd.DataFrame(results.median()).T.drop(['Rep'], axis=1) results_for_state = results original_cols = results_for_state.columns.values results_for_state['Triage\nCubicles'] = args.n_triage results_for_state['Registration\nClerks'] = args.n_reg results_for_state['Examination\nRooms'] = args.n_exam results_for_state['Non-Trauma\nTreatment Cubicles'] = args.n_cubicles_1 results_for_state['Trauma\nStabilisation Bays'] = args.n_trauma results_for_state['Trauma\nTreatment Cubicles'] = args.n_cubicles_2 results_for_state['Probability patient\nis a trauma patient'] = args.prob_trauma results_for_state['Probability non-trauma patients\nrequire treatment'] = args.non_trauma_treat_p results_for_state['Model Run'] = len(st.session_state['session_results']) + 1 results_for_state['Random Seed'] = seed # Reorder columns column_order = ['Model Run', 'Triage\nCubicles', 'Registration\nClerks', 'Examination\nRooms', 'Non-Trauma\nTreatment Cubicles', 'Trauma\nStabilisation Bays', 'Trauma\nTreatment Cubicles', 'Probability patient\nis a trauma patient', 'Probability non-trauma patients\nrequire treatment', 'Random Seed' ] + list(original_cols) results_for_state = results_for_state[column_order] current_state = st.session_state['session_results'] current_state.append(results_for_state) del results_for_state gc.collect() st.session_state['session_results'] = current_state del current_state gc.collect() # print(len(st.session_state['session_results'])) # UTILISATION AUDIT - BRING BACK WHEN NEEDED # full_utilisation_audit = pd.concat([detailed_outputs[i]['results']['utilisation_audit'].assign(Rep= i+1) # for i in range(n_reps)]) # animation_dfs_queue = reshape_for_animations( # full_event_log[ # (full_event_log['rep']==1) & # ((full_event_log['event_type']=='queue') | (full_event_log['event_type']=='arrival_departure')) # ] # ) my_bar.progress(80, text="Creating Animations...")
animation_dfs_log = reshape_for_animations(
5
2023-10-26 09:57:52+00:00
16k
hyperspy/exspy
exspy/models/edsmodel.py
[ { "identifier": "_get_element_and_line", "path": "exspy/misc/eds/utils.py", "snippet": "def _get_element_and_line(xray_line):\n \"\"\"\n Returns the element name and line character for a particular X-ray line as\n a tuple.\n\n By example, if xray_line = 'Mn_Ka' this function returns ('Mn', '...
import warnings import numpy as np import math import logging import hyperspy.components1d as create_component from hyperspy.misc.utils import stash_active_state from exspy.misc.eds.utils import _get_element_and_line from hyperspy.models.model1d import Model1D from exspy.signals.eds import EDSSpectrum from exspy.misc.elements import elements as elements_db from exspy.misc.eds import utils as utils_eds from hyperspy import utils
12,074
# -*- coding: utf-8 -*- # Copyright 2007-2023 The exSpy developers # # This file is part of exSpy. # # exSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # exSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with exSpy. If not, see <https://www.gnu.org/licenses/#GPL>. from __future__ import division _logger = logging.getLogger(__name__) eV2keV = 1000.0 sigma2fwhm = 2 * math.sqrt(2 * math.log(2)) def _get_weight(element, line, weight_line=None): if weight_line is None:
# -*- coding: utf-8 -*- # Copyright 2007-2023 The exSpy developers # # This file is part of exSpy. # # exSpy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # exSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with exSpy. If not, see <https://www.gnu.org/licenses/#GPL>. from __future__ import division _logger = logging.getLogger(__name__) eV2keV = 1000.0 sigma2fwhm = 2 * math.sqrt(2 * math.log(2)) def _get_weight(element, line, weight_line=None): if weight_line is None:
weight_line = elements_db[element]["Atomic_properties"]["Xray_lines"][line][
1
2023-10-28 20:04:10+00:00
16k
Sllambias/yucca
yucca/training/augmentation/YuccaAugmentationComposer.py
[ { "identifier": "get_max_rotated_size", "path": "yucca/image_processing/matrix_ops.py", "snippet": "def get_max_rotated_size(patch_size):\n if len(patch_size) == 2:\n max_dim = int(np.sqrt(patch_size[0] ** 2 + patch_size[1] ** 2))\n return (max_dim, max_dim)\n\n max_dim_0 = max(\n ...
from torchvision import transforms from yucca.image_processing.matrix_ops import get_max_rotated_size from yucca.image_processing.transforms.formatting import ( AddBatchDimension, RemoveBatchDimension, ) from yucca.image_processing.transforms.BiasField import BiasField from yucca.image_processing.transforms.Blur import Blur from yucca.image_processing.transforms.CopyImageToSeg import CopyImageToSeg from yucca.image_processing.transforms.Gamma import Gamma from yucca.image_processing.transforms.Ghosting import MotionGhosting from yucca.image_processing.transforms.Masking import Masking from yucca.image_processing.transforms.Mirror import Mirror from yucca.image_processing.transforms.Noise import ( AdditiveNoise, MultiplicativeNoise, ) from yucca.image_processing.transforms.Ringing import GibbsRinging from yucca.image_processing.transforms.sampling import DownsampleSegForDS from yucca.image_processing.transforms.SimulateLowres import SimulateLowres from yucca.image_processing.transforms.Spatial import Spatial from yucca.network_architectures.utils.model_memory_estimation import ( find_optimal_tensor_dims, )
13,389
self.gamma_range = (0.5, 2.0) self.gibbs_ringing_p_per_sample = 0.2 self.gibbs_ringing_cutfreq = (96, 129) self.gibbs_ringing_axes = (0, 2) if is_2d else (0, 3) self.mirror_p_per_sample = 0.0 self.mirror_p_per_axis = 0.33 self.mirror_axes = (0, 1) if is_2d else (0, 1, 2) self.motion_ghosting_p_per_sample = 0.2 self.motion_ghosting_alpha = (0.85, 0.95) self.motion_ghosting_numreps = (2, 11) self.motion_ghosting_axes = (0, 2) if is_2d else (0, 3) self.multiplicative_noise_p_per_sample = 0.2 self.multiplicative_noise_mean = (0, 0) self.multiplicative_noise_sigma = (1e-3, 1e-4) self.rotation_p_per_sample = 0.2 self.rotation_p_per_axis = 0.66 self.rotation_x = (-30.0, 30.0) self.rotation_y = (-0.0, 0.0) if is_2d else (-30.0, 30.0) self.rotation_z = (-0.0, 0.0) if is_2d else (-30.0, 30.0) self.scale_p_per_sample = 0.2 self.scale_factor = (0.9, 1.1) self.simulate_lowres_p_per_sample = 0.2 self.simulate_lowres_p_per_channel = 0.5 self.simulate_lowres_p_per_axis = 0.33 self.simulate_lowres_zoom_range = (0.5, 1.0) @property def pre_aug_patch_size(self): # First check if any spatial transforms are included if self.elastic_deform_p_per_sample > 0 or self.rotation_p_per_sample > 0 or self.scale_p_per_sample > 0: self._pre_aug_patch_size = get_max_rotated_size(self.patch_size) return self._pre_aug_patch_size def apply_task_type_specific_preset(self, task_type_preset): if task_type_preset == "classification": self.skip_label = True if task_type_preset == "unsupervised": self.skip_label = True self.copy_image_to_label = True # This should be uncommented when masking is properly implemented # augmentation_parameter_dict["mask_image_for_reconstruction"] = True def overwrite_params(self, parameter_dict): for key, value in parameter_dict.items(): setattr(self, key, value) def compose_train_transforms(self): tr_transforms = transforms.Compose( [ AddBatchDimension(), Spatial( patch_size=self.patch_size, crop=True, random_crop=self.random_crop, p_deform_per_sample=self.elastic_deform_p_per_sample, deform_sigma=self.elastic_deform_sigma, deform_alpha=self.elastic_deform_alpha, p_rot_per_sample=self.rotation_p_per_sample, p_rot_per_axis=self.rotation_p_per_axis, x_rot_in_degrees=self.rotation_x, y_rot_in_degrees=self.rotation_y, z_rot_in_degrees=self.rotation_z, p_scale_per_sample=self.scale_p_per_sample, scale_factor=self.scale_factor, skip_label=self.skip_label, ), AdditiveNoise( p_per_sample=self.additive_noise_p_per_sample, mean=self.additive_noise_mean, sigma=self.additive_noise_sigma, ), Blur( p_per_sample=self.blurring_p_per_sample, p_per_channel=self.blurring_p_per_channel, sigma=self.blurring_sigma, ), MultiplicativeNoise( p_per_sample=self.multiplicative_noise_p_per_sample, mean=self.multiplicative_noise_mean, sigma=self.multiplicative_noise_sigma, ), MotionGhosting( p_per_sample=self.motion_ghosting_p_per_sample, alpha=self.motion_ghosting_alpha, numReps=self.motion_ghosting_numreps, axes=self.motion_ghosting_axes, ), GibbsRinging( p_per_sample=self.gibbs_ringing_p_per_sample, cutFreq=self.gibbs_ringing_cutfreq, axes=self.gibbs_ringing_axes, ), SimulateLowres( p_per_sample=self.simulate_lowres_p_per_sample, p_per_channel=self.simulate_lowres_p_per_channel, p_per_axis=self.simulate_lowres_p_per_axis, zoom_range=self.simulate_lowres_zoom_range, ), BiasField(p_per_sample=self.biasfield_p_per_sample), Gamma( p_per_sample=self.gamma_p_per_sample, p_invert_image=self.gamma_p_invert_image, gamma_range=self.gamma_range, ), Mirror( p_per_sample=self.mirror_p_per_sample, axes=self.mirror_axes, p_mirror_per_axis=self.mirror_p_per_axis, skip_label=self.skip_label, ), DownsampleSegForDS(deep_supervision=self.deep_supervision), CopyImageToSeg(copy=self.copy_image_to_label),
class YuccaAugmentationComposer: def __init__( self, patch_size: list | tuple, deep_supervision: bool = False, is_2D: bool = False, parameter_dict: dict = {}, task_type_preset: str = None, ): self._pre_aug_patch_size = None self.deep_supervision = deep_supervision self.setup_default_params(is_2D, patch_size) self.apply_task_type_specific_preset(task_type_preset) self.overwrite_params(parameter_dict) self.train_transforms = self.compose_train_transforms() self.val_transforms = self.compose_val_transforms() def setup_default_params(self, is_2d, patch_size): print("Composing Transforms") # Define whether we crop before or after applying augmentations # Define if cropping is random or always centered self.random_crop = True self.mask_image_for_reconstruction = False self.patch_size = patch_size # label/segmentation transforms self.skip_label = False self.label_dtype = int self.copy_image_to_label = False self.additive_noise_p_per_sample = 0.2 self.additive_noise_mean = (0.0, 0.0) self.additive_noise_sigma = (1e-3, 1e-4) self.biasfield_p_per_sample = 0.33 self.blurring_p_per_sample = 0.2 self.blurring_sigma = (0.0, 1.0) self.blurring_p_per_channel = 0.5 self.elastic_deform_p_per_sample = 0.33 self.elastic_deform_alpha = (200, 600) self.elastic_deform_sigma = (20, 30) self.gamma_p_per_sample = 0.2 self.gamma_p_invert_image = 0.05 self.gamma_range = (0.5, 2.0) self.gibbs_ringing_p_per_sample = 0.2 self.gibbs_ringing_cutfreq = (96, 129) self.gibbs_ringing_axes = (0, 2) if is_2d else (0, 3) self.mirror_p_per_sample = 0.0 self.mirror_p_per_axis = 0.33 self.mirror_axes = (0, 1) if is_2d else (0, 1, 2) self.motion_ghosting_p_per_sample = 0.2 self.motion_ghosting_alpha = (0.85, 0.95) self.motion_ghosting_numreps = (2, 11) self.motion_ghosting_axes = (0, 2) if is_2d else (0, 3) self.multiplicative_noise_p_per_sample = 0.2 self.multiplicative_noise_mean = (0, 0) self.multiplicative_noise_sigma = (1e-3, 1e-4) self.rotation_p_per_sample = 0.2 self.rotation_p_per_axis = 0.66 self.rotation_x = (-30.0, 30.0) self.rotation_y = (-0.0, 0.0) if is_2d else (-30.0, 30.0) self.rotation_z = (-0.0, 0.0) if is_2d else (-30.0, 30.0) self.scale_p_per_sample = 0.2 self.scale_factor = (0.9, 1.1) self.simulate_lowres_p_per_sample = 0.2 self.simulate_lowres_p_per_channel = 0.5 self.simulate_lowres_p_per_axis = 0.33 self.simulate_lowres_zoom_range = (0.5, 1.0) @property def pre_aug_patch_size(self): # First check if any spatial transforms are included if self.elastic_deform_p_per_sample > 0 or self.rotation_p_per_sample > 0 or self.scale_p_per_sample > 0: self._pre_aug_patch_size = get_max_rotated_size(self.patch_size) return self._pre_aug_patch_size def apply_task_type_specific_preset(self, task_type_preset): if task_type_preset == "classification": self.skip_label = True if task_type_preset == "unsupervised": self.skip_label = True self.copy_image_to_label = True # This should be uncommented when masking is properly implemented # augmentation_parameter_dict["mask_image_for_reconstruction"] = True def overwrite_params(self, parameter_dict): for key, value in parameter_dict.items(): setattr(self, key, value) def compose_train_transforms(self): tr_transforms = transforms.Compose( [ AddBatchDimension(), Spatial( patch_size=self.patch_size, crop=True, random_crop=self.random_crop, p_deform_per_sample=self.elastic_deform_p_per_sample, deform_sigma=self.elastic_deform_sigma, deform_alpha=self.elastic_deform_alpha, p_rot_per_sample=self.rotation_p_per_sample, p_rot_per_axis=self.rotation_p_per_axis, x_rot_in_degrees=self.rotation_x, y_rot_in_degrees=self.rotation_y, z_rot_in_degrees=self.rotation_z, p_scale_per_sample=self.scale_p_per_sample, scale_factor=self.scale_factor, skip_label=self.skip_label, ), AdditiveNoise( p_per_sample=self.additive_noise_p_per_sample, mean=self.additive_noise_mean, sigma=self.additive_noise_sigma, ), Blur( p_per_sample=self.blurring_p_per_sample, p_per_channel=self.blurring_p_per_channel, sigma=self.blurring_sigma, ), MultiplicativeNoise( p_per_sample=self.multiplicative_noise_p_per_sample, mean=self.multiplicative_noise_mean, sigma=self.multiplicative_noise_sigma, ), MotionGhosting( p_per_sample=self.motion_ghosting_p_per_sample, alpha=self.motion_ghosting_alpha, numReps=self.motion_ghosting_numreps, axes=self.motion_ghosting_axes, ), GibbsRinging( p_per_sample=self.gibbs_ringing_p_per_sample, cutFreq=self.gibbs_ringing_cutfreq, axes=self.gibbs_ringing_axes, ), SimulateLowres( p_per_sample=self.simulate_lowres_p_per_sample, p_per_channel=self.simulate_lowres_p_per_channel, p_per_axis=self.simulate_lowres_p_per_axis, zoom_range=self.simulate_lowres_zoom_range, ), BiasField(p_per_sample=self.biasfield_p_per_sample), Gamma( p_per_sample=self.gamma_p_per_sample, p_invert_image=self.gamma_p_invert_image, gamma_range=self.gamma_range, ), Mirror( p_per_sample=self.mirror_p_per_sample, axes=self.mirror_axes, p_mirror_per_axis=self.mirror_p_per_axis, skip_label=self.skip_label, ), DownsampleSegForDS(deep_supervision=self.deep_supervision), CopyImageToSeg(copy=self.copy_image_to_label),
Masking(mask=self.mask_image_for_reconstruction),
8
2023-10-26 08:13:03+00:00
16k
Elfenreigen/UniChest
optim/optim_factory.py
[ { "identifier": "Adafactor", "path": "optim/adafactor.py", "snippet": "class Adafactor(torch.optim.Optimizer):\n \"\"\"Implements Adafactor algorithm.\n This implementation is based on: `Adafactor: Adaptive Learning Rates with Sublinear Memory Cost`\n (see https://arxiv.org/abs/1804.04235)\n\n ...
import torch from torch import optim as optim from .adafactor import Adafactor from .adahessian import Adahessian from .adamp import AdamP from .lookahead import Lookahead from .nadam import Nadam from .novograd import NovoGrad from .nvnovograd import NvNovoGrad from .radam import RAdam from .rmsprop_tf import RMSpropTF from .sgdp import SGDP from apex.optimizers import FusedNovoGrad, FusedAdam, FusedLAMB, FusedSGD
12,364
""" Optimizer Factory w/ Custom Weight Decay Hacked together by / Copyright 2020 Ross Wightman """ try: has_apex = True except ImportError: has_apex = False def add_weight_decay(model, image_encoder,text_encoder, weight_decay=1e-5, skip_list=()): decay = [] no_decay = [] for name, param in model.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: no_decay.append(param) else: decay.append(param) for name, param in image_encoder.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: no_decay.append(param) else: decay.append(param) for name, param in text_encoder.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: no_decay.append(param) else: decay.append(param) return [ {'params': no_decay, 'weight_decay': 0.}, {'params': decay, 'weight_decay': weight_decay}] def create_optimizer(args, model, image_encoder,text_encoder, filter_bias_and_bn=True): opt_lower = args.opt.lower() weight_decay = args.weight_decay if weight_decay and filter_bias_and_bn: skip = {} if hasattr(model, 'no_weight_decay'): skip = model.no_weight_decay() parameters = add_weight_decay(model,image_encoder,text_encoder, weight_decay, skip) weight_decay = 0. else: parameters = [filter(lambda p: p.requires_grad, model.parameters()),filter(lambda p: p.requires_grad, image_encoder.parameters()),filter(lambda p: p.requires_grad, text_encoder.parameters())] #model.parameters() # print(parameters) if 'fused' in opt_lower: assert has_apex and torch.cuda.is_available(), 'APEX and CUDA required for fused optimizers' opt_args = dict(lr=args.lr, weight_decay=weight_decay) if hasattr(args, 'opt_eps') and args.opt_eps is not None: opt_args['eps'] = args.opt_eps if hasattr(args, 'opt_betas') and args.opt_betas is not None: opt_args['betas'] = args.opt_betas if hasattr(args, 'opt_args') and args.opt_args is not None: opt_args.update(args.opt_args) opt_split = opt_lower.split('_') opt_lower = opt_split[-1] if opt_lower == 'sgd' or opt_lower == 'nesterov': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'momentum': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=False, **opt_args) elif opt_lower == 'adam': optimizer = optim.Adam(parameters, **opt_args) elif opt_lower == 'adamw': optimizer = optim.AdamW(parameters, **opt_args) elif opt_lower == 'nadam': optimizer = Nadam(parameters, **opt_args) elif opt_lower == 'radam':
""" Optimizer Factory w/ Custom Weight Decay Hacked together by / Copyright 2020 Ross Wightman """ try: has_apex = True except ImportError: has_apex = False def add_weight_decay(model, image_encoder,text_encoder, weight_decay=1e-5, skip_list=()): decay = [] no_decay = [] for name, param in model.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: no_decay.append(param) else: decay.append(param) for name, param in image_encoder.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: no_decay.append(param) else: decay.append(param) for name, param in text_encoder.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list: no_decay.append(param) else: decay.append(param) return [ {'params': no_decay, 'weight_decay': 0.}, {'params': decay, 'weight_decay': weight_decay}] def create_optimizer(args, model, image_encoder,text_encoder, filter_bias_and_bn=True): opt_lower = args.opt.lower() weight_decay = args.weight_decay if weight_decay and filter_bias_and_bn: skip = {} if hasattr(model, 'no_weight_decay'): skip = model.no_weight_decay() parameters = add_weight_decay(model,image_encoder,text_encoder, weight_decay, skip) weight_decay = 0. else: parameters = [filter(lambda p: p.requires_grad, model.parameters()),filter(lambda p: p.requires_grad, image_encoder.parameters()),filter(lambda p: p.requires_grad, text_encoder.parameters())] #model.parameters() # print(parameters) if 'fused' in opt_lower: assert has_apex and torch.cuda.is_available(), 'APEX and CUDA required for fused optimizers' opt_args = dict(lr=args.lr, weight_decay=weight_decay) if hasattr(args, 'opt_eps') and args.opt_eps is not None: opt_args['eps'] = args.opt_eps if hasattr(args, 'opt_betas') and args.opt_betas is not None: opt_args['betas'] = args.opt_betas if hasattr(args, 'opt_args') and args.opt_args is not None: opt_args.update(args.opt_args) opt_split = opt_lower.split('_') opt_lower = opt_split[-1] if opt_lower == 'sgd' or opt_lower == 'nesterov': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=True, **opt_args) elif opt_lower == 'momentum': opt_args.pop('eps', None) optimizer = optim.SGD(parameters, momentum=args.momentum, nesterov=False, **opt_args) elif opt_lower == 'adam': optimizer = optim.Adam(parameters, **opt_args) elif opt_lower == 'adamw': optimizer = optim.AdamW(parameters, **opt_args) elif opt_lower == 'nadam': optimizer = Nadam(parameters, **opt_args) elif opt_lower == 'radam':
optimizer = RAdam(parameters, **opt_args)
7
2023-10-30 00:24:16+00:00
16k
YichenZW/Coh-MGT-Detection
run_detector.py
[ { "identifier": "glue_compute_metrics", "path": "util.py", "snippet": "def glue_compute_metrics(task_name, preds, labels):\n assert len(preds) == len(labels)\n if task_name == \"cola\":\n return {\"mcc\": matthews_corrcoef(labels, preds)}\n elif task_name == \"sst-2\":\n return {\...
import os import torch import argparse import logging import random import wandb import numpy as np import ray from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm, trange from torch.optim import AdamW from transformers import ( set_seed, AutoTokenizer, AutoConfig, AutoModel, AutoModelForSequenceClassification, get_linear_schedule_with_warmup, ) from functools import partial from util import glue_compute_metrics as compute_metrics from util import ( glue_convert_examples_to_features as convert_examples_to_features, ) from util import glue_output_modes as output_modes from util import glue_processors as processors from modeling_roberta import ( RobertaForGraphBasedSequenceClassification, RobertaForGraphBasedSequenceClassification_CL, RobertaForGraphBasedSequenceClassification_MBCL, EncoderForMBCL, RobertaForGraphBasedSequenceClassification_RFCL, ) from ray import tune from ray.tune import CLIReporter from ray.tune.schedulers import ASHAScheduler from apex import amp
11,050
) torch.save( scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt") ) logger.info("Saving optimizer and scheduler states to %s", output_dir) if args.max_steps > 0 and global_step > args.max_steps: train_iterator.close() break return_res = { "max_acc": max_acc, "max_acc_f1": max_acc_f1, "max_f1": max_f1, "max_f1_acc": max_f1_acc, } if args.do_ray: tune.report( accuracy=max_acc, max_acc_f1=max_acc_f1, f1=max_f1, max_f1_acc=max_f1_acc ) return global_step, tr_loss / global_step, return_res, output_dir def evaluate(args, model, tokenizer, checkpoint=None, prefix="", mode="dev"): eval_task_names = (args.task_name,) eval_outputs_dirs = (args.output_dir,) results = {} for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs): eval_dataset = load_and_cache_examples( args, eval_task, tokenizer, evaluate=True, mode=mode ) if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]: os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) # Note that DistributedSampler samples randomly. eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader( eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size ) if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel): model = torch.nn.DataParallel(model) # Evaluation logger.info("***** Running evaluation {} *****".format(prefix)) logger.info(" Num examples = %d", len(eval_dataset)) logger.info(" Batch size = %d", args.eval_batch_size) eval_loss = 0.0 nb_eval_steps = 0 preds, out_label_ids = None, None for batch in tqdm(eval_dataloader, desc="Evaluating"): model.eval() batch = tuple(t.to(args.device) for t in batch) with torch.no_grad(): inputs = { "input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3], "nodes_index_mask": batch[4], "adj_metric": batch[5], "node_mask": batch[6], "sen2node": batch[7], "sentence_mask": batch[8], "sentence_length": batch[9], } if args.model_type != "distilbert": inputs["token_type_ids"] = ( batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None ) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids outputs, _ = model(**inputs) tmp_eval_loss, logits = outputs[:2] eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append( out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0 ) probs = preds eval_loss = eval_loss / nb_eval_steps if args.output_mode == "classification": preds = np.argmax(preds, axis=1) elif args.output_mode == "regression": preds = np.squeeze(preds) result = compute_metrics(eval_task, preds, out_label_ids) results.update(result) output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt") with open(output_eval_file, "w") as writer: logger.info("***** Eval results {} *****".format(prefix)) for key in sorted(result.keys()): logger.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key]))) wandb.log( { "eval/acc": result["acc"], "eval/f1": result["f1"], "eval/acc_and_f1": result["acc_and_f1"], } ) return results def load_and_cache_examples( args, task, tokenizer, evaluate=False, mode="train", dataset_name="", rel="" ): if args.local_rank not in [-1, 0] and not evaluate: torch.distributed.barrier()
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Based on code from the above authors, modifications made by Xi'an Jiaotong University. # # 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.getLogger(__name__) def set_seed(args): random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed) def number_h(num): for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: if abs(num) < 1000.0: return "%3.1f%s" % (num, unit) num /= 1000.0 return "%.1f%s" % (num, "Yi") def generate_shaped_nodes_mask(nodes, max_seq_length, max_nodes_num): nodes_mask = np.zeros(shape=(max_nodes_num, max_seq_length)) nodes_num = min(len(nodes), max_nodes_num) for i in range(nodes_num): span = nodes[i] if span[0] != -1: if span[0] < max_seq_length - 1: end_pos = ( span[1] if span[1] < max_seq_length - 1 else max_seq_length - 1 ) nodes_mask[i, span[0] + 1 : end_pos + 1] = 1 else: continue return nodes_mask, nodes_num def generate_shaped_edge_mask(adj_metric, nodes_num, max_nodes_num, relation_n): if nodes_num != 0: if relation_n != 0: new_adj_metric = np.zeros(shape=(relation_n, max_nodes_num, max_nodes_num)) for i in range(relation_n): new_adj_metric[i][:nodes_num, :nodes_num] = adj_metric[i][ :nodes_num, :nodes_num ] else: new_adj_metric = np.zeros(shape=(max_nodes_num, max_nodes_num)) new_adj_metric[:nodes_num, :nodes_num] = adj_metric[:nodes_num, :nodes_num] return new_adj_metric def train(args, train_dataset, model, tokenizer): """Train the model""" total_params = sum(p.numel() for p in model.parameters()) total_trainable_params = sum( p.numel() for p in model.parameters() if p.requires_grad ) print("Total Params:", number_h(total_params)) print("Total Trainable Params:", number_h(total_trainable_params)) args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = ( RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset) ) train_dataloader = DataLoader( train_dataset, sampler=train_sampler, batch_size=args.train_batch_size ) if args.max_steps > 0: t_total = args.max_steps args.num_train_epochs = ( args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1 ) else: t_total = ( len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs ) # Prepare optimizer and schedule (linear warmup and decay) no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay) ], "weight_decay": args.weight_decay, }, { "params": [ p for n, p in model.named_parameters() if any(nd in n for nd in no_decay) ], "weight_decay": 0.01, }, ] optimizer = AdamW( optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon ) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total ) # Check if saved optimizer or scheduler states exist if os.path.isfile( os.path.join(args.model_name_or_path, "optimizer.pt") ) and os.path.isfile(os.path.join(args.model_name_or_path, "scheduler.pt")): optimizer.load_state_dict( torch.load(os.path.join(args.model_name_or_path, "optimizer.pt")) ) scheduler.load_state_dict( torch.load(os.path.join(args.model_name_or_path, "scheduler.pt")) ) if args.fp16: try: except ImportError: raise ImportError( "Please install apex from https://www.github.com/nvidia/apex to use fp16 training." ) model, optimizer = amp.initialize( model, optimizer, opt_level=args.fp16_opt_level ) # Multi-gpu training (should be after apex fp16 initialization) if args.n_gpu > 1: model = torch.nn.DataParallel(model) # Distributed training (should be after apex fp16 initialization) if args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True, ) # Training logger.info("***** Running training *****") logger.info(" Num examples = %d", len(train_dataset)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info( " Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size ) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps * (torch.distributed.get_world_size() if args.local_rank != -1 else 1), ) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) best_acc, best_f1 = 0.0, 0.0 global_step, epochs_trained, steps_trained_in_current_epoch = 0, 0, 0 # Check if continuing training from a checkpoint if os.path.exists(args.model_name_or_path): # set global_step to gobal_step of last saved checkpoint from model path global_step = int(args.model_name_or_path.split("-")[-1].split("/")[0]) epochs_trained = global_step // ( len(train_dataloader) // args.gradient_accumulation_steps ) steps_trained_in_current_epoch = global_step % ( len(train_dataloader) // args.gradient_accumulation_steps ) logger.info( " Continuing training from checkpoint, will skip to saved global_step" ) logger.info(" Continuing training from epoch %d", epochs_trained) logger.info(" Continuing training from global step %d", global_step) logger.info( " Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch, ) tr_loss, logging_loss = 0.0, 0.0 model.zero_grad() train_iterator = trange( epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0], ) set_seed(args) max_acc, max_acc_f1, max_f1, max_f1_acc = 0.0, 0.0, 0.0, 0.0 for idx, _ in enumerate(train_iterator): tr_loss = 0.0 epoch_iterator = tqdm( train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0] ) for step, batch in enumerate(epoch_iterator): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue model.train() batch = tuple(t.to(args.device) for t in batch) inputs = { "input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3], "nodes_index_mask": batch[4], "adj_metric": batch[5], "node_mask": batch[6], "sen2node": batch[7], "sentence_mask": batch[8], "sentence_length": batch[9], "batch_id": batch[10], } if args.model_type != "distilbert": inputs["token_type_ids"] = ( batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None ) outputs, _ = model(**inputs) loss = outputs[0] wandb.log({"train/loss": loss}) if args.n_gpu > 1: loss = loss.mean() if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps if args.fp16: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() tr_loss += loss.item() epoch_iterator.set_description( "loss {}".format( round(tr_loss * args.gradient_accumulation_steps / (step + 1), 4) ) ) if (step + 1) % args.gradient_accumulation_steps == 0: if args.fp16: torch.nn.utils.clip_grad_norm_( amp.master_params(optimizer), args.max_grad_norm ) else: torch.nn.utils.clip_grad_norm_( model.parameters(), args.max_grad_norm ) optimizer.step() scheduler.step() model.zero_grad() global_step += 1 if ( args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0 ): logs = {} if ( args.local_rank == -1 and args.evaluate_during_training ): results = evaluate(args, model, tokenizer) for key, value in results.items(): eval_key = "eval_{}".format(key) logs[eval_key] = value loss_scalar = (tr_loss - logging_loss) / args.logging_steps learning_rate_scalar = scheduler.get_lr()[0] logs["learning_rate"] = learning_rate_scalar logs["loss"] = loss_scalar logging_loss = tr_loss wandb.log({"eval/loss": loss_scalar}) if args.max_steps > 0 and global_step > args.max_steps: epoch_iterator.close() break if args.local_rank in [-1, 0] and args.save_steps > 0 and args.do_eval: results = evaluate(args, model, tokenizer, checkpoint=str(idx)) logger.info("the results is {}".format(results)) if results["acc"] > max_acc: max_acc = results["acc"] max_acc_f1 = results["f1"] if results["f1"] > max_f1: max_f1 = results["f1"] max_f1_acc = results["acc"] if results["f1"] > best_f1: best_f1 = results["f1"] output_dir = os.path.join( args.output_dir, "seed-{}".format(args.seed), "checkpoint-{}-{}".format(idx, best_f1), ) if not os.path.exists(output_dir): os.makedirs(output_dir) model_to_save = ( model.module if hasattr(model, "module") else model ) # Take care of distributed/parallel training model_to_save.save_pretrained(output_dir) torch.save( args, os.path.join(output_dir, "training_{}.bin".format(idx)) ) logger.info("Saving model checkpoint to %s", output_dir) torch.save( optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt") ) torch.save( scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt") ) logger.info("Saving optimizer and scheduler states to %s", output_dir) if args.max_steps > 0 and global_step > args.max_steps: train_iterator.close() break return_res = { "max_acc": max_acc, "max_acc_f1": max_acc_f1, "max_f1": max_f1, "max_f1_acc": max_f1_acc, } if args.do_ray: tune.report( accuracy=max_acc, max_acc_f1=max_acc_f1, f1=max_f1, max_f1_acc=max_f1_acc ) return global_step, tr_loss / global_step, return_res, output_dir def mb_train(args, train_dataset, encoder_q, encoder_k, dataloader, tokenizer): """Train the model""" global memory_queue encoder_q.train() total_params = sum(p.numel() for p in encoder_q.parameters()) total_trainable_params = sum( p.numel() for p in encoder_q.parameters() if p.requires_grad ) print("Encoder Params:", number_h(total_params)) print("Encoder Trainable Params:", number_h(total_trainable_params)) args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = ( RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset) ) train_dataloader = DataLoader( train_dataset, sampler=train_sampler, batch_size=args.train_batch_size ) if args.max_steps > 0: t_total = args.max_steps args.num_train_epochs = ( args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1 ) else: t_total = ( len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs ) # Prepare optimizer and schedule (linear warmup and decay) no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [ p for n, p in encoder_q.named_parameters() if not any(nd in n for nd in no_decay) ], "weight_decay": args.weight_decay, }, { "params": [ p for n, p in encoder_q.named_parameters() if any(nd in n for nd in no_decay) ], "weight_decay": 0.01, }, ] optimizer = AdamW( optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon ) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total ) # Training logger.info("***** Running training *****") logger.info(" Num examples = %d", len(train_dataset)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info( " Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size ) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps * (torch.distributed.get_world_size() if args.local_rank != -1 else 1), ) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) best_f1 = 0.0 global_step, epochs_trained, steps_trained_in_current_epoch = 0, 0, 0 tr_loss, logging_loss = 0.0, 0.0 encoder_q.zero_grad() train_iterator = trange( epochs_trained, int(args.num_train_epochs), desc="Epoch", disable=args.local_rank not in [-1, 0], ) set_seed(args) max_acc, max_acc_f1, max_f1, max_f1_acc = 0.0, 0.0, 0.0, 0.0 for idx, _ in enumerate(train_iterator): tr_loss = 0.0 epoch_iterator = tqdm( train_dataloader, desc="Iteration", disable=args.local_rank not in [-1, 0] ) for step, batch in enumerate(epoch_iterator): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue encoder_q.train() batch = tuple(t.to(args.device) for t in batch) inputs = { "input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3], "nodes_index_mask": batch[4], "adj_metric": batch[5], "node_mask": batch[6], "sen2node": batch[7], "sentence_mask": batch[8], "sentence_length": batch[9], "batch_id": batch[10], } if args.model_type != "distilbert": inputs["token_type_ids"] = ( batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None ) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids q_outputs, q_rep = encoder_q(**inputs) # Model outputs are always tuple in transformers (see doc). if args.n_gpu > 1: loss = loss.mean() if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps loss.backward() tr_loss += loss.item() epoch_iterator.set_description( "loss {}".format( round(tr_loss * args.gradient_accumulation_steps / (step + 1), 4) ) ) if (step + 1) % args.gradient_accumulation_steps == 0: if args.fp16: torch.nn.utils.clip_grad_norm_( amp.master_params(optimizer), args.max_grad_norm ) else: torch.nn.utils.clip_grad_norm_( encoder_q.parameters(), args.max_grad_norm ) optimizer.step() scheduler.step() encoder_q.zero_grad() global_step += 1 if ( args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0 ): logs = {} if ( args.local_rank == -1 and args.evaluate_during_training ): # Only evaluate when single GPU otherwise metrics may not average well results = evaluate(args, encoder_q, tokenizer) for key, value in results.items(): eval_key = "eval_{}".format(key) logs[eval_key] = value loss_scalar = (tr_loss - logging_loss) / args.logging_steps learning_rate_scalar = scheduler.get_lr()[0] logs["learning_rate"] = learning_rate_scalar logs["loss"] = loss_scalar logging_loss = tr_loss wandb.log({"train/loss": loss_scalar}) if args.max_steps > 0 and global_step > args.max_steps: epoch_iterator.close() break if args.local_rank in [-1, 0] and args.save_steps > 0 and args.do_eval: results = evaluate(args, encoder_q, tokenizer, checkpoint=str(idx)) logger.info("the results is {}".format(results)) if results["f1"] > max_f1: max_f1 = results["f1"] max_f1_acc = results["acc"] if results["acc"] > max_acc: max_acc = results["acc"] max_acc_f1 = results["f1"] if results["f1"] > best_f1: best_f1 = results["f1"] output_dir = os.path.join( args.output_dir, "seed-{}".format(args.seed), "checkpoint-{}-{}".format(idx, best_f1), ) if not os.path.exists(output_dir): os.makedirs(output_dir) model_to_save = ( encoder_q.module if hasattr(encoder_q, "module") else encoder_q ) # Take care of distributed/parallel training model_to_save.save_pretrained(output_dir) torch.save( args, os.path.join(output_dir, "training_{}.bin".format(idx)) ) logger.info("Saving model checkpoint to %s", output_dir) torch.save( optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt") ) torch.save( scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt") ) logger.info("Saving optimizer and scheduler states to %s", output_dir) if args.max_steps > 0 and global_step > args.max_steps: train_iterator.close() break return_res = { "max_acc": max_acc, "max_acc_f1": max_acc_f1, "max_f1": max_f1, "max_f1_acc": max_f1_acc, } if args.do_ray: tune.report( accuracy=max_acc, max_acc_f1=max_acc_f1, f1=max_f1, max_f1_acc=max_f1_acc ) return global_step, tr_loss / global_step, return_res, output_dir def evaluate(args, model, tokenizer, checkpoint=None, prefix="", mode="dev"): eval_task_names = (args.task_name,) eval_outputs_dirs = (args.output_dir,) results = {} for eval_task, eval_output_dir in zip(eval_task_names, eval_outputs_dirs): eval_dataset = load_and_cache_examples( args, eval_task, tokenizer, evaluate=True, mode=mode ) if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]: os.makedirs(eval_output_dir) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) # Note that DistributedSampler samples randomly. eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader( eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size ) if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel): model = torch.nn.DataParallel(model) # Evaluation logger.info("***** Running evaluation {} *****".format(prefix)) logger.info(" Num examples = %d", len(eval_dataset)) logger.info(" Batch size = %d", args.eval_batch_size) eval_loss = 0.0 nb_eval_steps = 0 preds, out_label_ids = None, None for batch in tqdm(eval_dataloader, desc="Evaluating"): model.eval() batch = tuple(t.to(args.device) for t in batch) with torch.no_grad(): inputs = { "input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3], "nodes_index_mask": batch[4], "adj_metric": batch[5], "node_mask": batch[6], "sen2node": batch[7], "sentence_mask": batch[8], "sentence_length": batch[9], } if args.model_type != "distilbert": inputs["token_type_ids"] = ( batch[2] if args.model_type in ["bert", "xlnet", "albert"] else None ) # XLM, DistilBERT, RoBERTa, and XLM-RoBERTa don't use segment_ids outputs, _ = model(**inputs) tmp_eval_loss, logits = outputs[:2] eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append( out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0 ) probs = preds eval_loss = eval_loss / nb_eval_steps if args.output_mode == "classification": preds = np.argmax(preds, axis=1) elif args.output_mode == "regression": preds = np.squeeze(preds) result = compute_metrics(eval_task, preds, out_label_ids) results.update(result) output_eval_file = os.path.join(eval_output_dir, prefix, "eval_results.txt") with open(output_eval_file, "w") as writer: logger.info("***** Eval results {} *****".format(prefix)) for key in sorted(result.keys()): logger.info(" %s = %s", key, str(result[key])) writer.write("%s = %s\n" % (key, str(result[key]))) wandb.log( { "eval/acc": result["acc"], "eval/f1": result["f1"], "eval/acc_and_f1": result["acc_and_f1"], } ) return results def load_and_cache_examples( args, task, tokenizer, evaluate=False, mode="train", dataset_name="", rel="" ): if args.local_rank not in [-1, 0] and not evaluate: torch.distributed.barrier()
processor = processors[task]()
0
2023-10-24 14:03:11+00:00
16k
deforum-studio/deforum
src/deforum/models/depth_models/zoedepth/models/zoedepth_nk/zoedepth_nk_v1.py
[ { "identifier": "DepthModel", "path": "src/deforum/models/depth_models/zoedepth/models/depth_model.py", "snippet": "class DepthModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.device = 'cuda'\n \n def to(self, device) -> nn.Module:\n self.device = device\...
import itertools import torch import torch.nn as nn from ..depth_model import DepthModel from ..base_models.midas import MidasCore from ..layers.attractor import AttractorLayer, AttractorLayerUnnormed from ..layers.dist_layers import ConditionalLogBinomial from ..layers.localbins_layers import (Projector, SeedBinRegressor, SeedBinRegressorUnnormed) from ..layers.patch_transformer import PatchTransformerEncoder from ..model_io import load_state_from_resource
11,174
b_prev = (seed_b_centers - min_depth) / (max_depth - min_depth) else: b_prev = seed_b_centers prev_b_embedding = self.seed_projector(x) attractors = self.attractors[bin_conf_name] for projector, attractor, x in zip(self.projectors, attractors, x_blocks): b_embedding = projector(x) b, b_centers = attractor( b_embedding, b_prev, prev_b_embedding, interpolate=True) b_prev = b prev_b_embedding = b_embedding last = outconv_activation b_centers = nn.functional.interpolate( b_centers, last.shape[-2:], mode='bilinear', align_corners=True) b_embedding = nn.functional.interpolate( b_embedding, last.shape[-2:], mode='bilinear', align_corners=True) clb = self.conditional_log_binomial[bin_conf_name] x = clb(last, b_embedding) # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor # print(x.shape, b_centers.shape) # b_centers = nn.functional.interpolate(b_centers, x.shape[-2:], mode='bilinear', align_corners=True) out = torch.sum(x * b_centers, dim=1, keepdim=True) output = dict(domain_logits=domain_logits, metric_depth=out) if return_final_centers or return_probs: output['bin_centers'] = b_centers if return_probs: output['probs'] = x return output def get_lr_params(self, lr): """ Learning rate configuration for different layers of the model Args: lr (float) : Base learning rate Returns: list : list of parameters to optimize and their learning rates, in the format required by torch optimizers. """ param_conf = [] if self.train_midas: def get_rel_pos_params(): for name, p in self.core.core.pretrained.named_parameters(): if "relative_position" in name: yield p def get_enc_params_except_rel_pos(): for name, p in self.core.core.pretrained.named_parameters(): if "relative_position" not in name: yield p encoder_params = get_enc_params_except_rel_pos() rel_pos_params = get_rel_pos_params() midas_params = self.core.core.scratch.parameters() midas_lr_factor = self.midas_lr_factor if self.is_midas_pretrained else 1.0 param_conf.extend([ {'params': encoder_params, 'lr': lr / self.encoder_lr_factor}, {'params': rel_pos_params, 'lr': lr / self.pos_enc_lr_factor}, {'params': midas_params, 'lr': lr / midas_lr_factor} ]) remaining_modules = [] for name, child in self.named_children(): if name != 'core': remaining_modules.append(child) remaining_params = itertools.chain( *[child.parameters() for child in remaining_modules]) param_conf.append({'params': remaining_params, 'lr': lr}) return param_conf def get_conf_parameters(self, conf_name): """ Returns parameters of all the ModuleDicts children that are exclusively used for the given bin configuration """ params = [] for name, child in self.named_children(): if isinstance(child, nn.ModuleDict): for bin_conf_name, module in child.items(): if bin_conf_name == conf_name: params += list(module.parameters()) return params def freeze_conf(self, conf_name): """ Freezes all the parameters of all the ModuleDicts children that are exclusively used for the given bin configuration """ for p in self.get_conf_parameters(conf_name): p.requires_grad = False def unfreeze_conf(self, conf_name): """ Unfreezes all the parameters of all the ModuleDicts children that are exclusively used for the given bin configuration """ for p in self.get_conf_parameters(conf_name): p.requires_grad = True def freeze_all_confs(self): """ Freezes all the parameters of all the ModuleDicts children """ for name, child in self.named_children(): if isinstance(child, nn.ModuleDict): for bin_conf_name, module in child.items(): for p in module.parameters(): p.requires_grad = False @staticmethod def build(midas_model_type="DPT_BEiT_L_384", pretrained_resource=None, use_pretrained_midas=False, train_midas=False, freeze_midas_bn=True, **kwargs): core = MidasCore.build(midas_model_type=midas_model_type, use_pretrained_midas=use_pretrained_midas, train_midas=train_midas, fetch_features=True, freeze_bn=freeze_midas_bn, **kwargs) model = ZoeDepthNK(core, **kwargs) if pretrained_resource: assert isinstance(pretrained_resource, str), "pretrained_resource must be a string"
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # File author: Shariq Farooq Bhat class ZoeDepthNK(DepthModel): def __init__(self, core, bin_conf, bin_centers_type="softplus", bin_embedding_dim=128, n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, memory_efficient=False, train_midas=True, is_midas_pretrained=True, midas_lr_factor=1, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs): """ZoeDepthNK model. This is the version of ZoeDepth that has two metric heads and uses a learned router to route to experts. Args: core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features bin_conf (List[dict]): A list of dictionaries that contain the bin configuration for each metric head. Each dictionary should contain the following keys: "name" (str, typically same as the dataset name), "n_bins" (int), "min_depth" (float), "max_depth" (float) The length of this list determines the number of metric heads. bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded. Defaults to "normed". bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1]. attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300. attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2. attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'. attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'. min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5. max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50. memory_efficient (bool, optional): Whether to use memory efficient version of attractor layers. Memory efficient version is slower but is recommended incase of multiple metric heads in order save GPU memory. Defaults to False. train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True. is_midas_pretrained (bool, optional): Is "core" pretrained? Defaults to True. midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10. encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10. pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10. """ super().__init__() self.core = core self.bin_conf = bin_conf self.min_temp = min_temp self.max_temp = max_temp self.memory_efficient = memory_efficient self.train_midas = train_midas self.is_midas_pretrained = is_midas_pretrained self.midas_lr_factor = midas_lr_factor self.encoder_lr_factor = encoder_lr_factor self.pos_enc_lr_factor = pos_enc_lr_factor self.inverse_midas = inverse_midas N_MIDAS_OUT = 32 btlnck_features = self.core.output_channels[0] num_out_features = self.core.output_channels[1:] # self.scales = [16, 8, 4, 2] # spatial scale factors self.conv2 = nn.Conv2d( btlnck_features, btlnck_features, kernel_size=1, stride=1, padding=0) # Transformer classifier on the bottleneck self.patch_transformer = PatchTransformerEncoder( btlnck_features, 1, 128, use_class_token=True) self.mlp_classifier = nn.Sequential( nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 2) ) if bin_centers_type == "normed": SeedBinRegressorLayer = SeedBinRegressor Attractor = AttractorLayer elif bin_centers_type == "softplus": SeedBinRegressorLayer = SeedBinRegressorUnnormed Attractor = AttractorLayerUnnormed elif bin_centers_type == "hybrid1": SeedBinRegressorLayer = SeedBinRegressor Attractor = AttractorLayerUnnormed elif bin_centers_type == "hybrid2": SeedBinRegressorLayer = SeedBinRegressorUnnormed Attractor = AttractorLayer else: raise ValueError( "bin_centers_type should be one of 'normed', 'softplus', 'hybrid1', 'hybrid2'") self.bin_centers_type = bin_centers_type # We have bins for each bin conf. # Create a map (ModuleDict) of 'name' -> seed_bin_regressor self.seed_bin_regressors = nn.ModuleDict( {conf['name']: SeedBinRegressorLayer(btlnck_features, conf["n_bins"], mlp_dim=bin_embedding_dim // 2, min_depth=conf["min_depth"], max_depth=conf["max_depth"]) for conf in bin_conf} ) self.seed_projector = Projector( btlnck_features, bin_embedding_dim, mlp_dim=bin_embedding_dim // 2) self.projectors = nn.ModuleList([ Projector(num_out, bin_embedding_dim, mlp_dim=bin_embedding_dim // 2) for num_out in num_out_features ]) # Create a map (ModuleDict) of 'name' -> attractors (ModuleList) self.attractors = nn.ModuleDict( {conf['name']: nn.ModuleList([ Attractor(bin_embedding_dim, n_attractors[i], mlp_dim=bin_embedding_dim, alpha=attractor_alpha, gamma=attractor_gamma, kind=attractor_kind, attractor_type=attractor_type, memory_efficient=memory_efficient, min_depth=conf["min_depth"], max_depth=conf["max_depth"]) for i in range(len(n_attractors)) ]) for conf in bin_conf} ) last_in = N_MIDAS_OUT # conditional log binomial for each bin conf self.conditional_log_binomial = nn.ModuleDict( {conf['name']: ConditionalLogBinomial(last_in, bin_embedding_dim, conf['n_bins'], bottleneck_factor=4, min_temp=self.min_temp, max_temp=self.max_temp) for conf in bin_conf} ) def forward(self, x, return_final_centers=False, denorm=False, return_probs=False, **kwargs): """ Args: x (torch.Tensor): Input image tensor of shape (B, C, H, W). Assumes all images are from the same domain. return_final_centers (bool, optional): Whether to return the final centers of the attractors. Defaults to False. denorm (bool, optional): Whether to denormalize the input image. Defaults to False. return_probs (bool, optional): Whether to return the probabilities of the bins. Defaults to False. Returns: dict: Dictionary of outputs with keys: - "rel_depth": Relative depth map of shape (B, 1, H, W) - "metric_depth": Metric depth map of shape (B, 1, H, W) - "domain_logits": Domain logits of shape (B, 2) - "bin_centers": Bin centers of shape (B, N, H, W). Present only if return_final_centers is True - "probs": Bin probabilities of shape (B, N, H, W). Present only if return_probs is True """ b, c, h, w = x.shape self.orig_input_width = w self.orig_input_height = h rel_depth, out = self.core(x, denorm=denorm, return_rel_depth=True) outconv_activation = out[0] btlnck = out[1] x_blocks = out[2:] x_d0 = self.conv2(btlnck) x = x_d0 # Predict which path to take embedding = self.patch_transformer(x)[0] # N, E domain_logits = self.mlp_classifier(embedding) # N, 2 domain_vote = torch.softmax(domain_logits.sum( dim=0, keepdim=True), dim=-1) # 1, 2 # Get the path bin_conf_name = ["nyu", "kitti"][torch.argmax( domain_vote, dim=-1).squeeze().item()] try: conf = [c for c in self.bin_conf if c["name"] == bin_conf_name][0] except IndexError: raise ValueError( f"bin_conf_name {bin_conf_name} not found in bin_confs") min_depth = conf['min_depth'] max_depth = conf['max_depth'] seed_bin_regressor = self.seed_bin_regressors[bin_conf_name] _, seed_b_centers = seed_bin_regressor(x) if self.bin_centers_type == 'normed' or self.bin_centers_type == 'hybrid2': b_prev = (seed_b_centers - min_depth) / (max_depth - min_depth) else: b_prev = seed_b_centers prev_b_embedding = self.seed_projector(x) attractors = self.attractors[bin_conf_name] for projector, attractor, x in zip(self.projectors, attractors, x_blocks): b_embedding = projector(x) b, b_centers = attractor( b_embedding, b_prev, prev_b_embedding, interpolate=True) b_prev = b prev_b_embedding = b_embedding last = outconv_activation b_centers = nn.functional.interpolate( b_centers, last.shape[-2:], mode='bilinear', align_corners=True) b_embedding = nn.functional.interpolate( b_embedding, last.shape[-2:], mode='bilinear', align_corners=True) clb = self.conditional_log_binomial[bin_conf_name] x = clb(last, b_embedding) # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor # print(x.shape, b_centers.shape) # b_centers = nn.functional.interpolate(b_centers, x.shape[-2:], mode='bilinear', align_corners=True) out = torch.sum(x * b_centers, dim=1, keepdim=True) output = dict(domain_logits=domain_logits, metric_depth=out) if return_final_centers or return_probs: output['bin_centers'] = b_centers if return_probs: output['probs'] = x return output def get_lr_params(self, lr): """ Learning rate configuration for different layers of the model Args: lr (float) : Base learning rate Returns: list : list of parameters to optimize and their learning rates, in the format required by torch optimizers. """ param_conf = [] if self.train_midas: def get_rel_pos_params(): for name, p in self.core.core.pretrained.named_parameters(): if "relative_position" in name: yield p def get_enc_params_except_rel_pos(): for name, p in self.core.core.pretrained.named_parameters(): if "relative_position" not in name: yield p encoder_params = get_enc_params_except_rel_pos() rel_pos_params = get_rel_pos_params() midas_params = self.core.core.scratch.parameters() midas_lr_factor = self.midas_lr_factor if self.is_midas_pretrained else 1.0 param_conf.extend([ {'params': encoder_params, 'lr': lr / self.encoder_lr_factor}, {'params': rel_pos_params, 'lr': lr / self.pos_enc_lr_factor}, {'params': midas_params, 'lr': lr / midas_lr_factor} ]) remaining_modules = [] for name, child in self.named_children(): if name != 'core': remaining_modules.append(child) remaining_params = itertools.chain( *[child.parameters() for child in remaining_modules]) param_conf.append({'params': remaining_params, 'lr': lr}) return param_conf def get_conf_parameters(self, conf_name): """ Returns parameters of all the ModuleDicts children that are exclusively used for the given bin configuration """ params = [] for name, child in self.named_children(): if isinstance(child, nn.ModuleDict): for bin_conf_name, module in child.items(): if bin_conf_name == conf_name: params += list(module.parameters()) return params def freeze_conf(self, conf_name): """ Freezes all the parameters of all the ModuleDicts children that are exclusively used for the given bin configuration """ for p in self.get_conf_parameters(conf_name): p.requires_grad = False def unfreeze_conf(self, conf_name): """ Unfreezes all the parameters of all the ModuleDicts children that are exclusively used for the given bin configuration """ for p in self.get_conf_parameters(conf_name): p.requires_grad = True def freeze_all_confs(self): """ Freezes all the parameters of all the ModuleDicts children """ for name, child in self.named_children(): if isinstance(child, nn.ModuleDict): for bin_conf_name, module in child.items(): for p in module.parameters(): p.requires_grad = False @staticmethod def build(midas_model_type="DPT_BEiT_L_384", pretrained_resource=None, use_pretrained_midas=False, train_midas=False, freeze_midas_bn=True, **kwargs): core = MidasCore.build(midas_model_type=midas_model_type, use_pretrained_midas=use_pretrained_midas, train_midas=train_midas, fetch_features=True, freeze_bn=freeze_midas_bn, **kwargs) model = ZoeDepthNK(core, **kwargs) if pretrained_resource: assert isinstance(pretrained_resource, str), "pretrained_resource must be a string"
model = load_state_from_resource(model, pretrained_resource)
9
2023-10-28 14:23:27+00:00
16k
samholt/ActiveObservingInContinuous-timeControl
mppi_dataset_collector.py
[ { "identifier": "dotdict", "path": "config.py", "snippet": "class dotdict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\n\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__" }, { "identifier": "create_env", "path": "over...
import logging import os import time import imageio import numpy as np import torch import torch.multiprocessing as multiprocessing from functools import partial from tqdm import tqdm from config import dotdict from overlay import create_env, setup_logger, start_virtual_display, step_env from planners.mppi import MPPI from planners.mppi_active_observing import MPPIActiveObserving from oracle import pendulum_dynamics_dt from oracle import cartpole_dynamics_dt from oracle import acrobot_dynamics_dt from oracle import cancer_dynamics_dt from pathlib import Path from config import get_config, seed_all
10,832
env_name, roll_outs=1000, time_steps=30, lambda_=1.0, sigma=1.0, dt=0.05, model_seed=11, save_video=False, state_constraint=False, change_goal=False, encode_obs_time=False, model=None, uniq=None, log_debug=False, episodes_per_sampler_task=10, config={}, iter_=200, change_goal_flipped_iter_=False, ts_grid="exp", intermediate_run=False, ): config = dotdict(config) env = create_env(env_name, dt=dt, ts_grid=ts_grid, friction=config.friction) ACTION_LOW = env.action_space.low[0] ACTION_HIGH = env.action_space.high[0] if env_name == "oderl-cancer": limit_actions_to_only_positive = True else: limit_actions_to_only_positive = False nx = env.get_obs().shape[0] nu = env.action_space.shape[0] dtype = torch.float32 gamma = sigma**2 off_diagonal = 0.5 * gamma mppi_noise_sigma = torch.ones((nu, nu), device=device, dtype=dtype) * off_diagonal + torch.eye( nu, device=device, dtype=dtype ) * (gamma - off_diagonal) logger.info(mppi_noise_sigma) mppi_lambda_ = 1.0 random_action_noise = config.collect_expert_random_action_noise if model_name == "random": def dynamics(state, perturbed_action): pass elif model_name == "oracle": oracle_sigma = config.observation_noise if env_name == "oderl-pendulum": dynamics_oracle = pendulum_dynamics_dt elif env_name == "oderl-cartpole": dynamics_oracle = cartpole_dynamics_dt elif env_name == "oderl-acrobot": dynamics_oracle = acrobot_dynamics_dt elif env_name == "oderl-cancer": dynamics_oracle = cancer_dynamics_dt def dynamics(*args, **kwargs): state_mu = dynamics_oracle(*args, **kwargs) return state_mu, torch.ones_like(state_mu) * oracle_sigma dynamics = partial(dynamics, friction=config.friction) def running_cost(state, action): if state_constraint: reward = env.diff_obs_reward_( state, exp_reward=False, state_constraint=state_constraint ) + env.diff_ac_reward_(action) elif change_goal: global change_goal_flipped reward = env.diff_obs_reward_( state, exp_reward=False, change_goal=change_goal, change_goal_flipped=change_goal_flipped ) + env.diff_ac_reward_(action) else: reward = env.diff_obs_reward_(state, exp_reward=False) + env.diff_ac_reward_(action) cost = -reward return cost if config.planner == "mppi": mppi_gym = MPPI( dynamics, running_cost, nx, mppi_noise_sigma, num_samples=roll_outs, horizon=time_steps, device=device, lambda_=mppi_lambda_, u_min=torch.tensor(ACTION_LOW), u_max=torch.tensor(ACTION_HIGH), u_scale=ACTION_HIGH, ) elif config.planner == "mppi_active_observing": mppi_gym = MPPIActiveObserving( dynamics, running_cost, nx, mppi_noise_sigma, num_samples=roll_outs, horizon=time_steps, device=device, lambda_=mppi_lambda_, u_min=torch.tensor(ACTION_LOW), u_max=torch.tensor(ACTION_HIGH), u_scale=ACTION_HIGH, observing_cost=config.observing_cost, sampling_policy=config.sampling_policy, observing_var_threshold=config.observing_var_threshold, limit_actions_to_only_positive=limit_actions_to_only_positive, dt=dt, ) if save_video:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logger = logging.getLogger() def inner_mppi_with_model_collect_data( seed, model_name, env_name, roll_outs=1000, time_steps=30, lambda_=1.0, sigma=1.0, dt=0.05, model_seed=11, save_video=False, state_constraint=False, change_goal=False, encode_obs_time=False, model=None, uniq=None, log_debug=False, episodes_per_sampler_task=10, config={}, iter_=200, change_goal_flipped_iter_=False, ts_grid="exp", intermediate_run=False, ): config = dotdict(config) env = create_env(env_name, dt=dt, ts_grid=ts_grid, friction=config.friction) ACTION_LOW = env.action_space.low[0] ACTION_HIGH = env.action_space.high[0] if env_name == "oderl-cancer": limit_actions_to_only_positive = True else: limit_actions_to_only_positive = False nx = env.get_obs().shape[0] nu = env.action_space.shape[0] dtype = torch.float32 gamma = sigma**2 off_diagonal = 0.5 * gamma mppi_noise_sigma = torch.ones((nu, nu), device=device, dtype=dtype) * off_diagonal + torch.eye( nu, device=device, dtype=dtype ) * (gamma - off_diagonal) logger.info(mppi_noise_sigma) mppi_lambda_ = 1.0 random_action_noise = config.collect_expert_random_action_noise if model_name == "random": def dynamics(state, perturbed_action): pass elif model_name == "oracle": oracle_sigma = config.observation_noise if env_name == "oderl-pendulum": dynamics_oracle = pendulum_dynamics_dt elif env_name == "oderl-cartpole": dynamics_oracle = cartpole_dynamics_dt elif env_name == "oderl-acrobot": dynamics_oracle = acrobot_dynamics_dt elif env_name == "oderl-cancer": dynamics_oracle = cancer_dynamics_dt def dynamics(*args, **kwargs): state_mu = dynamics_oracle(*args, **kwargs) return state_mu, torch.ones_like(state_mu) * oracle_sigma dynamics = partial(dynamics, friction=config.friction) def running_cost(state, action): if state_constraint: reward = env.diff_obs_reward_( state, exp_reward=False, state_constraint=state_constraint ) + env.diff_ac_reward_(action) elif change_goal: global change_goal_flipped reward = env.diff_obs_reward_( state, exp_reward=False, change_goal=change_goal, change_goal_flipped=change_goal_flipped ) + env.diff_ac_reward_(action) else: reward = env.diff_obs_reward_(state, exp_reward=False) + env.diff_ac_reward_(action) cost = -reward return cost if config.planner == "mppi": mppi_gym = MPPI( dynamics, running_cost, nx, mppi_noise_sigma, num_samples=roll_outs, horizon=time_steps, device=device, lambda_=mppi_lambda_, u_min=torch.tensor(ACTION_LOW), u_max=torch.tensor(ACTION_HIGH), u_scale=ACTION_HIGH, ) elif config.planner == "mppi_active_observing": mppi_gym = MPPIActiveObserving( dynamics, running_cost, nx, mppi_noise_sigma, num_samples=roll_outs, horizon=time_steps, device=device, lambda_=mppi_lambda_, u_min=torch.tensor(ACTION_LOW), u_max=torch.tensor(ACTION_HIGH), u_scale=ACTION_HIGH, observing_cost=config.observing_cost, sampling_policy=config.sampling_policy, observing_var_threshold=config.observing_var_threshold, limit_actions_to_only_positive=limit_actions_to_only_positive, dt=dt, ) if save_video:
start_virtual_display()
3
2023-10-24 16:19:14+00:00
16k
s1tools/s1-etad
s1etad/_jupyter_support.py
[ { "identifier": "Sentinel1Etad", "path": "s1etad/product.py", "snippet": "class Sentinel1Etad:\n \"\"\"Sentinel-1 ETAD product.\n\n Class to decode and access the elements of the Sentinel ETAD product\n which specification is governed by ETAD-DLR-PS-0014.\n\n The index operator [] (implement...
from .product import Sentinel1Etad, Sentinel1EtadSwath, Sentinel1EtadBurst
13,421
# -*- coding: utf-8 -*- def _sentinel1_etad_repr_pretty_(obj, p, cycle): if cycle: p.text(repr(obj)) else: p.text(repr(obj)) p.break_() plist = obj.s1_product_list() if isinstance(plist, str): plist = [plist] p.text(f"Number of Sentinel-1 slices: {len(plist)}") p.break_() with p.group(2, "Sentinel-1 products list:"): for name in plist: p.break_() p.text(name) p.break_() p.text(f"Number of swaths: {obj.number_of_swath}") p.break_() p.text("Swath list: {}".format(", ".join(obj.swath_list))) p.break_() with p.group(2, "Azimuth time:"): p.break_() p.text(f"min: {obj.min_azimuth_time}") p.break_() p.text(f"max: {obj.max_azimuth_time}") p.break_() with p.group(2, "Range time:"): p.break_() p.text(f"min: {obj.min_range_time}") p.break_() p.text(f"max: {obj.max_range_time}") p.break_() with p.group(2, "Grid sampling:"): for key, value in obj.grid_sampling.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Grid spacing:"): for key, value in obj.grid_spacing.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Processing settings:"): for key, value in obj.processing_setting().items(): p.break_() p.text(f"{key}: {value}") def _sentinel1_etad_swath_repr_pretty_(obj, p, cycle): if cycle: p.text(repr(obj)) else: p.text(repr(obj)) p.break_() p.text(f"Swaths ID: {obj.swath_id}") p.break_() p.text(f"Number of bursts: {obj.number_of_burst}") p.break_() p.text("Burst list: " + str(obj.burst_list)) p.break_() with p.group(2, "Sampling start:"): for key, value in obj.sampling_start.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Sampling:"): for key, value in obj.sampling.items(): p.break_() p.text(f"{key}: {value}") def _sentinel1_etad_burst_repr_pretty_(obj, p, cycle): if cycle: p.text(repr(obj)) else: p.text(repr(obj)) p.break_() p.text(f"Swaths ID: {obj.swath_id}") p.break_() p.text(f"Burst index: {obj.burst_index}") p.break_() p.text(f"Shape: ({obj.lines}, {obj.samples})") p.break_() with p.group(2, "Sampling start:"): for key, value in obj.sampling_start.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Sampling:"): for key, value in obj.sampling.items(): p.break_() p.text(f"{key}: {value}") def _register_jupyter_formatters(): try: ipy = get_ipython() # noqa except NameError: return False else: formatter = ipy.display_formatter.formatters["text/plain"]
# -*- coding: utf-8 -*- def _sentinel1_etad_repr_pretty_(obj, p, cycle): if cycle: p.text(repr(obj)) else: p.text(repr(obj)) p.break_() plist = obj.s1_product_list() if isinstance(plist, str): plist = [plist] p.text(f"Number of Sentinel-1 slices: {len(plist)}") p.break_() with p.group(2, "Sentinel-1 products list:"): for name in plist: p.break_() p.text(name) p.break_() p.text(f"Number of swaths: {obj.number_of_swath}") p.break_() p.text("Swath list: {}".format(", ".join(obj.swath_list))) p.break_() with p.group(2, "Azimuth time:"): p.break_() p.text(f"min: {obj.min_azimuth_time}") p.break_() p.text(f"max: {obj.max_azimuth_time}") p.break_() with p.group(2, "Range time:"): p.break_() p.text(f"min: {obj.min_range_time}") p.break_() p.text(f"max: {obj.max_range_time}") p.break_() with p.group(2, "Grid sampling:"): for key, value in obj.grid_sampling.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Grid spacing:"): for key, value in obj.grid_spacing.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Processing settings:"): for key, value in obj.processing_setting().items(): p.break_() p.text(f"{key}: {value}") def _sentinel1_etad_swath_repr_pretty_(obj, p, cycle): if cycle: p.text(repr(obj)) else: p.text(repr(obj)) p.break_() p.text(f"Swaths ID: {obj.swath_id}") p.break_() p.text(f"Number of bursts: {obj.number_of_burst}") p.break_() p.text("Burst list: " + str(obj.burst_list)) p.break_() with p.group(2, "Sampling start:"): for key, value in obj.sampling_start.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Sampling:"): for key, value in obj.sampling.items(): p.break_() p.text(f"{key}: {value}") def _sentinel1_etad_burst_repr_pretty_(obj, p, cycle): if cycle: p.text(repr(obj)) else: p.text(repr(obj)) p.break_() p.text(f"Swaths ID: {obj.swath_id}") p.break_() p.text(f"Burst index: {obj.burst_index}") p.break_() p.text(f"Shape: ({obj.lines}, {obj.samples})") p.break_() with p.group(2, "Sampling start:"): for key, value in obj.sampling_start.items(): p.break_() p.text(f"{key}: {value}") p.break_() with p.group(2, "Sampling:"): for key, value in obj.sampling.items(): p.break_() p.text(f"{key}: {value}") def _register_jupyter_formatters(): try: ipy = get_ipython() # noqa except NameError: return False else: formatter = ipy.display_formatter.formatters["text/plain"]
formatter.for_type(Sentinel1Etad, _sentinel1_etad_repr_pretty_)
0
2023-10-27 13:47:30+00:00
16k
ifrit98/storage-subnet
storage/validator/store.py
[ { "identifier": "EventSchema", "path": "storage/validator/event.py", "snippet": "class EventSchema:\n task_name: str # Task type, e.g. 'store', 'challenge', 'retrieve' 'broadcast'\n successful: List[bool] # List of whether or not the task was successful or not\n completion_times: List[float] ...
import os import sys import copy import time import torch import base64 import typing import asyncio import aioredis import bittensor as bt import websocket from pprint import pformat from pyinstrument import Profiler from Crypto.Random import get_random_bytes, random from dataclasses import asdict from storage.validator.event import EventSchema from storage import protocol from storage.shared.ecc import ( hash_data, setup_CRS, ecc_point_to_hex, ) from storage.shared.utils import b64_encode from storage.validator.utils import ( make_random_file, compute_chunk_distribution_mut_exclusive_numpy_reuse_uids, ) from storage.validator.encryption import encrypt_data from storage.validator.verify import verify_store_with_seed from storage.validator.reward import apply_reward_scores from storage.validator.database import ( add_metadata_to_hotkey, store_chunk_metadata, store_file_chunk_mapping_ordered, get_ordered_metadata, hotkey_at_capacity, ) from storage.validator.bonding import update_statistics from .reward import create_reward_vector from .network import ping_and_retry_uids, compute_and_ping_chunks, reroll_distribution from .utils import compute_chunk_distribution_mut_exclusive_numpy_reuse_uids
10,992
# Update event log with moving averaged scores event.moving_averaged_scores = self.moving_averaged_scores.tolist() return event async def store_random_data(self): """ Stores data on the network and ensures it is correctly committed by the miners. Parameters: - data (bytes, optional): The data to be stored. - wallet (bt.wallet, optional): The wallet to be used for encrypting the data. Returns: - The status of the data storage operation. """ # Setup CRS for this round of validation g, h = setup_CRS(curve=self.config.neuron.curve) # Make a random bytes file to test the miner if none provided data = make_random_file(maxsize=self.config.neuron.maxsize) bt.logging.debug(f"Random store data size: {sys.getsizeof(data)}") # Encrypt the data # TODO: create and use a throwaway wallet (never decrypable) encrypted_data, encryption_payload = encrypt_data(data, self.encryption_wallet) return await store_encrypted_data( self, encrypted_data, encryption_payload, k=self.config.neuron.store_sample_size, ttl=self.config.neuron.data_ttl, ) async def store_broadband( self, encrypted_data, encryption_payload, R=3, k=10, data_hash=None, exclude_uids=None, ): """ Asynchronously stores encrypted data across a distributed network by splitting it into chunks and assigning these chunks to various miners for storage. This method ensures redundancy and efficient data distribution while handling network requests concurrently. The process includes chunking the data, selecting miners for storage, and verifying the integrity of stored data through response validation. Parameters: encrypted_data (bytes): The encrypted data to be stored across the network. encryption_payload (dict): Additional payload information required for encryption. R (int, optional): The redundancy factor, denoting how many times each chunk is replicated. Default is 3. k (int, optional): The number of miners to query for each chunk. Default is 10. data_hash (str, optional): The hash of the data to be stored. If not provided, compute it. Default is None. exclude_uids: (list of int, optional): A list of UIDs to exclude from the storage process. Default is None. Returns: str: The hash of the full data, representing its unique identifier in the network. Raises: Exception: If the process of creating initial distributions fails after multiple retries. Note: - Uses a semaphore to limit the number of concurrent network requests. - Employs a retry mechanism for handling network and miner availability issues. - Logs various stages of the process for debugging and monitoring purposes. """ if self.config.neuron.profile: # Create a profiler instance profiler = Profiler() profiler.start() semaphore = asyncio.Semaphore(self.config.neuron.semaphore_size) async def store_chunk_group(chunk_hash, chunk, uids): event = EventSchema( task_name="Store", successful=[], completion_times=[], task_status_messages=[], task_status_codes=[], block=self.subtensor.get_current_block(), uids=[], step_length=0.0, best_uid="", best_hotkey="", rewards=[], moving_averaged_scores=[], ) g, h = setup_CRS(curve=self.config.neuron.curve) bt.logging.debug(f"type(chunk): {type(chunk)}") bt.logging.debug(f"chunk: {chunk[:100]}") chunk = chunk.encode("utf-8") if isinstance(chunk, str) else chunk b64_encoded_chunk = await asyncio.to_thread(base64.b64encode, chunk) b64_encoded_chunk = b64_encoded_chunk.decode("utf-8") bt.logging.debug(f"b64_encoded_chunk: {b64_encoded_chunk[:100]}") random_seed = get_random_bytes(32).hex() synapse = protocol.Store( encrypted_data=b64_encoded_chunk, curve=self.config.neuron.curve, g=ecc_point_to_hex(g), h=ecc_point_to_hex(h), seed=random_seed, ) uids = [ uid for uid in uids
# The MIT License (MIT) # Copyright © 2023 Yuma Rao # Copyright © 2023 philanthrope # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated # documentation files (the “Software”), to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all copies or substantial portions of # the Software. # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO # THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. async def store_encrypted_data( self, encrypted_data: typing.Union[bytes, str], encryption_payload: dict, exclude_uids: typing.List[str] = [], ttl: int = 0, k: int = None, max_retries: int = 3, ) -> bool: event = EventSchema( task_name="Store", successful=[], completion_times=[], task_status_messages=[], task_status_codes=[], block=self.subtensor.get_current_block(), uids=[], step_length=0.0, best_uid="", best_hotkey="", rewards=[], moving_averaged_scores=[], ) start_time = time.time() encrypted_data = ( encrypted_data.encode("utf-8") if isinstance(encrypted_data, str) else encrypted_data ) # Setup CRS for this round of validation g, h = setup_CRS(curve=self.config.neuron.curve) # Hash the data data_hash = hash_data(encrypted_data) # Convert to base64 for compactness # TODO: Don't do this if it's already b64 encoded. (Check first) b64_encrypted_data = base64.b64encode(encrypted_data).decode("utf-8") if self.config.neuron.verbose: bt.logging.debug(f"storing user data: {encrypted_data[:12]}...") bt.logging.debug(f"storing user hash: {data_hash}") bt.logging.debug(f"b64 encrypted data: {b64_encrypted_data[:12]}...") synapse = protocol.Store( encrypted_data=b64_encrypted_data, curve=self.config.neuron.curve, g=ecc_point_to_hex(g), h=ecc_point_to_hex(h), seed=get_random_bytes(32).hex(), # 256-bit seed ) # Select subset of miners to query (e.g. redunancy factor of N) uids, _ = await ping_and_retry_uids( self, k=k or self.config.neuron.store_redundancy, max_retries=max_retries, exclude_uids=exclude_uids, ) bt.logging.debug(f"store_encrypted_data() uids: {uids}") axons = [self.metagraph.axons[uid] for uid in uids] failed_uids = [None] retries = 0 while len(failed_uids) and retries < max_retries: if failed_uids == [None]: # initial loop failed_uids = [] # Broadcast the query to selected miners on the network. responses = await self.dendrite( axons, synapse, deserialize=False, timeout=self.config.neuron.store_timeout, ) # Compute the rewards for the responses given proc time. rewards: torch.FloatTensor = torch.zeros( len(responses), dtype=torch.float32 ).to(self.device) async def success(hotkey, idx, uid, response): # Prepare storage for the data for particular miner response_storage = { "prev_seed": synapse.seed, "size": sys.getsizeof(encrypted_data), # in bytes, not len(data) "encryption_payload": encryption_payload, } bt.logging.trace(f"Storing UID {uid} data {pformat(response_storage)}") # Store in the database according to the data hash and the miner hotkey await add_metadata_to_hotkey( hotkey, data_hash, response_storage, self.database, ) if ttl > 0: await self.database.expire( f"{hotkey}:{data_hash}", ttl, ) bt.logging.debug( f"Stored data in database with hotkey: {hotkey} | uid {uid} | {data_hash}" ) def failure(uid): failed_uids.append(uid) await create_reward_vector( self, synapse, rewards, uids, responses, event, success, failure ) event.rewards.extend(rewards.tolist()) if self.config.neuron.verbose and self.config.neuron.log_responses: bt.logging.debug(f"Store responses round: {retries}") [ bt.logging.debug(f"Store response: {response.dendrite.dict()}") for response in responses ] bt.logging.trace(f"Applying store rewards for retry: {retries}") apply_reward_scores( self, uids, responses, rewards, timeout=self.config.neuron.store_timeout, mode=self.config.neuron.reward_mode, ) # Get a new set of UIDs to query for those left behind if failed_uids != []: bt.logging.trace(f"Failed to store on uids: {failed_uids}") uids, _ = await ping_and_retry_uids( self, k=len(failed_uids), exclude_uids=exclude_uids ) bt.logging.trace(f"Retrying with new uids: {uids}") axons = [self.metagraph.axons[uid] for uid in uids] failed_uids = [] # reset failed uids for next round retries += 1 # Calculate step length end_time = time.time() event.step_length = end_time - start_time # Determine the best UID based on rewards if event.rewards: best_index = max(range(len(event.rewards)), key=event.rewards.__getitem__) event.best_uid = event.uids[best_index] event.best_hotkey = self.metagraph.hotkeys[event.best_uid] # Update event log with moving averaged scores event.moving_averaged_scores = self.moving_averaged_scores.tolist() return event async def store_random_data(self): """ Stores data on the network and ensures it is correctly committed by the miners. Parameters: - data (bytes, optional): The data to be stored. - wallet (bt.wallet, optional): The wallet to be used for encrypting the data. Returns: - The status of the data storage operation. """ # Setup CRS for this round of validation g, h = setup_CRS(curve=self.config.neuron.curve) # Make a random bytes file to test the miner if none provided data = make_random_file(maxsize=self.config.neuron.maxsize) bt.logging.debug(f"Random store data size: {sys.getsizeof(data)}") # Encrypt the data # TODO: create and use a throwaway wallet (never decrypable) encrypted_data, encryption_payload = encrypt_data(data, self.encryption_wallet) return await store_encrypted_data( self, encrypted_data, encryption_payload, k=self.config.neuron.store_sample_size, ttl=self.config.neuron.data_ttl, ) async def store_broadband( self, encrypted_data, encryption_payload, R=3, k=10, data_hash=None, exclude_uids=None, ): """ Asynchronously stores encrypted data across a distributed network by splitting it into chunks and assigning these chunks to various miners for storage. This method ensures redundancy and efficient data distribution while handling network requests concurrently. The process includes chunking the data, selecting miners for storage, and verifying the integrity of stored data through response validation. Parameters: encrypted_data (bytes): The encrypted data to be stored across the network. encryption_payload (dict): Additional payload information required for encryption. R (int, optional): The redundancy factor, denoting how many times each chunk is replicated. Default is 3. k (int, optional): The number of miners to query for each chunk. Default is 10. data_hash (str, optional): The hash of the data to be stored. If not provided, compute it. Default is None. exclude_uids: (list of int, optional): A list of UIDs to exclude from the storage process. Default is None. Returns: str: The hash of the full data, representing its unique identifier in the network. Raises: Exception: If the process of creating initial distributions fails after multiple retries. Note: - Uses a semaphore to limit the number of concurrent network requests. - Employs a retry mechanism for handling network and miner availability issues. - Logs various stages of the process for debugging and monitoring purposes. """ if self.config.neuron.profile: # Create a profiler instance profiler = Profiler() profiler.start() semaphore = asyncio.Semaphore(self.config.neuron.semaphore_size) async def store_chunk_group(chunk_hash, chunk, uids): event = EventSchema( task_name="Store", successful=[], completion_times=[], task_status_messages=[], task_status_codes=[], block=self.subtensor.get_current_block(), uids=[], step_length=0.0, best_uid="", best_hotkey="", rewards=[], moving_averaged_scores=[], ) g, h = setup_CRS(curve=self.config.neuron.curve) bt.logging.debug(f"type(chunk): {type(chunk)}") bt.logging.debug(f"chunk: {chunk[:100]}") chunk = chunk.encode("utf-8") if isinstance(chunk, str) else chunk b64_encoded_chunk = await asyncio.to_thread(base64.b64encode, chunk) b64_encoded_chunk = b64_encoded_chunk.decode("utf-8") bt.logging.debug(f"b64_encoded_chunk: {b64_encoded_chunk[:100]}") random_seed = get_random_bytes(32).hex() synapse = protocol.Store( encrypted_data=b64_encoded_chunk, curve=self.config.neuron.curve, g=ecc_point_to_hex(g), h=ecc_point_to_hex(h), seed=random_seed, ) uids = [ uid for uid in uids
if not await hotkey_at_capacity(self.metagraph.hotkeys[uid], self.database)
15
2023-10-26 18:54:47+00:00
16k
Eclectic-Sheep/sheeprlhf
sheeprlhf/task/train/ppo.py
[ { "identifier": "PPOAgent", "path": "sheeprlhf/agent/ppo.py", "snippet": "class PPOAgent:\n \"\"\"Agent model for PPO training.\"\"\"\n\n _reference: ActorModel\n _reward: RewardModel\n _finetune_mode: FINETUNE_MODE\n _actor: Optional[ActorModel] = None\n _critic: Optional[CriticModel]...
import copy import time import torch from pathlib import Path from typing import Dict from lightning import Fabric from torch.utils.data import DataLoader from tqdm import tqdm from transformers import GenerationConfig, PreTrainedTokenizer from sheeprlhf.agent.ppo import PPOAgent from sheeprlhf.data.base import TextDataset from sheeprlhf.data.collate import LeftPadCollate from sheeprlhf.loss.ppo import policy_loss, value_loss from sheeprlhf.model.actor import ActorModel from sheeprlhf.structure.data import DataConfig from sheeprlhf.structure.generation import GenConfig from sheeprlhf.structure.model import ModelConfig from sheeprlhf.structure.task import PPOConfig from sheeprlhf.utils.data import prepare_generation_config, validate_dataset from sheeprlhf.utils.helper import create_tensorboard_logger, get_log_dir, log_text from sheeprlhf.utils.hydra import instantiate_from_config from sheeprlhf.utils.metric import PPOMetricManager from sheeprlhf.utils.model import compute_grad_norm, prepare_optimizer_parameters from sheeprlhf.utils.ppo import AdaptiveKLController, FixedKLController, collect_rollout, masked_normalize from sheeprlhf.utils.registry import register_task
11,159
tokenizer=tokenizer, model_cfg=model_cfg, gen_cfg=gen_cfg, fabric=fabric, ) eval_gen_cfg = copy.deepcopy(gen_cfg) eval_gen_cfg.do_sample = False eval_generation_config = prepare_generation_config( tokenizer=tokenizer, model_cfg=model_cfg, gen_cfg=eval_gen_cfg, fabric=fabric, ) # Setup Optimizer Scheduler fabric models actor_trainable_params, _, _ = prepare_optimizer_parameters(agent.actor, weight_decay=optim_cfg.weight_decay) actor_optimizer = instantiate_from_config( optim_cfg, params=actor_trainable_params, _convert_="partial", ) actor_optimizer = fabric.setup_optimizers(actor_optimizer) critic_trainable_params, _, _ = prepare_optimizer_parameters(agent.critic, weight_decay=optim_cfg.weight_decay) critic_optimizer = instantiate_from_config( optim_cfg, params=critic_trainable_params, _convert_="partial", ) critic_optimizer = fabric.setup_optimizers(critic_optimizer) if fabric.is_global_zero: gen_text, score = generate( agent=agent, tokenizer=tokenizer, generation_config=eval_generation_config, example_prompt=example_prompt, device=fabric.device, ) log_text(fabric, gen_text, "info/example_sample", step=0) fabric.log("info/example_last_reward", score, step=0) num_training_steps = 2 if cfg.dry_run else task_cfg.epochs * len(train_dataloader) # KL Controller if task_cfg.adaptive_kl_coeff: kl_controller = AdaptiveKLController( init_kl_coef=task_cfg.init_kl_coeff, target=task_cfg.target_kl_coeff, kl_horizon=num_training_steps ) else: kl_controller = FixedKLController(kl_coeff=task_cfg.init_kl_coeff) fabric.print("Model Checkpoint interval: ", task_cfg.save_interval, "steps") fabric.print("Model Evaluation interval: ", task_cfg.eval_interval, "steps") iterator = tqdm(range(num_training_steps), disable=not fabric.is_global_zero) data_iterator = iter(train_dataloader) agent.reward.eval() for k in iterator: # Setup counters and data if k % len(train_dataloader) == 0 or data_iterator is None: data_iterator = iter(train_dataloader) is_accumulating = (k) % task_cfg.gradient_accumulation_steps != 0 last_step = k == num_training_steps - 1 # Setup batch data batch = next(data_iterator) max_prompt_length = batch["prompt_input_ids"].shape[1] agent.actor.eval() agent.critic.eval() t0 = time.time() rollout, sample_output = collect_rollout( batch=batch, agent=agent, generation_config=generation_config, kl_controller=kl_controller, task_cfg=task_cfg, tokenizer=tokenizer, fabric=fabric, metrics=metrics, ) time_rollout = time.time() - t0 rollout_dataloader = DataLoader( rollout, batch_size=task_cfg.micro_batch_size, shuffle=True, collate_fn=lambda x: x ) rollout_dataloader = fabric.setup_dataloaders(rollout_dataloader, use_distributed_sampler=False) agent.actor.train() agent.critic.train() for _ in range(task_cfg.ppo_epochs): accumulator_counter = 0 for micro_batch in rollout_dataloader: is_accumulating = (accumulator_counter) % task_cfg.gradient_accumulation_steps != 0 generated_data = { "input_ids": micro_batch["input_ids"], "attention_mask": micro_batch["attention_mask"], } old_log_probs = micro_batch["actor_log_probs"] old_values = micro_batch["values"] advantages = micro_batch["advantages"] returns = micro_batch["returns"] start_token_idx = max_prompt_length - 1 action_mask = micro_batch["attention_mask"][:, start_token_idx:-1].int() if task_cfg.normalize_advantages: advantages = masked_normalize(advantages, action_mask) with fabric.no_backward_sync(agent.actor, enabled=is_accumulating): log_probs = agent.actor(**generated_data)[:, start_token_idx:] # (B, num_new_tokens) p_loss = policy_loss( log_probs=log_probs, old_log_probs=old_log_probs, advantages=advantages, clip_coeff=task_cfg.clip_coeff, action_mask=action_mask, ) fabric.backward(p_loss / task_cfg.gradient_accumulation_steps) with fabric.no_backward_sync(agent.critic, enabled=is_accumulating): values = agent.critic(**generated_data)[:, start_token_idx:-1] # (B, num_new_tokens)
@torch.no_grad() def generate( # noqa: D103 agent: PPOAgent, tokenizer: PreTrainedTokenizer, generation_config: GenerationConfig, example_prompt: Dict[str, torch.Tensor], device: torch.device, ): generated_input_ids = agent.actor.module.generate( input_ids=example_prompt["input_ids"].to(device), attention_mask=example_prompt["attention_mask"].to(device), generation_config=generation_config, use_cache=True, ) prompt_length = example_prompt["input_ids"].shape[1] generated_attention_mask = (generated_input_ids != generation_config.pad_token_id).int() generated_data = {"input_ids": generated_input_ids, "attention_mask": generated_attention_mask} reward = agent.reward(**generated_data)[:, prompt_length:] action_mask = (generated_input_ids != generation_config.pad_token_id).int()[:, prompt_length:] last_token_idx = torch.argmax(torch.cumsum(action_mask, dim=1) * action_mask, dim=1, keepdim=True) reward_score = torch.gather(reward, dim=-1, index=last_token_idx).squeeze(-1) return tokenizer.decode(generated_input_ids[0], skip_special_tokens=True), reward_score.item() @register_task() def main(fabric: Fabric, cfg: Dict): # noqa: D103 task_cfg = PPOConfig(**cfg.task) model_cfg = ModelConfig(**cfg.model) data_cfg = DataConfig(**cfg.data) gen_cfg = GenConfig(**cfg.generation) optim_cfg = cfg.optim fabric.seed_everything(cfg.seed + fabric.global_rank) # Create TensorBoardLogger. This will create the logger only on the # rank-0 process logger = create_tensorboard_logger(fabric, cfg, override_log_level=True) if logger and fabric.is_global_zero: fabric._loggers = [logger] fabric.logger.log_hyperparams(cfg) log_dir = get_log_dir(fabric, cfg.root_dir, cfg.run_name) experiment_dir = Path(log_dir).parent # Setup Metrics metrics = PPOMetricManager(log_interval=task_cfg.log_interval).to(fabric.device) # Setup Dataloaders data_processor = validate_dataset(fabric, data_cfg) dataset_path = Path(data_processor.full_path) tokenizer = data_processor.tokenizer collator = LeftPadCollate(pad_value=tokenizer.pad_token_id, ignore_index=data_cfg.ignore_index) train_dataset = TextDataset(dataframe_path=dataset_path / "finetune_train.pkl") train_dataloader = DataLoader( train_dataset, shuffle=True, batch_size=task_cfg.micro_batch_size, collate_fn=collator, num_workers=task_cfg.num_workers, ) train_dataloader = fabric.setup_dataloaders(train_dataloader) example_prompt = torch.load(dataset_path / "example_prompt.pt") # Setup Model with fabric.init_module(empty_init=model_cfg.fabric_empty_init): agent = PPOAgent(model_cfg=model_cfg, task_cfg=task_cfg) agent.load_checkpoint(device=fabric.device) agent.setup_finetuning() agent.actor = fabric.setup_module(agent.actor) agent.critic = fabric.setup_module(agent.critic) if not agent.share_critic_reward: agent.reward = fabric.setup_module(agent.reward) if not agent.share_actor_critic and not agent.lora_enabled: agent.reference = fabric.setup_module(agent.reference) # Setup Generation Configs generation_config = prepare_generation_config( tokenizer=tokenizer, model_cfg=model_cfg, gen_cfg=gen_cfg, fabric=fabric, ) eval_gen_cfg = copy.deepcopy(gen_cfg) eval_gen_cfg.do_sample = False eval_generation_config = prepare_generation_config( tokenizer=tokenizer, model_cfg=model_cfg, gen_cfg=eval_gen_cfg, fabric=fabric, ) # Setup Optimizer Scheduler fabric models actor_trainable_params, _, _ = prepare_optimizer_parameters(agent.actor, weight_decay=optim_cfg.weight_decay) actor_optimizer = instantiate_from_config( optim_cfg, params=actor_trainable_params, _convert_="partial", ) actor_optimizer = fabric.setup_optimizers(actor_optimizer) critic_trainable_params, _, _ = prepare_optimizer_parameters(agent.critic, weight_decay=optim_cfg.weight_decay) critic_optimizer = instantiate_from_config( optim_cfg, params=critic_trainable_params, _convert_="partial", ) critic_optimizer = fabric.setup_optimizers(critic_optimizer) if fabric.is_global_zero: gen_text, score = generate( agent=agent, tokenizer=tokenizer, generation_config=eval_generation_config, example_prompt=example_prompt, device=fabric.device, ) log_text(fabric, gen_text, "info/example_sample", step=0) fabric.log("info/example_last_reward", score, step=0) num_training_steps = 2 if cfg.dry_run else task_cfg.epochs * len(train_dataloader) # KL Controller if task_cfg.adaptive_kl_coeff: kl_controller = AdaptiveKLController( init_kl_coef=task_cfg.init_kl_coeff, target=task_cfg.target_kl_coeff, kl_horizon=num_training_steps ) else: kl_controller = FixedKLController(kl_coeff=task_cfg.init_kl_coeff) fabric.print("Model Checkpoint interval: ", task_cfg.save_interval, "steps") fabric.print("Model Evaluation interval: ", task_cfg.eval_interval, "steps") iterator = tqdm(range(num_training_steps), disable=not fabric.is_global_zero) data_iterator = iter(train_dataloader) agent.reward.eval() for k in iterator: # Setup counters and data if k % len(train_dataloader) == 0 or data_iterator is None: data_iterator = iter(train_dataloader) is_accumulating = (k) % task_cfg.gradient_accumulation_steps != 0 last_step = k == num_training_steps - 1 # Setup batch data batch = next(data_iterator) max_prompt_length = batch["prompt_input_ids"].shape[1] agent.actor.eval() agent.critic.eval() t0 = time.time() rollout, sample_output = collect_rollout( batch=batch, agent=agent, generation_config=generation_config, kl_controller=kl_controller, task_cfg=task_cfg, tokenizer=tokenizer, fabric=fabric, metrics=metrics, ) time_rollout = time.time() - t0 rollout_dataloader = DataLoader( rollout, batch_size=task_cfg.micro_batch_size, shuffle=True, collate_fn=lambda x: x ) rollout_dataloader = fabric.setup_dataloaders(rollout_dataloader, use_distributed_sampler=False) agent.actor.train() agent.critic.train() for _ in range(task_cfg.ppo_epochs): accumulator_counter = 0 for micro_batch in rollout_dataloader: is_accumulating = (accumulator_counter) % task_cfg.gradient_accumulation_steps != 0 generated_data = { "input_ids": micro_batch["input_ids"], "attention_mask": micro_batch["attention_mask"], } old_log_probs = micro_batch["actor_log_probs"] old_values = micro_batch["values"] advantages = micro_batch["advantages"] returns = micro_batch["returns"] start_token_idx = max_prompt_length - 1 action_mask = micro_batch["attention_mask"][:, start_token_idx:-1].int() if task_cfg.normalize_advantages: advantages = masked_normalize(advantages, action_mask) with fabric.no_backward_sync(agent.actor, enabled=is_accumulating): log_probs = agent.actor(**generated_data)[:, start_token_idx:] # (B, num_new_tokens) p_loss = policy_loss( log_probs=log_probs, old_log_probs=old_log_probs, advantages=advantages, clip_coeff=task_cfg.clip_coeff, action_mask=action_mask, ) fabric.backward(p_loss / task_cfg.gradient_accumulation_steps) with fabric.no_backward_sync(agent.critic, enabled=is_accumulating): values = agent.critic(**generated_data)[:, start_token_idx:-1] # (B, num_new_tokens)
v_loss = value_loss(
4
2023-10-31 12:02:02+00:00
16k
cpacker/MemGPT
tests/test_storage.py
[ { "identifier": "StorageConnector", "path": "memgpt/agent_store/storage.py", "snippet": "class StorageConnector:\n \"\"\"Defines a DB connection that is user-specific to access data: Documents, Passages, Archival/Recall Memory\"\"\"\n\n def __init__(self, table_type: TableType, config: MemGPTConfi...
import os import uuid import pytest from sqlalchemy.ext.declarative import declarative_base from memgpt.agent_store.storage import StorageConnector, TableType from memgpt.embeddings import embedding_model from memgpt.data_types import Message, Passage, EmbeddingConfig, AgentState, OpenAIEmbeddingConfig from memgpt.config import MemGPTConfig from memgpt.credentials import MemGPTCredentials from memgpt.agent_store.storage import StorageConnector, TableType from memgpt.metadata import MetadataStore from memgpt.data_types import User from datetime import datetime, timedelta
12,773
# Note: the database will filter out rows that do not correspond to agent1 and test_user by default. texts = ["This is a test passage", "This is another test passage", "Cinderella wept"] start_date = datetime(2009, 10, 5, 18, 00) dates = [start_date, start_date - timedelta(weeks=1), start_date + timedelta(weeks=1)] roles = ["user", "assistant", "assistant"] agent_1_id = uuid.uuid4() agent_2_id = uuid.uuid4() agent_ids = [agent_1_id, agent_2_id, agent_1_id] ids = [uuid.uuid4(), uuid.uuid4(), uuid.uuid4()] user_id = uuid.uuid4() # Data generation functions: Passages def generate_passages(embed_model): """Generate list of 3 Passage objects""" # embeddings: use openai if env is set, otherwise local passages = [] for text, _, _, agent_id, id in zip(texts, dates, roles, agent_ids, ids): embedding = None if embed_model: embedding = embed_model.get_text_embedding(text) passages.append(Passage(user_id=user_id, text=text, agent_id=agent_id, embedding=embedding, data_source="test_source", id=id)) return passages # Data generation functions: Messages def generate_messages(embed_model): """Generate list of 3 Message objects""" messages = [] for text, date, role, agent_id, id in zip(texts, dates, roles, agent_ids, ids): embedding = None if embed_model: embedding = embed_model.get_text_embedding(text) messages.append( Message(user_id=user_id, text=text, agent_id=agent_id, role=role, created_at=date, id=id, model="gpt-4", embedding=embedding) ) print(messages[-1].text) return messages @pytest.fixture(autouse=True) def clear_dynamically_created_models(): """Wipe globals for SQLAlchemy""" yield for key in list(globals().keys()): if key.endswith("Model"): del globals()[key] @pytest.fixture(autouse=True) def recreate_declarative_base(): """Recreate the declarative base before each test""" global Base Base = declarative_base() yield Base.metadata.clear() @pytest.mark.parametrize("storage_connector", ["postgres", "chroma", "sqlite"]) # @pytest.mark.parametrize("storage_connector", ["sqlite", "chroma"]) # @pytest.mark.parametrize("storage_connector", ["postgres"]) @pytest.mark.parametrize("table_type", [TableType.RECALL_MEMORY, TableType.ARCHIVAL_MEMORY]) def test_storage(storage_connector, table_type, clear_dynamically_created_models, recreate_declarative_base): # setup memgpt config # TODO: set env for different config path # hacky way to cleanup globals that scruw up tests # for table_name in ['Message']: # if 'Message' in globals(): # print("Removing messages", globals()['Message']) # del globals()['Message'] config = MemGPTConfig() if storage_connector == "postgres": if not os.getenv("PGVECTOR_TEST_DB_URL"): print("Skipping test, missing PG URI") return config.archival_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.recall_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.archival_storage_type = "postgres" config.recall_storage_type = "postgres" if storage_connector == "lancedb": # TODO: complete lancedb implementation if not os.getenv("LANCEDB_TEST_URL"): print("Skipping test, missing LanceDB URI") return config.archival_storage_uri = os.getenv("LANCEDB_TEST_URL") config.recall_storage_uri = os.getenv("LANCEDB_TEST_URL") config.archival_storage_type = "lancedb" config.recall_storage_type = "lancedb" if storage_connector == "chroma": if table_type == TableType.RECALL_MEMORY: print("Skipping test, chroma only supported for archival memory") return config.archival_storage_type = "chroma" config.archival_storage_path = "./test_chroma" if storage_connector == "sqlite": if table_type == TableType.ARCHIVAL_MEMORY: print("Skipping test, sqlite only supported for recall memory") return config.recall_storage_type = "sqlite" # get embedding model embed_model = None if os.getenv("OPENAI_API_KEY"):
# Note: the database will filter out rows that do not correspond to agent1 and test_user by default. texts = ["This is a test passage", "This is another test passage", "Cinderella wept"] start_date = datetime(2009, 10, 5, 18, 00) dates = [start_date, start_date - timedelta(weeks=1), start_date + timedelta(weeks=1)] roles = ["user", "assistant", "assistant"] agent_1_id = uuid.uuid4() agent_2_id = uuid.uuid4() agent_ids = [agent_1_id, agent_2_id, agent_1_id] ids = [uuid.uuid4(), uuid.uuid4(), uuid.uuid4()] user_id = uuid.uuid4() # Data generation functions: Passages def generate_passages(embed_model): """Generate list of 3 Passage objects""" # embeddings: use openai if env is set, otherwise local passages = [] for text, _, _, agent_id, id in zip(texts, dates, roles, agent_ids, ids): embedding = None if embed_model: embedding = embed_model.get_text_embedding(text) passages.append(Passage(user_id=user_id, text=text, agent_id=agent_id, embedding=embedding, data_source="test_source", id=id)) return passages # Data generation functions: Messages def generate_messages(embed_model): """Generate list of 3 Message objects""" messages = [] for text, date, role, agent_id, id in zip(texts, dates, roles, agent_ids, ids): embedding = None if embed_model: embedding = embed_model.get_text_embedding(text) messages.append( Message(user_id=user_id, text=text, agent_id=agent_id, role=role, created_at=date, id=id, model="gpt-4", embedding=embedding) ) print(messages[-1].text) return messages @pytest.fixture(autouse=True) def clear_dynamically_created_models(): """Wipe globals for SQLAlchemy""" yield for key in list(globals().keys()): if key.endswith("Model"): del globals()[key] @pytest.fixture(autouse=True) def recreate_declarative_base(): """Recreate the declarative base before each test""" global Base Base = declarative_base() yield Base.metadata.clear() @pytest.mark.parametrize("storage_connector", ["postgres", "chroma", "sqlite"]) # @pytest.mark.parametrize("storage_connector", ["sqlite", "chroma"]) # @pytest.mark.parametrize("storage_connector", ["postgres"]) @pytest.mark.parametrize("table_type", [TableType.RECALL_MEMORY, TableType.ARCHIVAL_MEMORY]) def test_storage(storage_connector, table_type, clear_dynamically_created_models, recreate_declarative_base): # setup memgpt config # TODO: set env for different config path # hacky way to cleanup globals that scruw up tests # for table_name in ['Message']: # if 'Message' in globals(): # print("Removing messages", globals()['Message']) # del globals()['Message'] config = MemGPTConfig() if storage_connector == "postgres": if not os.getenv("PGVECTOR_TEST_DB_URL"): print("Skipping test, missing PG URI") return config.archival_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.recall_storage_uri = os.getenv("PGVECTOR_TEST_DB_URL") config.archival_storage_type = "postgres" config.recall_storage_type = "postgres" if storage_connector == "lancedb": # TODO: complete lancedb implementation if not os.getenv("LANCEDB_TEST_URL"): print("Skipping test, missing LanceDB URI") return config.archival_storage_uri = os.getenv("LANCEDB_TEST_URL") config.recall_storage_uri = os.getenv("LANCEDB_TEST_URL") config.archival_storage_type = "lancedb" config.recall_storage_type = "lancedb" if storage_connector == "chroma": if table_type == TableType.RECALL_MEMORY: print("Skipping test, chroma only supported for archival memory") return config.archival_storage_type = "chroma" config.archival_storage_path = "./test_chroma" if storage_connector == "sqlite": if table_type == TableType.ARCHIVAL_MEMORY: print("Skipping test, sqlite only supported for recall memory") return config.recall_storage_type = "sqlite" # get embedding model embed_model = None if os.getenv("OPENAI_API_KEY"):
embedding_config = EmbeddingConfig(
5
2023-10-11 07:38:37+00:00
16k
xxlong0/Wonder3D
mvdiffusion/models/unet_mv2d_condition.py
[ { "identifier": "CrossAttnDownBlockMV2D", "path": "mvdiffusion/models/unet_mv2d_blocks.py", "snippet": "class CrossAttnDownBlockMV2D(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 n...
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.loaders import UNet2DConditionLoadersMixin from diffusers.utils import BaseOutput, logging from diffusers.models.activations import get_activation from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor from diffusers.models.embeddings import ( GaussianFourierProjection, ImageHintTimeEmbedding, ImageProjection, ImageTimeEmbedding, TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps, ) from diffusers.models.modeling_utils import ModelMixin, load_state_dict, _load_state_dict_into_model from diffusers.models.unet_2d_blocks import ( CrossAttnDownBlock2D, CrossAttnUpBlock2D, DownBlock2D, UNetMidBlock2DCrossAttn, UNetMidBlock2DSimpleCrossAttn, UpBlock2D, ) from diffusers.utils import ( CONFIG_NAME, DIFFUSERS_CACHE, FLAX_WEIGHTS_NAME, HF_HUB_OFFLINE, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, _add_variant, _get_model_file, deprecate, is_accelerate_available, is_safetensors_available, is_torch_version, logging, ) from diffusers import __version__ from mvdiffusion.models.unet_mv2d_blocks import ( CrossAttnDownBlockMV2D, CrossAttnUpBlockMV2D, UNetMidBlockMV2DCrossAttn, get_down_block, get_up_block, ) import os import torch import torch.nn as nn import torch.utils.checkpoint import copy
11,839
image_embed_dim=cross_attention_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type == "image_proj": # Kandinsky 2.2 self.encoder_hid_proj = ImageProjection( image_embed_dim=encoder_hid_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type is not None: raise ValueError( f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'." ) else: self.encoder_hid_proj = None # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) elif class_embed_type == "projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" ) # The projection `class_embed_type` is the same as the timestep `class_embed_type` except # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings # 2. it projects from an arbitrary input dimension. # # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. # As a result, `TimestepEmbedding` can be passed arbitrary vectors. self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif class_embed_type == "simple_projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" ) self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) else: self.class_embedding = None if addition_embed_type == "text": if encoder_hid_dim is not None: text_time_embedding_from_dim = encoder_hid_dim else: text_time_embedding_from_dim = cross_attention_dim self.add_embedding = TextTimeEmbedding( text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads ) elif addition_embed_type == "text_image": # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` self.add_embedding = TextImageTimeEmbedding( text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim ) elif addition_embed_type == "text_time": self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif addition_embed_type == "image": # Kandinsky 2.2 self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type == "image_hint": # Kandinsky 2.2 ControlNet self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type is not None: raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") if time_embedding_act_fn is None: self.time_embed_act = None else: self.time_embed_act = get_activation(time_embedding_act_fn) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): if mid_block_only_cross_attention is None: mid_block_only_cross_attention = only_cross_attention only_cross_attention = [only_cross_attention] * len(down_block_types) if mid_block_only_cross_attention is None: mid_block_only_cross_attention = False if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1
# 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 UNetMV2DConditionOutput(BaseOutput): """ The output of [`UNet2DConditionModel`]. Args: sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor = None class UNetMV2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): r""" A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented for all models (such as downloading or saving). Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): Number of channels in the output. center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample. flip_sin_to_cos (`bool`, *optional*, defaults to `False`): Whether to flip the sin to cos in the time embedding. freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`): Block type for middle of UNet, it can be either `UNetMidBlock2DCrossAttn` or `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`): The tuple of upsample blocks to use. only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`): Whether to include self-attention in the basic transformer blocks, see [`~models.attention.BasicTransformerBlock`]. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. If `None`, normalization and activation layers is skipped in post-processing. norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280): The dimension of the cross attention features. transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1): The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`], [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`]. encoder_hid_dim (`int`, *optional*, defaults to None): If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim` dimension to `cross_attention_dim`. encoder_hid_dim_type (`str`, *optional*, defaults to `None`): If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. num_attention_heads (`int`, *optional*): The number of attention heads. If not defined, defaults to `attention_head_dim` resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`. class_embed_type (`str`, *optional*, defaults to `None`): The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`, `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`. addition_embed_type (`str`, *optional*, defaults to `None`): Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or "text". "text" will use the `TextTimeEmbedding` layer. addition_time_embed_dim: (`int`, *optional*, defaults to `None`): Dimension for the timestep embeddings. num_class_embeds (`int`, *optional*, defaults to `None`): Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing class conditioning with `class_embed_type` equal to `None`. time_embedding_type (`str`, *optional*, defaults to `positional`): The type of position embedding to use for timesteps. Choose from `positional` or `fourier`. time_embedding_dim (`int`, *optional*, defaults to `None`): An optional override for the dimension of the projected time embedding. time_embedding_act_fn (`str`, *optional*, defaults to `None`): Optional activation function to use only once on the time embeddings before they are passed to the rest of the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`. timestep_post_act (`str`, *optional*, defaults to `None`): The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`. time_cond_proj_dim (`int`, *optional*, defaults to `None`): The dimension of `cond_proj` layer in the timestep embedding. conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when `class_embed_type="projection"`. class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time embeddings with the class embeddings. mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`): Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False` otherwise. """ _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] = ( "CrossAttnDownBlockMV2D", "CrossAttnDownBlockMV2D", "CrossAttnDownBlockMV2D", "DownBlock2D", ), mid_block_type: Optional[str] = "UNetMidBlockMV2DCrossAttn", up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlockMV2D", "CrossAttnUpBlockMV2D", "CrossAttnUpBlockMV2D"), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: Union[int, Tuple[int]] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: Union[int, Tuple[int]] = 1280, transformer_layers_per_block: Union[int, Tuple[int]] = 1, encoder_hid_dim: Optional[int] = None, encoder_hid_dim_type: Optional[str] = None, attention_head_dim: Union[int, Tuple[int]] = 8, num_attention_heads: Optional[Union[int, Tuple[int]]] = None, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, addition_embed_type: Optional[str] = None, addition_time_embed_dim: Optional[int] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", resnet_skip_time_act: bool = False, resnet_out_scale_factor: int = 1.0, time_embedding_type: str = "positional", time_embedding_dim: Optional[int] = None, time_embedding_act_fn: Optional[str] = None, timestep_post_act: Optional[str] = None, time_cond_proj_dim: Optional[int] = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, projection_class_embeddings_input_dim: Optional[int] = None, class_embeddings_concat: bool = False, mid_block_only_cross_attention: Optional[bool] = None, cross_attention_norm: Optional[str] = None, addition_embed_type_num_heads=64, num_views: int = 1, cd_attention_last: bool = False, cd_attention_mid: bool = False, multiview_attention: bool = True, sparse_mv_attention: bool = False, mvcd_attention: bool = False ): super().__init__() self.sample_size = sample_size if num_attention_heads is not None: raise ValueError( "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19." ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. num_attention_heads = num_attention_heads or attention_head_dim # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." ) if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types): raise ValueError( f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}." ) if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): raise ValueError( f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." ) if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}." ) if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." ) if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): raise ValueError( f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." ) # input conv_in_padding = (conv_in_kernel - 1) // 2 self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding ) # time if time_embedding_type == "fourier": time_embed_dim = time_embedding_dim or block_out_channels[0] * 2 if time_embed_dim % 2 != 0: raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.") self.time_proj = GaussianFourierProjection( time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos ) timestep_input_dim = time_embed_dim elif time_embedding_type == "positional": time_embed_dim = time_embedding_dim or block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] else: raise ValueError( f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`." ) self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, post_act_fn=timestep_post_act, cond_proj_dim=time_cond_proj_dim, ) if encoder_hid_dim_type is None and encoder_hid_dim is not None: encoder_hid_dim_type = "text_proj" self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type) logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.") if encoder_hid_dim is None and encoder_hid_dim_type is not None: raise ValueError( f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}." ) if encoder_hid_dim_type == "text_proj": self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim) elif encoder_hid_dim_type == "text_image_proj": # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)` self.encoder_hid_proj = TextImageProjection( text_embed_dim=encoder_hid_dim, image_embed_dim=cross_attention_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type == "image_proj": # Kandinsky 2.2 self.encoder_hid_proj = ImageProjection( image_embed_dim=encoder_hid_dim, cross_attention_dim=cross_attention_dim, ) elif encoder_hid_dim_type is not None: raise ValueError( f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'." ) else: self.encoder_hid_proj = None # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) elif class_embed_type == "projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set" ) # The projection `class_embed_type` is the same as the timestep `class_embed_type` except # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings # 2. it projects from an arbitrary input dimension. # # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations. # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings. # As a result, `TimestepEmbedding` can be passed arbitrary vectors. self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif class_embed_type == "simple_projection": if projection_class_embeddings_input_dim is None: raise ValueError( "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set" ) self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim) else: self.class_embedding = None if addition_embed_type == "text": if encoder_hid_dim is not None: text_time_embedding_from_dim = encoder_hid_dim else: text_time_embedding_from_dim = cross_attention_dim self.add_embedding = TextTimeEmbedding( text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads ) elif addition_embed_type == "text_image": # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)` self.add_embedding = TextImageTimeEmbedding( text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim ) elif addition_embed_type == "text_time": self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) elif addition_embed_type == "image": # Kandinsky 2.2 self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type == "image_hint": # Kandinsky 2.2 ControlNet self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim) elif addition_embed_type is not None: raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.") if time_embedding_act_fn is None: self.time_embed_act = None else: self.time_embed_act = get_activation(time_embedding_act_fn) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): if mid_block_only_cross_attention is None: mid_block_only_cross_attention = only_cross_attention only_cross_attention = [only_cross_attention] * len(down_block_types) if mid_block_only_cross_attention is None: mid_block_only_cross_attention = False if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1
down_block = get_down_block(
3
2023-10-14 12:18:38+00:00
16k
PixArt-alpha/PixArt-alpha
train_scripts/train_pixart_lcm_lora.py
[ { "identifier": "IDDPM", "path": "diffusion/iddpm.py", "snippet": "def IDDPM(\n timestep_respacing,\n noise_schedule=\"linear\",\n use_kl=False,\n sigma_small=False,\n predict_xstart=False,\n learn_sigma=True,\n pred_sigma=True,\n rescale_learned_s...
import os import sys import types import argparse import datetime import time import warnings import torch import torch.nn.functional as F import numpy as np import re import accelerate from pathlib import Path from accelerate import Accelerator, InitProcessGroupKwargs from accelerate.utils import DistributedType from torch.utils.data import RandomSampler from mmcv.runner import LogBuffer from packaging import version from diffusion import IDDPM from diffusion.utils.dist_utils import get_world_size, clip_grad_norm_ from diffusion.data.builder import build_dataset, build_dataloader, set_data_root from diffusion.utils.logger import get_root_logger from diffusion.utils.misc import set_random_seed, read_config, init_random_seed, DebugUnderflowOverflow from diffusion.utils.optimizer import build_optimizer, auto_scale_lr from diffusion.utils.lr_scheduler import build_lr_scheduler from diffusion.utils.data_sampler import AspectRatioBatchSampler, BalancedAspectRatioBatchSampler from peft import LoraConfig, get_peft_model, get_peft_model_state_dict from diffusers import AutoencoderKL, Transformer2DModel, StableDiffusionPipeline, PixArtAlphaPipeline from accelerate import FullyShardedDataParallelPlugin from torch.distributed.fsdp.fully_sharded_data_parallel import FullStateDictConfig
11,110
logger = get_root_logger(os.path.join(config.work_dir, 'train_log.log')) logger.info(accelerator.state) config.seed = init_random_seed(config.get('seed', None)) set_random_seed(config.seed) if accelerator.is_main_process: config.dump(os.path.join(config.work_dir, 'config.py')) logger.info(f"Config: \n{config.pretty_text}") logger.info(f"World_size: {get_world_size()}, seed: {config.seed}") logger.info(f"Initializing: {init_train} for training") image_size = config.image_size # @param [256, 512] latent_size = int(image_size) // 8 pred_sigma = getattr(config, 'pred_sigma', True) learn_sigma = getattr(config, 'learn_sigma', True) and pred_sigma # prepare null_embedding for training if not os.path.exists('output/pretrained_models/null_embed.pth'): logger.info(f"Creating output/pretrained_models/null_embed.pth") os.makedirs('output/pretrained_models/', exist_ok=True) pipe = PixArtAlphaPipeline.from_pretrained("PixArt-alpha/PixArt-XL-2-1024-MS", torch_dtype=torch.float16, use_safetensors=True,).to("cuda") torch.save(pipe.encode_prompt(""), 'output/pretrained_models/null_embed.pth') del pipe torch.cuda.empty_cache() # build models train_diffusion = IDDPM(str(config.train_sampling_steps), learn_sigma=learn_sigma, pred_sigma=pred_sigma, return_startx=True) model_teacher = Transformer2DModel.from_pretrained(config.load_from, subfolder="transformer") model_teacher.requires_grad_(False) model = Transformer2DModel.from_pretrained(config.load_from, subfolder="transformer").train() logger.info(f"{model.__class__.__name__} Model Parameters: {sum(p.numel() for p in model.parameters()):}") lora_config = LoraConfig( r=config.lora_rank, target_modules=[ "to_q", "to_k", "to_v", "to_out.0", "proj_in", "proj_out", "ff.net.0.proj", "ff.net.2", "proj", "linear", "linear_1", "linear_2", # "scale_shift_table", # not available due to the implementation in huggingface/peft, working on it. ], ) print(lora_config) model = get_peft_model(model, lora_config) model.print_trainable_parameters() # 9. Handle mixed precision and device placement # For mixed precision training we cast all non-trainable weigths to half-precision # as these weights are only used for inference, keeping weights in full precision is not required. weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 # 11. Enable optimizations # model.enable_xformers_memory_efficient_attention() # model_teacher.enable_xformers_memory_efficient_attention() lora_layers = filter(lambda p: p.requires_grad, model.parameters()) # for name, params in model.named_parameters(): # if params.requires_grad == False: logger.info(f"freeze param: {name}") # # for name, params in model.named_parameters(): # if params.requires_grad == True: logger.info(f"trainable param: {name}") # 10. Handle saving and loading of checkpoints # `accelerate` 0.16.0 will have better support for customized saving if version.parse(accelerate.__version__) >= version.parse("0.16.0"): # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format def save_model_hook(models, weights, output_dir): if accelerator.is_main_process: transformer_ = accelerator.unwrap_model(models[0]) lora_state_dict = get_peft_model_state_dict(transformer_, adapter_name="default") StableDiffusionPipeline.save_lora_weights(os.path.join(output_dir, "transformer_lora"), lora_state_dict) # save weights in peft format to be able to load them back transformer_.save_pretrained(output_dir) for _, model in enumerate(models): # make sure to pop weight so that corresponding model is not saved again weights.pop() def load_model_hook(models, input_dir): # load the LoRA into the model transformer_ = accelerator.unwrap_model(models[0]) transformer_.load_adapter(input_dir, "default", is_trainable=True) for _ in range(len(models)): # pop models so that they are not loaded again models.pop() accelerator.register_save_state_pre_hook(save_model_hook) accelerator.register_load_state_pre_hook(load_model_hook) if config.grad_checkpointing: model.enable_gradient_checkpointing() if not config.data.load_vae_feat: vae = AutoencoderKL.from_pretrained(config.vae_pretrained).cuda() # prepare for FSDP clip grad norm calculation if accelerator.distributed_type == DistributedType.FSDP: for m in accelerator._models: m.clip_grad_norm_ = types.MethodType(clip_grad_norm_, m) # build dataloader set_data_root(config.data_root) dataset = build_dataset(config.data, resolution=image_size, aspect_ratio_type=config.aspect_ratio_type) if config.multi_scale:
current_file_path = Path(__file__).resolve() sys.path.insert(0, str(current_file_path.parent.parent)) warnings.filterwarnings("ignore") # ignore warning def set_fsdp_env(): os.environ["ACCELERATE_USE_FSDP"] = 'true' os.environ["FSDP_AUTO_WRAP_POLICY"] = 'TRANSFORMER_BASED_WRAP' os.environ["FSDP_BACKWARD_PREFETCH"] = 'BACKWARD_PRE' os.environ["FSDP_TRANSFORMER_CLS_TO_WRAP"] = 'PixArtBlock' def filter_keys(key_set): def _f(dictionary): return {k: v for k, v in dictionary.items() if k in key_set} return _f def append_dims(x, target_dims): """Appends dimensions to the end of a tensor until it has target_dims dimensions.""" dims_to_append = target_dims - x.ndim if dims_to_append < 0: raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less") return x[(...,) + (None,) * dims_to_append] # From LCMScheduler.get_scalings_for_boundary_condition_discrete def scalings_for_boundary_conditions(timestep, sigma_data=0.5, timestep_scaling=10.0): c_skip = sigma_data**2 / ((timestep / 0.1) ** 2 + sigma_data**2) c_out = (timestep / 0.1) / ((timestep / 0.1) ** 2 + sigma_data**2) ** 0.5 return c_skip, c_out # Compare LCMScheduler.step, Step 4 def predicted_origin(model_output, timesteps, sample, prediction_type, alphas, sigmas): if prediction_type == "epsilon": sigmas = extract_into_tensor(sigmas, timesteps, sample.shape) alphas = extract_into_tensor(alphas, timesteps, sample.shape) pred_x_0 = (sample - sigmas * model_output) / alphas elif prediction_type == "v_prediction": sigmas = extract_into_tensor(sigmas, timesteps, sample.shape) alphas = extract_into_tensor(alphas, timesteps, sample.shape) pred_x_0 = alphas * sample - sigmas * model_output else: raise ValueError(f"Prediction type {prediction_type} currently not supported.") return pred_x_0 def extract_into_tensor(a, t, x_shape): b, *_ = t.shape out = a.gather(-1, t) return out.reshape(b, *((1,) * (len(x_shape) - 1))) class DDIMSolver: def __init__(self, alpha_cumprods, timesteps=1000, ddim_timesteps=50): # DDIM sampling parameters step_ratio = timesteps // ddim_timesteps self.ddim_timesteps = (np.arange(1, ddim_timesteps + 1) * step_ratio).round().astype(np.int64) - 1 self.ddim_alpha_cumprods = alpha_cumprods[self.ddim_timesteps] self.ddim_alpha_cumprods_prev = np.asarray( [alpha_cumprods[0]] + alpha_cumprods[self.ddim_timesteps[:-1]].tolist() ) # convert to torch tensors self.ddim_timesteps = torch.from_numpy(self.ddim_timesteps).long() self.ddim_alpha_cumprods = torch.from_numpy(self.ddim_alpha_cumprods) self.ddim_alpha_cumprods_prev = torch.from_numpy(self.ddim_alpha_cumprods_prev) def to(self, device): self.ddim_timesteps = self.ddim_timesteps.to(device) self.ddim_alpha_cumprods = self.ddim_alpha_cumprods.to(device) self.ddim_alpha_cumprods_prev = self.ddim_alpha_cumprods_prev.to(device) return self def ddim_step(self, pred_x0, pred_noise, timestep_index): alpha_cumprod_prev = extract_into_tensor(self.ddim_alpha_cumprods_prev, timestep_index, pred_x0.shape) dir_xt = (1.0 - alpha_cumprod_prev).sqrt() * pred_noise x_prev = alpha_cumprod_prev.sqrt() * pred_x0 + dir_xt return x_prev def train(model): if config.get('debug_nan', False): DebugUnderflowOverflow(model) logger.info('NaN debugger registered. Start to detect overflow during training.') time_start, last_tic = time.time(), time.time() log_buffer = LogBuffer() global_step = start_step load_vae_feat = getattr(train_dataloader.dataset, 'load_vae_feat', False) # Create uncond embeds for classifier free guidance uncond_prompt_embeds = torch.load('output/pretrained_models/null_embed.pth', map_location='cpu').to(accelerator.device).repeat(config.train_batch_size, 1, 1, 1) # Now you train the model for epoch in range(start_epoch + 1, config.num_epochs + 1): data_time_start= time.time() data_time_all = 0 for step, batch in enumerate(train_dataloader): data_time_all += time.time() - data_time_start if load_vae_feat: z = batch[0] else: with torch.no_grad(): with torch.cuda.amp.autocast(enabled=config.mixed_precision == 'fp16'): posterior = vae.encode(batch[0]).latent_dist if config.sample_posterior: z = posterior.sample() else: z = posterior.mode() latents = (z * config.scale_factor).to(weight_dtype) y = batch[1].squeeze(1).to(weight_dtype) y_mask = batch[2].squeeze(1).squeeze(1).to(weight_dtype) data_info = {'resolution': batch[3]['img_hw'].to(weight_dtype), 'aspect_ratio': batch[3]['aspect_ratio'].to(weight_dtype),} # Sample a random timestep for each image grad_norm = None with accelerator.accumulate(model): # Predict the noise residual optimizer.zero_grad() # Sample noise that we'll add to the latents noise = torch.randn_like(latents) bsz = latents.shape[0] # Sample a random timestep for each image t_n ~ U[0, N - k - 1] without bias. topk = config.train_sampling_steps // config.num_ddim_timesteps index = torch.randint(0, config.num_ddim_timesteps, (bsz,), device=latents.device).long() start_timesteps = solver.ddim_timesteps[index] timesteps = start_timesteps - topk timesteps = torch.where(timesteps < 0, torch.zeros_like(timesteps), timesteps) # Get boundary scalings for start_timesteps and (end) timesteps. c_skip_start, c_out_start = scalings_for_boundary_conditions(start_timesteps) c_skip_start, c_out_start = [append_dims(x, latents.ndim) for x in [c_skip_start, c_out_start]] c_skip, c_out = scalings_for_boundary_conditions(timesteps) c_skip, c_out = [append_dims(x, latents.ndim) for x in [c_skip, c_out]] # Sample a random guidance scale w from U[w_min, w_max] and embed it # w = (config.w_max - config.w_min) * torch.rand((bsz,)) + config.w_min w = config.cfg_scale * torch.ones((bsz,)) w = w.reshape(bsz, 1, 1, 1) w = w.to(device=latents.device, dtype=latents.dtype) # Get online LCM prediction on z_{t_{n + k}}, w, c, t_{n + k} _, pred_x_0, noisy_model_input = train_diffusion.training_losses_diffusers( model, latents, start_timesteps, model_kwargs=dict(encoder_hidden_states=y, encoder_attention_mask=y_mask, added_cond_kwargs=data_info), noise=noise ) model_pred = c_skip_start * noisy_model_input + c_out_start * pred_x_0 with torch.no_grad(): with torch.autocast("cuda"): cond_teacher_output, cond_pred_x0, _ = train_diffusion.training_losses_diffusers( model_teacher, latents, start_timesteps, model_kwargs=dict(encoder_hidden_states=y, encoder_attention_mask=y_mask, added_cond_kwargs=data_info), noise=noise ) # Get teacher model prediction on noisy_latents and unconditional embedding uncond_teacher_output, uncond_pred_x0, _ = train_diffusion.training_losses_diffusers( model_teacher, latents, start_timesteps, model_kwargs=dict(encoder_hidden_states=uncond_prompt_embeds, encoder_attention_mask=y_mask, added_cond_kwargs=data_info), noise=noise ) # Perform "CFG" to get x_prev estimate (using the LCM paper's CFG formulation) pred_x0 = cond_pred_x0 + w * (cond_pred_x0 - uncond_pred_x0) pred_noise = cond_teacher_output + w * (cond_teacher_output - uncond_teacher_output) x_prev = solver.ddim_step(pred_x0, pred_noise, index) # Get target LCM prediction on x_prev, w, c, t_n with torch.no_grad(): with torch.autocast("cuda", enabled=True): _, pred_x_0, _ = train_diffusion.training_losses_diffusers( model, x_prev.float(), timesteps, model_kwargs=dict(encoder_hidden_states=y, encoder_attention_mask=y_mask, added_cond_kwargs=data_info), skip_noise=True ) target = c_skip * x_prev + c_out * pred_x_0 # Calculate loss if config.loss_type == "l2": loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean") elif config.loss_type == "huber": loss = torch.mean(torch.sqrt((model_pred.float() - target.float()) ** 2 + config.huber_c**2) - config.huber_c) accelerator.backward(loss) if accelerator.sync_gradients: grad_norm = accelerator.clip_grad_norm_(model.parameters(), config.gradient_clip) optimizer.step() lr_scheduler.step() optimizer.zero_grad(set_to_none=True) lr = lr_scheduler.get_last_lr()[0] logs = {"loss": accelerator.gather(loss).mean().item()} if grad_norm is not None: logs.update(grad_norm=accelerator.gather(grad_norm).mean().item()) log_buffer.update(logs) if (step + 1) % config.log_interval == 0 or (step + 1) == 1: t = (time.time() - last_tic) / config.log_interval t_d = data_time_all / config.log_interval avg_time = (time.time() - time_start) / (global_step + 1) eta = str(datetime.timedelta(seconds=int(avg_time * (total_steps - start_step - global_step - 1)))) eta_epoch = str(datetime.timedelta(seconds=int(avg_time * (len(train_dataloader) - step - 1)))) # avg_loss = sum(loss_buffer) / len(loss_buffer) log_buffer.average() info = f"Step/Epoch [{(epoch-1)*len(train_dataloader)+step+1}/{epoch}][{step + 1}/{len(train_dataloader)}]:total_eta: {eta}, " \ f"epoch_eta:{eta_epoch}, time_all:{t:.3f}, time_data:{t_d:.3f}, lr:{lr:.3e}, s:({data_info['resolution'][0][0].item()}, {data_info['resolution'][0][1].item()}), " info += ', '.join([f"{k}:{v:.4f}" for k, v in log_buffer.output.items()]) logger.info(info) last_tic = time.time() log_buffer.clear() data_time_all = 0 logs.update(lr=lr) accelerator.log(logs, step=global_step + start_step) global_step += 1 data_time_start= time.time() accelerator.wait_for_everyone() if accelerator.is_main_process: if ((epoch - 1) * len(train_dataloader) + step + 1) % config.save_model_steps == 0: save_path = os.path.join(os.path.join(config.work_dir, 'checkpoints'), f"checkpoint-{(epoch - 1) * len(train_dataloader) + step + 1}") os.umask(0o000) logger.info(f"Start to save state to {save_path}") accelerator.save_state(save_path) logger.info(f"Saved state to {save_path}") accelerator.wait_for_everyone() if epoch % config.save_model_epochs == 0 or epoch == config.num_epochs: os.umask(0o000) save_path = os.path.join(os.path.join(config.work_dir, 'checkpoints'), f"checkpoint-{(epoch - 1) * len(train_dataloader) + step + 1}") logger.info(f"Start to save state to {save_path}") model = accelerator.unwrap_model(model) model.save_pretrained(save_path) lora_state_dict = get_peft_model_state_dict(model, adapter_name="default") StableDiffusionPipeline.save_lora_weights(os.path.join(save_path, "transformer_lora"), lora_state_dict) logger.info(f"Saved state to {save_path}") def parse_args(): parser = argparse.ArgumentParser(description="Process some integers.") parser.add_argument("config", type=str, help="config") parser.add_argument("--cloud", action='store_true', default=False, help="cloud or local machine") parser.add_argument("--work-dir", default='output', help='the dir to save logs and models') parser.add_argument("--resume-from", help='the dir to save logs and models') parser.add_argument("--local-rank", type=int, default=-1) parser.add_argument("--local_rank", type=int, default=-1) parser.add_argument("--debug", action='store_true') parser.add_argument("--lora_rank", type=int, default=64, help="The rank of the LoRA projection matrix.", ) args = parser.parse_args() return args if __name__ == '__main__': args = parse_args() config = read_config(args.config) config.resume_from = None if args.work_dir is not None: # update configs according to CLI args if args.work_dir is not None config.work_dir = args.work_dir if args.cloud: config.data_root = '/data/data' if args.resume_from is not None: config.resume_from = args.resume_from if args.debug: config.log_interval = 1 config.train_batch_size = 4 config.valid_num = 10 config.save_model_steps = 10 os.umask(0o000) os.makedirs(config.work_dir, exist_ok=True) init_handler = InitProcessGroupKwargs() init_handler.timeout = datetime.timedelta(seconds=5400) # change timeout to avoid a strange NCCL bug # Initialize accelerator and tensorboard logging if config.use_fsdp: init_train = 'FSDP' set_fsdp_env() fsdp_plugin = FullyShardedDataParallelPlugin(state_dict_config=FullStateDictConfig(offload_to_cpu=False, rank0_only=False),) else: init_train = 'DDP' fsdp_plugin = None even_batches = True if config.multi_scale: even_batches=False, accelerator = Accelerator( mixed_precision=config.mixed_precision, gradient_accumulation_steps=config.gradient_accumulation_steps, log_with="tensorboard", project_dir=os.path.join(config.work_dir, "logs"), fsdp_plugin=fsdp_plugin, even_batches=even_batches, kwargs_handlers=[init_handler] ) logger = get_root_logger(os.path.join(config.work_dir, 'train_log.log')) logger.info(accelerator.state) config.seed = init_random_seed(config.get('seed', None)) set_random_seed(config.seed) if accelerator.is_main_process: config.dump(os.path.join(config.work_dir, 'config.py')) logger.info(f"Config: \n{config.pretty_text}") logger.info(f"World_size: {get_world_size()}, seed: {config.seed}") logger.info(f"Initializing: {init_train} for training") image_size = config.image_size # @param [256, 512] latent_size = int(image_size) // 8 pred_sigma = getattr(config, 'pred_sigma', True) learn_sigma = getattr(config, 'learn_sigma', True) and pred_sigma # prepare null_embedding for training if not os.path.exists('output/pretrained_models/null_embed.pth'): logger.info(f"Creating output/pretrained_models/null_embed.pth") os.makedirs('output/pretrained_models/', exist_ok=True) pipe = PixArtAlphaPipeline.from_pretrained("PixArt-alpha/PixArt-XL-2-1024-MS", torch_dtype=torch.float16, use_safetensors=True,).to("cuda") torch.save(pipe.encode_prompt(""), 'output/pretrained_models/null_embed.pth') del pipe torch.cuda.empty_cache() # build models train_diffusion = IDDPM(str(config.train_sampling_steps), learn_sigma=learn_sigma, pred_sigma=pred_sigma, return_startx=True) model_teacher = Transformer2DModel.from_pretrained(config.load_from, subfolder="transformer") model_teacher.requires_grad_(False) model = Transformer2DModel.from_pretrained(config.load_from, subfolder="transformer").train() logger.info(f"{model.__class__.__name__} Model Parameters: {sum(p.numel() for p in model.parameters()):}") lora_config = LoraConfig( r=config.lora_rank, target_modules=[ "to_q", "to_k", "to_v", "to_out.0", "proj_in", "proj_out", "ff.net.0.proj", "ff.net.2", "proj", "linear", "linear_1", "linear_2", # "scale_shift_table", # not available due to the implementation in huggingface/peft, working on it. ], ) print(lora_config) model = get_peft_model(model, lora_config) model.print_trainable_parameters() # 9. Handle mixed precision and device placement # For mixed precision training we cast all non-trainable weigths to half-precision # as these weights are only used for inference, keeping weights in full precision is not required. weight_dtype = torch.float32 if accelerator.mixed_precision == "fp16": weight_dtype = torch.float16 elif accelerator.mixed_precision == "bf16": weight_dtype = torch.bfloat16 # 11. Enable optimizations # model.enable_xformers_memory_efficient_attention() # model_teacher.enable_xformers_memory_efficient_attention() lora_layers = filter(lambda p: p.requires_grad, model.parameters()) # for name, params in model.named_parameters(): # if params.requires_grad == False: logger.info(f"freeze param: {name}") # # for name, params in model.named_parameters(): # if params.requires_grad == True: logger.info(f"trainable param: {name}") # 10. Handle saving and loading of checkpoints # `accelerate` 0.16.0 will have better support for customized saving if version.parse(accelerate.__version__) >= version.parse("0.16.0"): # create custom saving & loading hooks so that `accelerator.save_state(...)` serializes in a nice format def save_model_hook(models, weights, output_dir): if accelerator.is_main_process: transformer_ = accelerator.unwrap_model(models[0]) lora_state_dict = get_peft_model_state_dict(transformer_, adapter_name="default") StableDiffusionPipeline.save_lora_weights(os.path.join(output_dir, "transformer_lora"), lora_state_dict) # save weights in peft format to be able to load them back transformer_.save_pretrained(output_dir) for _, model in enumerate(models): # make sure to pop weight so that corresponding model is not saved again weights.pop() def load_model_hook(models, input_dir): # load the LoRA into the model transformer_ = accelerator.unwrap_model(models[0]) transformer_.load_adapter(input_dir, "default", is_trainable=True) for _ in range(len(models)): # pop models so that they are not loaded again models.pop() accelerator.register_save_state_pre_hook(save_model_hook) accelerator.register_load_state_pre_hook(load_model_hook) if config.grad_checkpointing: model.enable_gradient_checkpointing() if not config.data.load_vae_feat: vae = AutoencoderKL.from_pretrained(config.vae_pretrained).cuda() # prepare for FSDP clip grad norm calculation if accelerator.distributed_type == DistributedType.FSDP: for m in accelerator._models: m.clip_grad_norm_ = types.MethodType(clip_grad_norm_, m) # build dataloader set_data_root(config.data_root) dataset = build_dataset(config.data, resolution=image_size, aspect_ratio_type=config.aspect_ratio_type) if config.multi_scale:
batch_sampler = AspectRatioBatchSampler(sampler=RandomSampler(dataset), dataset=dataset,
14
2023-10-12 14:16:33+00:00
16k
showlab/MotionDirector
MotionDirector_train.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 argparse import datetime import logging import inspect import math import os import random import gc import copy import torch import torch.nn.functional as F import torch.utils.checkpoint import diffusers import transformers import imageio import numpy as np import itertools import bitsandbytes as bnb from typing import Dict, Optional, Tuple from omegaconf import OmegaConf from torchvision import transforms from tqdm.auto import tqdm from accelerate import Accelerator from accelerate.logging import get_logger from accelerate.utils import set_seed from models.unet_3d_condition import UNet3DConditionModel from diffusers.models import AutoencoderKL from diffusers import DDIMScheduler, TextToVideoSDPipeline from diffusers.optimization import get_scheduler from diffusers.utils.import_utils import is_xformers_available from diffusers.models.attention_processor import AttnProcessor2_0, Attention from diffusers.models.attention import BasicTransformerBlock from transformers import CLIPTextModel, CLIPTokenizer from transformers.models.clip.modeling_clip import CLIPEncoder from utils.dataset import VideoJsonDataset, SingleVideoDataset, \ ImageDataset, VideoFolderDataset, CachedDataset from einops import rearrange, repeat from utils.lora_handler import LoraHandler from utils.lora import extract_lora_child_module from utils.ddim_utils import ddim_inversion from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
11,326
already_printed_trainables = False logger = get_logger(__name__, log_level="INFO") def create_logging(logging, logger, accelerator): 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) def accelerate_set_verbose(accelerator): if accelerator.is_local_main_process: transformers.utils.logging.set_verbosity_warning() diffusers.utils.logging.set_verbosity_info() else: transformers.utils.logging.set_verbosity_error() diffusers.utils.logging.set_verbosity_error() def get_train_dataset(dataset_types, train_data, tokenizer): train_datasets = [] # Loop through all available datasets, get the name, then add to list of data to process.
already_printed_trainables = False logger = get_logger(__name__, log_level="INFO") def create_logging(logging, logger, accelerator): 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) def accelerate_set_verbose(accelerator): if accelerator.is_local_main_process: transformers.utils.logging.set_verbosity_warning() diffusers.utils.logging.set_verbosity_info() else: transformers.utils.logging.set_verbosity_error() diffusers.utils.logging.set_verbosity_error() def get_train_dataset(dataset_types, train_data, tokenizer): train_datasets = [] # Loop through all available datasets, get the name, then add to list of data to process.
for DataSet in [VideoJsonDataset, SingleVideoDataset, ImageDataset, VideoFolderDataset]:
1
2023-10-12 12:06:55+00:00
16k
NVlabs/EmerNeRF
datasets/base/split_wrapper.py
[ { "identifier": "SceneLidarSource", "path": "datasets/base/lidar_source.py", "snippet": "class SceneLidarSource(abc.ABC):\n \"\"\"\n The base class for the lidar source of a scene.\n \"\"\"\n\n data_cfg: OmegaConf = None\n # the normalized timestamps of all points (normalized to [0, 1]), ...
from typing import List, Union from .lidar_source import SceneLidarSource from .pixel_source import ScenePixelSource import torch import torch.nn.functional as F
12,378
class SplitWrapper(torch.utils.data.Dataset): # a sufficiently large number to make sure we don't run out of data _num_iters = 1000000 def __init__( self,
class SplitWrapper(torch.utils.data.Dataset): # a sufficiently large number to make sure we don't run out of data _num_iters = 1000000 def __init__( self,
datasource: Union[ScenePixelSource, SceneLidarSource],
1
2023-10-11 20:56:27+00:00
16k
alibaba-damo-academy/FunCodec
funcodec/models/decoder/contextual_decoder.py
[ { "identifier": "utils", "path": "funcodec/modules/streaming_utils/utils.py", "snippet": "def sequence_mask(lengths, maxlen=None, dtype=torch.float32, device=None):\ndef apply_cmvn(inputs, mvn):\ndef drop_and_add(inputs: torch.Tensor,\n outputs: torch.Tensor,\n training: ...
from typing import List from typing import Tuple from funcodec.modules.streaming_utils import utils as myutils from funcodec.models.decoder.transformer_decoder import BaseTransformerDecoder from typeguard import check_argument_types from funcodec.modules.attention import MultiHeadedAttentionSANMDecoder, MultiHeadedAttentionCrossAtt from funcodec.modules.embedding import PositionalEncoding from funcodec.modules.layer_norm import LayerNorm from funcodec.modules.positionwise_feed_forward import PositionwiseFeedForwardDecoderSANM from funcodec.modules.repeat import repeat from funcodec.models.decoder.sanm_decoder import DecoderLayerSANM, ParaformerSANMDecoder import logging import torch import torch.nn as nn import numpy as np
13,827
class ContextualDecoderLayer(nn.Module): def __init__( self, size, self_attn, src_attn, feed_forward, dropout_rate, normalize_before=True, concat_after=False, ): """Construct an DecoderLayer object.""" super(ContextualDecoderLayer, self).__init__() self.size = size self.self_attn = self_attn self.src_attn = src_attn self.feed_forward = feed_forward
class ContextualDecoderLayer(nn.Module): def __init__( self, size, self_attn, src_attn, feed_forward, dropout_rate, normalize_before=True, concat_after=False, ): """Construct an DecoderLayer object.""" super(ContextualDecoderLayer, self).__init__() self.size = size self.self_attn = self_attn self.src_attn = src_attn self.feed_forward = feed_forward
self.norm1 = LayerNorm(size)
5
2023-10-07 02:00:40+00:00
16k
longzw1997/Open-GroundingDino
models/GroundingDINO/groundingdino.py
[ { "identifier": "box_ops", "path": "groundingdino/util/box_ops.py", "snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef box_iou_pairwise(boxes1, boxes2):\ndef generalized_box_iou_pairwise(boxes1, boxes2):\ndef ma...
import copy import torch import torch.nn.functional as F from typing import List from torch import nn from torchvision.ops.boxes import nms from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast from groundingdino.util import box_ops, get_tokenlizer from groundingdino.util.misc import ( NestedTensor, accuracy, get_world_size, interpolate, inverse_sigmoid, is_dist_avail_and_initialized, nested_tensor_from_tensor_list, ) from groundingdino.util.utils import get_phrases_from_posmap from groundingdino.util.visualizer import COCOVisualizer from groundingdino.util.vl_utils import create_positive_map_from_span from ..registry import MODULE_BUILD_FUNCS from .backbone import build_backbone from .bertwarper import ( BertModelWarper, generate_masks_with_special_tokens, generate_masks_with_special_tokens_and_transfer_map, ) from .transformer import build_transformer from .utils import MLP, ContrastiveEmbed, sigmoid_focal_loss from .matcher import build_matcher from pycocotools.coco import COCO
12,492
two_stage_type ) if two_stage_type != "no": if two_stage_bbox_embed_share: assert dec_pred_bbox_embed_share self.transformer.enc_out_bbox_embed = _bbox_embed else: self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed) if two_stage_class_embed_share: assert dec_pred_bbox_embed_share self.transformer.enc_out_class_embed = _class_embed else: self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed) self.refpoint_embed = None self._reset_parameters() def _reset_parameters(self): # init input_proj for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) def init_ref_points(self, use_num_queries): self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim) def forward(self, samples: NestedTensor, targets: List = None, **kw): """The forward expects a NestedTensor, which consists of: - samples.tensor: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x num_classes] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if targets is None: captions = kw["captions"] else: captions = [t["caption"] for t in targets] # encoder texts tokenized = self.tokenizer(captions, padding="longest", return_tensors="pt").to( samples.device ) one_hot_token = tokenized ( text_self_attention_masks, position_ids, cate_to_token_mask_list, ) = generate_masks_with_special_tokens_and_transfer_map( tokenized, self.specical_tokens, self.tokenizer ) if text_self_attention_masks.shape[1] > self.max_text_len: text_self_attention_masks = text_self_attention_masks[ :, : self.max_text_len, : self.max_text_len ] position_ids = position_ids[:, : self.max_text_len] tokenized["input_ids"] = tokenized["input_ids"][:, : self.max_text_len] tokenized["attention_mask"] = tokenized["attention_mask"][:, : self.max_text_len] tokenized["token_type_ids"] = tokenized["token_type_ids"][:, : self.max_text_len] # extract text embeddings if self.sub_sentence_present: tokenized_for_encoder = {k: v for k, v in tokenized.items() if k != "attention_mask"} tokenized_for_encoder["attention_mask"] = text_self_attention_masks tokenized_for_encoder["position_ids"] = position_ids else: tokenized_for_encoder = tokenized bert_output = self.bert(**tokenized_for_encoder) # bs, 195, 768 encoded_text = self.feat_map(bert_output["last_hidden_state"]) # bs, 195, d_model text_token_mask = tokenized.attention_mask.bool() # bs, 195 # text_token_mask: True for nomask, False for mask # text_self_attention_masks: True for nomask, False for mask if encoded_text.shape[1] > self.max_text_len: encoded_text = encoded_text[:, : self.max_text_len, :] text_token_mask = text_token_mask[:, : self.max_text_len] position_ids = position_ids[:, : self.max_text_len] text_self_attention_masks = text_self_attention_masks[ :, : self.max_text_len, : self.max_text_len ] text_dict = { "encoded_text": encoded_text, # bs, 195, d_model "text_token_mask": text_token_mask, # bs, 195 "position_ids": position_ids, # bs, 195 "text_self_attention_masks": text_self_attention_masks, # bs, 195,195 } if isinstance(samples, (list, torch.Tensor)): samples = nested_tensor_from_tensor_list(samples) features, poss = self.backbone(samples) srcs = [] masks = [] for l, feat in enumerate(features): src, mask = feat.decompose() srcs.append(self.input_proj[l](src)) masks.append(mask) assert mask is not None if self.num_feature_levels > len(srcs): _len_srcs = len(srcs) for l in range(_len_srcs, self.num_feature_levels): if l == _len_srcs: src = self.input_proj[l](features[-1].tensors) else: src = self.input_proj[l](srcs[-1]) m = samples.mask
# ------------------------------------------------------------------------ # Grounding DINO # url: https://github.com/IDEA-Research/GroundingDINO # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR model and criterion classes. # Copyright (c) 2021 Microsoft. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ class GroundingDINO(nn.Module): """This is the Cross-Attention Detector module that performs object detection""" def __init__( self, backbone, transformer, num_queries, aux_loss=False, iter_update=False, query_dim=2, num_feature_levels=1, nheads=8, # two stage two_stage_type="no", # ['no', 'standard'] dec_pred_bbox_embed_share=True, two_stage_class_embed_share=True, two_stage_bbox_embed_share=True, num_patterns=0, dn_number=100, dn_box_noise_scale=0.4, dn_label_noise_ratio=0.5, dn_labelbook_size=100, text_encoder_type="bert-base-uncased", sub_sentence_present=True, max_text_len=256, ): """Initializes the model. Parameters: backbone: torch module of the backbone to be used. See backbone.py transformer: torch module of the transformer architecture. See transformer.py num_queries: number of object queries, ie detection slot. This is the maximal number of objects Conditional DETR can detect in a single image. For COCO, we recommend 100 queries. aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used. """ super().__init__() self.num_queries = num_queries self.transformer = transformer self.hidden_dim = hidden_dim = transformer.d_model self.num_feature_levels = num_feature_levels self.nheads = nheads self.max_text_len = 256 self.sub_sentence_present = sub_sentence_present # setting query dim self.query_dim = query_dim assert query_dim == 4 # for dn training self.num_patterns = num_patterns self.dn_number = dn_number self.dn_box_noise_scale = dn_box_noise_scale self.dn_label_noise_ratio = dn_label_noise_ratio self.dn_labelbook_size = dn_labelbook_size # bert self.tokenizer = get_tokenlizer.get_tokenlizer(text_encoder_type) self.bert = get_tokenlizer.get_pretrained_language_model(text_encoder_type) self.bert.pooler.dense.weight.requires_grad_(False) self.bert.pooler.dense.bias.requires_grad_(False) self.bert = BertModelWarper(bert_model=self.bert) self.feat_map = nn.Linear(self.bert.config.hidden_size, self.hidden_dim, bias=True) nn.init.constant_(self.feat_map.bias.data, 0) nn.init.xavier_uniform_(self.feat_map.weight.data) # freeze # special tokens self.specical_tokens = self.tokenizer.convert_tokens_to_ids(["[CLS]", "[SEP]", ".", "?"]) # prepare input projection layers if num_feature_levels > 1: num_backbone_outs = len(backbone.num_channels) input_proj_list = [] for _ in range(num_backbone_outs): in_channels = backbone.num_channels[_] input_proj_list.append( nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), ) ) for _ in range(num_feature_levels - num_backbone_outs): input_proj_list.append( nn.Sequential( nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1), nn.GroupNorm(32, hidden_dim), ) ) in_channels = hidden_dim self.input_proj = nn.ModuleList(input_proj_list) else: assert two_stage_type == "no", "two_stage_type should be no if num_feature_levels=1 !!!" self.input_proj = nn.ModuleList( [ nn.Sequential( nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1), nn.GroupNorm(32, hidden_dim), ) ] ) self.backbone = backbone self.aux_loss = aux_loss self.box_pred_damping = box_pred_damping = None self.iter_update = iter_update assert iter_update, "Why not iter_update?" # prepare pred layers self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share # prepare class & box embed _class_embed = ContrastiveEmbed() _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) if dec_pred_bbox_embed_share: box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)] else: box_embed_layerlist = [ copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers) ] class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)] self.bbox_embed = nn.ModuleList(box_embed_layerlist) self.class_embed = nn.ModuleList(class_embed_layerlist) self.transformer.decoder.bbox_embed = self.bbox_embed self.transformer.decoder.class_embed = self.class_embed # two stage self.two_stage_type = two_stage_type assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format( two_stage_type ) if two_stage_type != "no": if two_stage_bbox_embed_share: assert dec_pred_bbox_embed_share self.transformer.enc_out_bbox_embed = _bbox_embed else: self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed) if two_stage_class_embed_share: assert dec_pred_bbox_embed_share self.transformer.enc_out_class_embed = _class_embed else: self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed) self.refpoint_embed = None self._reset_parameters() def _reset_parameters(self): # init input_proj for proj in self.input_proj: nn.init.xavier_uniform_(proj[0].weight, gain=1) nn.init.constant_(proj[0].bias, 0) def init_ref_points(self, use_num_queries): self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim) def forward(self, samples: NestedTensor, targets: List = None, **kw): """The forward expects a NestedTensor, which consists of: - samples.tensor: batched images, of shape [batch_size x 3 x H x W] - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels It returns a dict with the following elements: - "pred_logits": the classification logits (including no-object) for all queries. Shape= [batch_size x num_queries x num_classes] - "pred_boxes": The normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These values are normalized in [0, 1], relative to the size of each individual image (disregarding possible padding). See PostProcess for information on how to retrieve the unnormalized bounding box. - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of dictionnaries containing the two above keys for each decoder layer. """ if targets is None: captions = kw["captions"] else: captions = [t["caption"] for t in targets] # encoder texts tokenized = self.tokenizer(captions, padding="longest", return_tensors="pt").to( samples.device ) one_hot_token = tokenized ( text_self_attention_masks, position_ids, cate_to_token_mask_list, ) = generate_masks_with_special_tokens_and_transfer_map( tokenized, self.specical_tokens, self.tokenizer ) if text_self_attention_masks.shape[1] > self.max_text_len: text_self_attention_masks = text_self_attention_masks[ :, : self.max_text_len, : self.max_text_len ] position_ids = position_ids[:, : self.max_text_len] tokenized["input_ids"] = tokenized["input_ids"][:, : self.max_text_len] tokenized["attention_mask"] = tokenized["attention_mask"][:, : self.max_text_len] tokenized["token_type_ids"] = tokenized["token_type_ids"][:, : self.max_text_len] # extract text embeddings if self.sub_sentence_present: tokenized_for_encoder = {k: v for k, v in tokenized.items() if k != "attention_mask"} tokenized_for_encoder["attention_mask"] = text_self_attention_masks tokenized_for_encoder["position_ids"] = position_ids else: tokenized_for_encoder = tokenized bert_output = self.bert(**tokenized_for_encoder) # bs, 195, 768 encoded_text = self.feat_map(bert_output["last_hidden_state"]) # bs, 195, d_model text_token_mask = tokenized.attention_mask.bool() # bs, 195 # text_token_mask: True for nomask, False for mask # text_self_attention_masks: True for nomask, False for mask if encoded_text.shape[1] > self.max_text_len: encoded_text = encoded_text[:, : self.max_text_len, :] text_token_mask = text_token_mask[:, : self.max_text_len] position_ids = position_ids[:, : self.max_text_len] text_self_attention_masks = text_self_attention_masks[ :, : self.max_text_len, : self.max_text_len ] text_dict = { "encoded_text": encoded_text, # bs, 195, d_model "text_token_mask": text_token_mask, # bs, 195 "position_ids": position_ids, # bs, 195 "text_self_attention_masks": text_self_attention_masks, # bs, 195,195 } if isinstance(samples, (list, torch.Tensor)): samples = nested_tensor_from_tensor_list(samples) features, poss = self.backbone(samples) srcs = [] masks = [] for l, feat in enumerate(features): src, mask = feat.decompose() srcs.append(self.input_proj[l](src)) masks.append(mask) assert mask is not None if self.num_feature_levels > len(srcs): _len_srcs = len(srcs) for l in range(_len_srcs, self.num_feature_levels): if l == _len_srcs: src = self.input_proj[l](features[-1].tensors) else: src = self.input_proj[l](srcs[-1]) m = samples.mask
mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]
5
2023-10-14 02:20:31+00:00
16k
Beckschen/3D-TransUNet
nn_transunet/trainer/network_trainer.py
[ { "identifier": "SegmentationNetwork", "path": "nn_transunet/networks/neural_network.py", "snippet": "class SegmentationNetwork(NeuralNetwork):\n def __init__(self):\n super(NeuralNetwork, self).__init__()\n\n # if we have 5 pooling then our patch size must be divisible by 2**5\n ...
from _warnings import warn from typing import Tuple from batchgenerators.utilities.file_and_folder_operations import * from nn_transunet.networks.neural_network import SegmentationNetwork from sklearn.model_selection import KFold from torch import nn from torch.cuda.amp import GradScaler, autocast from torch.optim.lr_scheduler import _LRScheduler from ..trainer.loss_functions import ModelLossSemsegGatedCRF from time import time, sleep from collections import OrderedDict from abc import abstractmethod from datetime import datetime from tqdm import trange from ..utils.dist_utils import check_call_hdfs_command, mkdir_hdfs import matplotlib import numpy as np import matplotlib.pyplot as plt import sys import torch.backends.cudnn as cudnn import torch import math import matplotlib.pyplot as plt
13,783
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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. matplotlib.use("agg") def maybe_to_torch(d): if isinstance(d, list): d = [maybe_to_torch(i) if not isinstance(i, torch.Tensor) else i for i in d] elif not isinstance(d, torch.Tensor): d = torch.from_numpy(d).float() return d def poly_lr(epoch, max_epochs, initial_lr, exponent=0.9): return initial_lr * (1 - epoch / max_epochs) ** exponent def warmup_poly_lr(epoch, max_epochs, warmup_epochs, initial_lr, exponent=0.9): if epoch < warmup_epochs: return initial_lr * (float(epoch) / float(max(1.0, warmup_epochs))) epoch_rel = epoch - warmup_epochs max_epochs_rel = max_epochs - warmup_epochs return initial_lr * (1 - epoch_rel / max_epochs_rel) ** exponent def to_cuda(data, non_blocking=True, gpu_id=0): if isinstance(data, list): data = [i.cuda(gpu_id, non_blocking=non_blocking) for i in data] else: data = data.cuda(gpu_id, non_blocking=non_blocking) return data class NetworkTrainer(object): def __init__(self, deterministic=True, fp16=False): """ A generic class that can train almost any neural network (RNNs excluded). It provides basic functionality such as the training loop, tracking of training and validation losses (and the target metric if you implement it) Training can be terminated early if the validation loss (or the target metric if implemented) do not improve anymore. This is based on a moving average (MA) of the loss/metric instead of the raw values to get more smooth results. What you need to override: - __init__ - initialize - run_online_evaluation (optional) - finish_online_evaluation (optional) - validate - predict_test_case """ self.fp16 = fp16 self.amp_grad_scaler = None if deterministic: np.random.seed(12345) torch.manual_seed(12345) if torch.cuda.is_available(): torch.cuda.manual_seed_all(12345) cudnn.deterministic = True torch.backends.cudnn.benchmark = False else: cudnn.deterministic = False torch.backends.cudnn.benchmark = True ################# SET THESE IN self.initialize() ################################### self.network: Tuple[SegmentationNetwork, nn.DataParallel] = None self.optimizer = None self.lr_scheduler = None self.tr_gen = self.val_gen = None self.was_initialized = False self.initial_lr = 1e-2 ################# SET THESE IN INIT ################################################ self.output_folder = None self.fold = None # self.loss = PartiallyCrossEntropyLoss() self.loss = None
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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. matplotlib.use("agg") def maybe_to_torch(d): if isinstance(d, list): d = [maybe_to_torch(i) if not isinstance(i, torch.Tensor) else i for i in d] elif not isinstance(d, torch.Tensor): d = torch.from_numpy(d).float() return d def poly_lr(epoch, max_epochs, initial_lr, exponent=0.9): return initial_lr * (1 - epoch / max_epochs) ** exponent def warmup_poly_lr(epoch, max_epochs, warmup_epochs, initial_lr, exponent=0.9): if epoch < warmup_epochs: return initial_lr * (float(epoch) / float(max(1.0, warmup_epochs))) epoch_rel = epoch - warmup_epochs max_epochs_rel = max_epochs - warmup_epochs return initial_lr * (1 - epoch_rel / max_epochs_rel) ** exponent def to_cuda(data, non_blocking=True, gpu_id=0): if isinstance(data, list): data = [i.cuda(gpu_id, non_blocking=non_blocking) for i in data] else: data = data.cuda(gpu_id, non_blocking=non_blocking) return data class NetworkTrainer(object): def __init__(self, deterministic=True, fp16=False): """ A generic class that can train almost any neural network (RNNs excluded). It provides basic functionality such as the training loop, tracking of training and validation losses (and the target metric if you implement it) Training can be terminated early if the validation loss (or the target metric if implemented) do not improve anymore. This is based on a moving average (MA) of the loss/metric instead of the raw values to get more smooth results. What you need to override: - __init__ - initialize - run_online_evaluation (optional) - finish_online_evaluation (optional) - validate - predict_test_case """ self.fp16 = fp16 self.amp_grad_scaler = None if deterministic: np.random.seed(12345) torch.manual_seed(12345) if torch.cuda.is_available(): torch.cuda.manual_seed_all(12345) cudnn.deterministic = True torch.backends.cudnn.benchmark = False else: cudnn.deterministic = False torch.backends.cudnn.benchmark = True ################# SET THESE IN self.initialize() ################################### self.network: Tuple[SegmentationNetwork, nn.DataParallel] = None self.optimizer = None self.lr_scheduler = None self.tr_gen = self.val_gen = None self.was_initialized = False self.initial_lr = 1e-2 ################# SET THESE IN INIT ################################################ self.output_folder = None self.fold = None # self.loss = PartiallyCrossEntropyLoss() self.loss = None
self.gatecrfloss = ModelLossSemsegGatedCRF()
1
2023-10-11 05:19:25+00:00
16k
AMAAI-Lab/Video2Music
train.py
[ { "identifier": "compute_vevo_accuracy", "path": "dataset/vevo_dataset.py", "snippet": "def compute_vevo_accuracy(out, tgt):\n softmax = nn.Softmax(dim=-1)\n out = torch.argmax(softmax(out), dim=-1)\n\n out = out.flatten()\n tgt = tgt.flatten()\n\n mask = (tgt != CHORD_PAD)\n\n out = o...
import os import csv import shutil import torch import torch.nn as nn from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from torch.optim import Adam from dataset.vevo_dataset import compute_vevo_accuracy, create_vevo_datasets from model.music_transformer import MusicTransformer from model.video_music_transformer import VideoMusicTransformer from model.loss import SmoothCrossEntropyLoss from utilities.constants import * from utilities.device import get_device, use_cuda from utilities.lr_scheduling import LrStepTracker, get_lr from utilities.argument_funcs import parse_train_args, print_train_args, write_model_params from utilities.run_model_vevo import train_epoch, eval_model from torch.utils.tensorboard import SummaryWriter
12,950
CSV_HEADER = ["Epoch", "Learn rate", "Avg Train loss (total)", "Avg Train loss (chord)", "Avg Train loss (emotion)", "Avg Eval loss (total)", "Avg Eval loss (chord)", "Avg Eval loss (emotion)"] BASELINE_EPOCH = -1 version = VERSION split_ver = SPLIT_VER split_path = "split_" + split_ver VIS_MODELS_ARR = [ "2d/clip_l14p" ] # main def main( vm = "" , isPrintArgs = True ): args = parse_train_args() if isPrintArgs:
CSV_HEADER = ["Epoch", "Learn rate", "Avg Train loss (total)", "Avg Train loss (chord)", "Avg Train loss (emotion)", "Avg Eval loss (total)", "Avg Eval loss (chord)", "Avg Eval loss (emotion)"] BASELINE_EPOCH = -1 version = VERSION split_ver = SPLIT_VER split_path = "split_" + split_ver VIS_MODELS_ARR = [ "2d/clip_l14p" ] # main def main( vm = "" , isPrintArgs = True ): args = parse_train_args() if isPrintArgs:
print_train_args(args)
10
2023-10-13 09:06:24+00:00
16k
RobotLocomotion/gcs-science-robotics
reproduction/bimanual/helpers.py
[ { "identifier": "BezierGCS", "path": "gcs/bezier.py", "snippet": "class BezierGCS(BaseGCS):\n def __init__(self, regions, order, continuity, edges=None, hdot_min=1e-6, full_dim_overlap=False):\n BaseGCS.__init__(self, regions)\n\n self.order = order\n self.continuity = continuity...
import numpy as np import os import time from copy import copy from pydrake.common import FindResourceOrThrow from pydrake.geometry import ( CollisionFilterDeclaration, GeometrySet, MeshcatVisualizer, Rgba, Role, SceneGraph ) from pydrake.math import RigidTransform, RollPitchYaw, RotationMatrix from pydrake.multibody.inverse_kinematics import InverseKinematics from pydrake.multibody.parsing import LoadModelDirectives, Parser, ProcessModelDirectives from pydrake.multibody.plant import AddMultibodyPlantSceneGraph, MultibodyPlant from pydrake.perception import PointCloud from pydrake.solvers import MosekSolver, Solve from pydrake.systems.analysis import Simulator from pydrake.systems.framework import DiagramBuilder, LeafSystem from pydrake.systems.primitives import TrajectorySource from pydrake.systems.rendering import MultibodyPositionToGeometryPose from gcs.bezier import BezierGCS from gcs.linear import LinearGCS from gcs.rounding import * from reproduction.prm_comparison.helpers import set_transparency_of_models from reproduction.util import *
12,024
def filterCollsionGeometry(scene_graph, context): filter_manager = scene_graph.collision_filter_manager(context) inspector = scene_graph.model_inspector() iiwa1 = [[], [], [], [], [], [], [], []] iiwa2 = [[], [], [], [], [], [], [], []] wsg1 = [] wsg2 = [] shelf = [] bins = [[], []] table = [] for gid in inspector.GetGeometryIds( GeometrySet(inspector.GetAllGeometryIds()), Role.kProximity): gid_name = inspector.GetName(inspector.GetFrameId(gid)) if "iiwa_1::iiwa_link_" in gid_name: link_num = gid_name[18] iiwa1[int(link_num)].append(gid) elif "iiwa_2::iiwa_link_" in gid_name: link_num = gid_name[18] iiwa2[int(link_num)].append(gid) elif "wsg_1" in gid_name: wsg1.append(gid) elif "wsg_2" in gid_name: wsg2.append(gid) elif "shelves::" in gid_name: shelf.append(gid) elif "binR" in gid_name: bins[0].append(gid) elif "binL" in gid_name: bins[1].append(gid) elif "table" in gid_name: table.append(gid) else: print("Geometry", gid_name, "not assigned to an object.") filter_manager.Apply(CollisionFilterDeclaration().ExcludeWithin( GeometrySet(iiwa1[0] + iiwa1[1] + iiwa1[2] + iiwa1[3] + shelf))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[1] + iiwa1[2]+ iiwa1[3]), GeometrySet(iiwa1[4] + iiwa1[5]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[3] + iiwa1[4]), GeometrySet(iiwa1[6]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[2] + iiwa1[3] + iiwa1[4] + iiwa1[5] + iiwa1[6]), GeometrySet(iiwa1[7] + wsg1))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[0] + iiwa1[2]), GeometrySet(bins[0]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[1] + iiwa1[2] + iiwa1[3] + iiwa1[4]), GeometrySet(bins[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[0] + iiwa1[2]), GeometrySet(table))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeWithin( GeometrySet(iiwa2[0] + iiwa2[1] + iiwa2[2] + iiwa2[3] + shelf))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[1] + iiwa2[2]+ iiwa2[3]), GeometrySet(iiwa2[4] + iiwa2[5]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[3] + iiwa2[4]), GeometrySet(iiwa2[6]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[2] + iiwa2[3] + iiwa2[4] + iiwa2[5] + iiwa2[6]), GeometrySet(iiwa2[7] + wsg2))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[0] + iiwa2[0] + iiwa2[2]), GeometrySet(bins[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[0] + iiwa2[1] + iiwa2[2] + iiwa2[3] + iiwa2[4]), GeometrySet(bins[0]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[0] + iiwa2[0] + iiwa2[2]), GeometrySet(table))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[1]), GeometrySet(iiwa2[0] + iiwa2[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[2]), GeometrySet(iiwa2[0] + iiwa2[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[1]), GeometrySet(iiwa2[2]))) pairs = scene_graph.get_query_output_port().Eval(context).inspector().GetCollisionCandidates() print("Filtered collision pairs from", len(inspector.GetCollisionCandidates()), "to", len(pairs)) # initial_guess = np.concatenate((q0, q0)) # min_dist = (0.01, 0.01)??? def runBimanualIK(plant, context, wsg1_id, wsg2_id, wsg1_pose, wsg2_pose, initial_guess, min_dist=None): hand_frame1 = plant.GetBodyByName("body", wsg1_id).body_frame() hand_frame2 = plant.GetBodyByName("body", wsg2_id).body_frame() ik = InverseKinematics(plant, context) if min_dist is not None: ik.AddMinimumDistanceConstraint(*min_dist) ik.prog().AddBoundingBoxConstraint(plant.GetPositionLowerLimits(), plant.GetPositionUpperLimits(), ik.q()) ik.prog().SetInitialGuess(ik.q(), initial_guess) ik.prog().AddQuadraticCost((ik.q() - initial_guess).dot(ik.q() - initial_guess)) ik.AddPositionConstraint(hand_frame1, [0, 0, 0], plant.world_frame(), wsg1_pose.translation(), wsg1_pose.translation()) ik.AddOrientationConstraint(hand_frame1, RotationMatrix(), plant.world_frame(), wsg1_pose.rotation(), 0.001) ik.AddPositionConstraint(hand_frame2, [0, 0, 0], plant.world_frame(), wsg2_pose.translation(), wsg2_pose.translation()) ik.AddOrientationConstraint(hand_frame2, RotationMatrix(), plant.world_frame(), wsg2_pose.rotation(), 0.001) result = Solve(ik.prog()) return result.GetSolution(ik.q()) def visualizeConfig(diagram, plant, context, q): plant_context = plant.GetMyMutableContextFromRoot(context) plant.SetPositions(plant_context, q) diagram.ForcedPublish(context) def getLinearGcsPath(regions, sequence): path = [sequence[0]] run_time = 0.0
def getIkSeeds(): return { "top_shelf/top_shelf": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.9])), "top_shelf/shelf_1": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.65])), "top_shelf/shelf_2": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.4])), "top_shelf/bin_L": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9]), RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, np.pi), [0., 1.1, 0.3])), "shelf_1/top_shelf": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.65]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.9])), "shelf_1/shelf_1": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.65]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.65])), "shelf_1/shelf_2": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.65]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.4])), "shelf_1/bin_L": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.65]), RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, np.pi), [0., 1.1, 0.3])), "shelf_2/top_shelf": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.4]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.9])), "shelf_2/shelf_1": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.4]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.65])), "shelf_2/shelf_2": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.4]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.4])), "shelf_2/bin_L": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.4]), RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, np.pi), [0., 1.1, 0.3])), "bin_R/top_shelf": (RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, -np.pi), [0.0, -0.6, 0.3]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.9])), "bin_R/shelf_1": (RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, -np.pi), [0.0, -0.6, 0.3]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.65])), "bin_R/shelf_2": (RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, -np.pi), [0.0, -0.6, 0.3]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.4])), "bin_R/bin_L": (RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, -np.pi), [0.0, -0.6, 0.3]), RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, np.pi), [0., 1.1, 0.3])), "top_shelf/shelf_1_extract": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.5, 0.35, 0.65])), "top_shelf/shelf_2_extract": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.5, 0.35, 0.4])), "shelf_2_extract/top_shelf": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.5, 0.15, 0.4]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.9])), "shelf_1_extract/top_shelf": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.5, 0.15, 0.65]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.35, 0.9])), "top_shelf/shelf_1_cross": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2-0.3), [0.7, 0.15, 0.65])), "cross_table/top_shelf_cross": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi), [0.4, 0.4, 0.2]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.15, 0.9])), "shelf_2_cross/top_shelf_cross": (RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2+0.4), [0.7, 0.35, 0.4]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2-0.4), [0.7, 0.15, 0.9])), } def getConfigurationSeeds(): return { "top_shelf/top_shelf": [0.37080011, 0.41394084, -0.16861973, -0.70789778, -0.37031516, 0.60412162, 0.39982981, -0.37080019, 0.41394089, 0.16861988, -0.70789766, 0.37031506, 0.60412179, -0.39982996], "top_shelf/shelf_1": [0.37080079, 0.41394132, -0.16862043, -0.70789679, -0.37031656, 0.60412327, 0.39982969, -0.93496924, 0.46342534, 0.92801666, -1.45777635, -0.31061724, -0.0657716, -0.06019899], "top_shelf/shelf_2": [0.37086448, 0.41394538, -0.16875166, -0.70789745, -0.37020563, 0.60411217, 0.399785, -0.4416204 , 0.62965228, 0.20598405, -1.73324339, -0.41354372, -0.68738414, 0.17443976], "top_shelf/bin_L": [0.37081989, 0.41394235, -0.16866012, -0.70789737, -0.37028201, 0.60411923, 0.39981634, -0.89837331, -1.1576151 , 1.75505216, -1.37515153, 1.0676443 , 1.56371166, -0.64126346], "shelf_1/top_shelf": [0.93496924, 0.46342534, -0.92801666, -1.45777635, 0.31061724, -0.0657716 , 0.06019899, -0.37080079, 0.41394132, 0.16862043, -0.70789679, 0.37031656, 0.60412327, -0.39982969], "shelf_1/shelf_1": [0.87224109, 0.43096634, -0.82223436, -1.45840049, 0.73813452, -0.08999384, -0.41624203, -0.87556489, 0.43246906, 0.82766047, -1.45838515, -0.72259842, -0.0884963, 0.39840129], "shelf_1/shelf_2": [0.93496866, 0.463425 , -0.92801564, -1.45777634, 0.3106235, -0.06577172, 0.06019173, -0.44158858, 0.62964838, 0.20594112, -1.73324341, -0.41354987, -0.6873923 , 0.17446778], "shelf_1/bin_L": [0.93496918, 0.46342531, -0.92801656, -1.45777637, 0.31061728, -0.06577167, 0.06019927, -0.89837321, -1.15761746, 1.75504915, -1.37515113, 1.06764716, 1.56371454, -0.64126383], "shelf_2/top_shelf": [0.4416204, 0.62965228, -0.20598405, -1.73324339, 0.41354372, -0.68738414, -0.17443976, -0.37086448, 0.41394538, 0.16875166, -0.70789745, 0.37020563, 0.60411217, -0.399785], "shelf_2/shelf_1": [0.44158858, 0.62964838, -0.20594112, -1.73324341, 0.41354987, -0.6873923, -0.17446778, -0.93496866, 0.463425 , 0.92801564, -1.45777634, -0.3106235 , -0.06577172, -0.06019173], "shelf_2/shelf_2": [0.44161313, 0.62965141, -0.20597435, -1.73324346, 0.41354447, -0.68738613, -0.17444557, -0.4416132 , 0.62965142, 0.20597452, -1.73324348, -0.41354416, -0.68738609, 0.17444625], "shelf_2/bin_L": [0.44161528, 0.62965169, -0.20597726, -1.73324347, 0.41354399, -0.68738565, -0.17444283, -1.37292761, -0.68372976, 2.96705973, -1.41521783, 2.96705973, -1.11343251, -3.0140737 ], "bin_R/top_shelf": [0.81207926, -1.25359738, -1.58098625, -1.5155474 , -1.32223687, 1.50549708, -2.38221725, -0.37085114, 0.4139444 , 0.16872443, -0.70789757, 0.37022786, 0.60411401, -0.39979449], "bin_R/shelf_1": [0.81207923, -1.25358454, -1.58100042, -1.51554769, -1.32222337, 1.50548369, -2.3822204 , -0.9349716 , 0.46342674, 0.92802082, -1.45777624, -0.31059455, -0.0657707 , -0.06022391], "bin_R/shelf_2": [0.81207937, -1.25360462, -1.58097816, -1.51554761, -1.32224557, 1.50550485, -2.38221483, -0.44166552, 0.62965782, 0.20604497, -1.7332434 , -0.41353464, -0.6873727 , 0.17439863], "bin_R/bin_L": [-1.73637519, 0.6209681 , 0.24232887, -1.51538355, -0.17977474, 0.92618894, -3.01360257, 1.31861497, 0.72394333, 0.4044295 , -1.37509496, -0.27461997, 1.20038493, 0.18611701], "neutral/neutral": [0.0, -0.2, 0, -1.2, 0, 1.6, 0.0, 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0], "neutral/shelf_1": [0.0, -0.2, 0, -1.2, 0, 1.6, 0.0, -0.93496866, 0.463425 , 0.92801564, -1.45777634, -0.3106235 , -0.06577172, -0.06019173], "neutral/shelf_2": [0.0, -0.2, 0, -1.2, 0, 1.6, 0.0, -0.44166552, 0.62965782, 0.20604497, -1.7332434 , -0.41353464, -0.6873727 , 0.17439863], "shelf_1/neutral": [0.93496924, 0.46342534, -0.92801666, -1.45777635, 0.31061724, -0.0657716 , 0.06019899, 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0], "shelf_2/neutral": [0.44161528, 0.62965169, -0.20597726, -1.73324347, 0.41354399, -0.68738565, -0.17444283, 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0], "shelf_2_cross/top_shelf_cross": [0.47500706, 0.72909874, 0.01397772, -1.52841372, 0.15392366, -0.591641, -0.12870521, -0.48821156, 0.67762534, 0.02049926, -0.27420758, 0.10620709, 0.72215209, -0.09973172], } # Additional seed points not needed to connect the graph # "neutral/shelf_1_extract": [ 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0, -0.35486829, -0.10621117, -0.09276445, -1.94995786, 1.88826556, 0.46922151, -1.98267349], # "neutral/shelf_2_extract": [ 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0, 0.3078069 , 0.56765359, -0.86829439, -2.0943951 , 2.53950045, 1.09607546, -2.4169564], # "shelf_1_extract/neutral": [-1.05527083, -0.43710629, 1.15648812, -1.95011062, 0.24422131, -0.07820216, 0.15872416, 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0], # "shelf_2_extract/neutral": [-0.30739053, 0.5673891 , 0.86772198, -2.0943951 , -2.53946773, 1.09586777, 2.41729532, 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0], # "cross_table/top_shelf_cross": [ 0.04655887, 0.97997658, 0.52004246, -1.91926412, -1.37518707, -0.88823968, 0.07674699, -0.5921624 , 0.83651867, 0.20513136, -0.00257881, 0.51748756, 0.92012332, -0.51686487], def getDemoConfigurations(): return [ [0.0, -0.2, 0, -1.2, 0, 1.6, 0.0, 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0], [0.69312848, 0.36303784, -0.66625368, -1.49515991, 0.3230085, -0.10942887, -0.09496304, -0.69312891, 0.36303794, 0.66625426, -1.49515975, -0.32300928, -0.10942832, 0.0949629], [0.2014604, 0.66463495, 0.16799372, -1.66212763, -0.09131682, -0.64368844, -0.03645568, -0.38777291, 0.56141139, -0.05760515, -0.47447495, 0.06515541, 0.63627899, -0.02552148], [-1.8487163 , 0.71749397, 0.66464618, -1.4912954 , -0.52882233, 1.0096015 , -2.62844995, 1.43620829, 0.70451542, -0.01532988, -1.34999693, -0.00550105, 1.18684923, -0.14400234], ] def generateDemoConfigurations(plant, context, wsg1_id, wsg2_id): demo_q = [[0.0, -0.2, 0, -1.2, 0, 1.6, 0.0, 0.0, -0.2, 0, -1.2, 0, 1.6, 0.0]] initial_guess = copy(demo_q[0]) demo_q.append(runBimanualIK( plant, context, wsg1_id, wsg2_id, RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.10, 0.65]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2), [0.7, 0.40, 0.65]), initial_guess, (0.01, 0.01))) demo_q.append(runBimanualIK( plant, context, wsg1_id, wsg2_id, RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2+0.4), [0.7, 0.25, 0.4]), RigidTransform(RollPitchYaw(-np.pi+0.1, 0, np.pi/2-0.4), [0.7, 0.20, 0.9]), initial_guess, None)) initial_guess[0] = -np.pi/2 initial_guess[7] = np.pi/2 demo_q.append(runBimanualIK( plant, context, wsg1_id, wsg2_id, RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, -np.pi), [0.09, -0.6, 0.3]), RigidTransform(RollPitchYaw(-np.pi/2+0.1, 0, np.pi), [0.09, 1.1, 0.3]), initial_guess, None)) return demo_q def filterCollsionGeometry(scene_graph, context): filter_manager = scene_graph.collision_filter_manager(context) inspector = scene_graph.model_inspector() iiwa1 = [[], [], [], [], [], [], [], []] iiwa2 = [[], [], [], [], [], [], [], []] wsg1 = [] wsg2 = [] shelf = [] bins = [[], []] table = [] for gid in inspector.GetGeometryIds( GeometrySet(inspector.GetAllGeometryIds()), Role.kProximity): gid_name = inspector.GetName(inspector.GetFrameId(gid)) if "iiwa_1::iiwa_link_" in gid_name: link_num = gid_name[18] iiwa1[int(link_num)].append(gid) elif "iiwa_2::iiwa_link_" in gid_name: link_num = gid_name[18] iiwa2[int(link_num)].append(gid) elif "wsg_1" in gid_name: wsg1.append(gid) elif "wsg_2" in gid_name: wsg2.append(gid) elif "shelves::" in gid_name: shelf.append(gid) elif "binR" in gid_name: bins[0].append(gid) elif "binL" in gid_name: bins[1].append(gid) elif "table" in gid_name: table.append(gid) else: print("Geometry", gid_name, "not assigned to an object.") filter_manager.Apply(CollisionFilterDeclaration().ExcludeWithin( GeometrySet(iiwa1[0] + iiwa1[1] + iiwa1[2] + iiwa1[3] + shelf))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[1] + iiwa1[2]+ iiwa1[3]), GeometrySet(iiwa1[4] + iiwa1[5]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[3] + iiwa1[4]), GeometrySet(iiwa1[6]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[2] + iiwa1[3] + iiwa1[4] + iiwa1[5] + iiwa1[6]), GeometrySet(iiwa1[7] + wsg1))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[0] + iiwa1[2]), GeometrySet(bins[0]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[1] + iiwa1[2] + iiwa1[3] + iiwa1[4]), GeometrySet(bins[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[0] + iiwa1[2]), GeometrySet(table))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeWithin( GeometrySet(iiwa2[0] + iiwa2[1] + iiwa2[2] + iiwa2[3] + shelf))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[1] + iiwa2[2]+ iiwa2[3]), GeometrySet(iiwa2[4] + iiwa2[5]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[3] + iiwa2[4]), GeometrySet(iiwa2[6]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[2] + iiwa2[3] + iiwa2[4] + iiwa2[5] + iiwa2[6]), GeometrySet(iiwa2[7] + wsg2))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[0] + iiwa2[0] + iiwa2[2]), GeometrySet(bins[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[0] + iiwa2[1] + iiwa2[2] + iiwa2[3] + iiwa2[4]), GeometrySet(bins[0]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa2[0] + iiwa2[0] + iiwa2[2]), GeometrySet(table))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[1]), GeometrySet(iiwa2[0] + iiwa2[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[2]), GeometrySet(iiwa2[0] + iiwa2[1]))) filter_manager.Apply(CollisionFilterDeclaration().ExcludeBetween( GeometrySet(iiwa1[0] + iiwa1[1]), GeometrySet(iiwa2[2]))) pairs = scene_graph.get_query_output_port().Eval(context).inspector().GetCollisionCandidates() print("Filtered collision pairs from", len(inspector.GetCollisionCandidates()), "to", len(pairs)) # initial_guess = np.concatenate((q0, q0)) # min_dist = (0.01, 0.01)??? def runBimanualIK(plant, context, wsg1_id, wsg2_id, wsg1_pose, wsg2_pose, initial_guess, min_dist=None): hand_frame1 = plant.GetBodyByName("body", wsg1_id).body_frame() hand_frame2 = plant.GetBodyByName("body", wsg2_id).body_frame() ik = InverseKinematics(plant, context) if min_dist is not None: ik.AddMinimumDistanceConstraint(*min_dist) ik.prog().AddBoundingBoxConstraint(plant.GetPositionLowerLimits(), plant.GetPositionUpperLimits(), ik.q()) ik.prog().SetInitialGuess(ik.q(), initial_guess) ik.prog().AddQuadraticCost((ik.q() - initial_guess).dot(ik.q() - initial_guess)) ik.AddPositionConstraint(hand_frame1, [0, 0, 0], plant.world_frame(), wsg1_pose.translation(), wsg1_pose.translation()) ik.AddOrientationConstraint(hand_frame1, RotationMatrix(), plant.world_frame(), wsg1_pose.rotation(), 0.001) ik.AddPositionConstraint(hand_frame2, [0, 0, 0], plant.world_frame(), wsg2_pose.translation(), wsg2_pose.translation()) ik.AddOrientationConstraint(hand_frame2, RotationMatrix(), plant.world_frame(), wsg2_pose.rotation(), 0.001) result = Solve(ik.prog()) return result.GetSolution(ik.q()) def visualizeConfig(diagram, plant, context, q): plant_context = plant.GetMyMutableContextFromRoot(context) plant.SetPositions(plant_context, q) diagram.ForcedPublish(context) def getLinearGcsPath(regions, sequence): path = [sequence[0]] run_time = 0.0
gcs = LinearGCS(regions)
1
2023-10-13 00:27:32+00:00
16k
LeapLabTHU/Rank-DETR
projects/pnp_detr/configs/models/pnp_detr_r50.py
[ { "identifier": "BasicStem", "path": "detrex/modeling/backbone/resnet.py", "snippet": "class BasicStem(CNNBlockBase):\n \"\"\"\n The standard ResNet stem (layers before the first residual block),\n with a conv, relu and max_pool.\n\n Args:\n norm (str or callable): norm after the firs...
from detectron2.config import LazyCall as L from detrex.modeling.backbone import ResNet, BasicStem from detrex.modeling.matcher import HungarianMatcher from detrex.modeling.criterion.criterion import SetCriterion from detrex.layers.position_embedding import PositionEmbeddingSine from projects.pnp_detr.modeling import ( PnPDETR, PnPDetrTransformer, PnPDetrTransformerEncoder, PnPDetrTransformerDecoder, )
11,842
model = L(PnPDETR)( backbone=L(ResNet)( stem=L(BasicStem)(in_channels=3, out_channels=64, norm="FrozenBN"), stages=L(ResNet.make_default_stages)( depth=50, stride_in_1x1=False, norm="FrozenBN", ), out_features=["res2", "res3", "res4", "res5"], freeze_at=1, ), in_features=["res5"], in_channels=2048, position_embedding=L(PositionEmbeddingSine)( num_pos_feats=128, temperature=10000, normalize=True, ),
model = L(PnPDETR)( backbone=L(ResNet)( stem=L(BasicStem)(in_channels=3, out_channels=64, norm="FrozenBN"), stages=L(ResNet.make_default_stages)( depth=50, stride_in_1x1=False, norm="FrozenBN", ), out_features=["res2", "res3", "res4", "res5"], freeze_at=1, ), in_features=["res5"], in_channels=2048, position_embedding=L(PositionEmbeddingSine)( num_pos_feats=128, temperature=10000, normalize=True, ),
transformer=L(PnPDetrTransformer)(
8
2023-10-12 03:02:25+00:00
16k
ByungKwanLee/Full-Segment-Anything
mask_generator.py
[ { "identifier": "Sam", "path": "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_decoder: MaskDecoder,\n...
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,848
""" 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":
# 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 SamMaskGenerator: 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"]]
9
2023-10-13 20:07:42+00:00
16k
sakemin/cog-musicgen-remixer
audiocraft/modules/conditioners.py
[ { "identifier": "ChromaExtractor", "path": "audiocraft/modules/chroma.py", "snippet": "class ChromaExtractor(nn.Module):\n \"\"\"Chroma extraction and quantization.\n\n Args:\n sample_rate (int): Sample rate for the chroma extraction.\n n_chroma (int): Number of chroma bins for the c...
from collections import defaultdict from copy import deepcopy from dataclasses import dataclass, field from itertools import chain from pathlib import Path from num2words import num2words from transformers import RobertaTokenizer, T5EncoderModel, T5Tokenizer # type: ignore from torch import nn from torch.nn.utils.rnn import pad_sequence from .chroma import ChromaExtractor from .chord_chroma import ChordExtractor from .streaming import StreamingModule from .transformer import create_sin_embedding from ..data.audio import audio_read from ..data.audio_dataset import SegmentInfo from ..data.audio_utils import convert_audio from ..environment import AudioCraftEnvironment from ..quantization import ResidualVectorQuantizer from ..utils.autocast import TorchAutocast from ..utils.cache import EmbeddingCache from ..utils.utils import collate, hash_trick, length_to_mask, load_clap_state_dict, warn_once from .btc.utils import chords from demucs import pretrained from audiocraft.data.audio_dataset import AudioDataset from demucs.apply import apply_model from demucs.audio import convert_audio from demucs import pretrained from audiocraft.data.audio_dataset import AudioDataset from demucs.apply import apply_model from demucs.audio import convert_audio import logging import math import random import re import typing as tp import warnings import einops import spacy import torch import torch.nn.functional as F import numpy as np import laion_clap # type: ignore
13,735
if match_len_on_eval: self._use_masking = False self.duration = duration self.__dict__['demucs'] = pretrained.get_model('htdemucs').to(device) stem_sources: list = self.demucs.sources # type: ignore self.stem_indices = torch.LongTensor([stem_sources.index('vocals'), stem_sources.index('other')]).to(device) self.chroma = ChromaExtractor(sample_rate=sample_rate, n_chroma=n_chroma, radix2_exp=radix2_exp, **kwargs).to(device) self.chroma_len = self._get_chroma_len() self.eval_wavs: tp.Optional[torch.Tensor] = self._load_eval_wavs(eval_wavs, n_eval_wavs) self.cache = None if cache_path is not None: self.cache = EmbeddingCache(Path(cache_path) / 'wav', self.device, compute_embed_fn=self._get_full_chroma_for_cache, extract_embed_fn=self._extract_chroma_chunk) def _downsampling_factor(self) -> int: return self.chroma.winhop def _load_eval_wavs(self, path: tp.Optional[str], num_samples: int) -> tp.Optional[torch.Tensor]: """Load pre-defined waveforms from a json. These waveforms will be used for chroma extraction during evaluation. This is done to make the evaluation on MusicCaps fair (we shouldn't see the chromas of MusicCaps). """ if path is None: return None logger.info(f"Loading evaluation wavs from {path}") dataset: AudioDataset = AudioDataset.from_meta( path, segment_duration=self.duration, min_audio_duration=self.duration, sample_rate=self.sample_rate, channels=1) if len(dataset) > 0: eval_wavs = dataset.collater([dataset[i] for i in range(num_samples)]).to(self.device) logger.info(f"Using {len(eval_wavs)} evaluation wavs for chroma-stem conditioner") return eval_wavs else: raise ValueError("Could not find evaluation wavs, check lengths of wavs") def reset_eval_wavs(self, eval_wavs: tp.Optional[torch.Tensor]) -> None: self.eval_wavs = eval_wavs def has_eval_wavs(self) -> bool: return self.eval_wavs is not None def _sample_eval_wavs(self, num_samples: int) -> torch.Tensor: """Sample wavs from a predefined list.""" assert self.eval_wavs is not None, "Cannot sample eval wavs as no eval wavs provided." total_eval_wavs = len(self.eval_wavs) out = self.eval_wavs if num_samples > total_eval_wavs: out = self.eval_wavs.repeat(num_samples // total_eval_wavs + 1, 1, 1) return out[torch.randperm(len(out))][:num_samples] def _get_chroma_len(self) -> int: """Get length of chroma during training.""" dummy_wav = torch.zeros((1, int(self.sample_rate * self.duration)), device=self.device) dummy_chr = self.chroma(dummy_wav) return dummy_chr.shape[1] @torch.no_grad() def _get_stemmed_wav(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor: """Get parts of the wav that holds the melody, extracting the main stems from the wav.""" with self.autocast: wav = convert_audio( wav, sample_rate, self.demucs.samplerate, self.demucs.audio_channels) # type: ignore stems = apply_model(self.demucs, wav, device=self.device) stems = stems[:, self.stem_indices] # extract relevant stems for melody conditioning mix_wav = stems.sum(1) # merge extracted stems to single waveform mix_wav = convert_audio(mix_wav, self.demucs.samplerate, self.sample_rate, 1) # type: ignore return mix_wav @torch.no_grad() def _extract_chroma(self, wav: torch.Tensor) -> torch.Tensor: """Extract chroma features from the waveform.""" with self.autocast: return self.chroma(wav) @torch.no_grad() def _compute_wav_embedding(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor: """Compute wav embedding, applying stem and chroma extraction.""" # avoid 0-size tensors when we are working with null conds if wav.shape[-1] == 1: return self._extract_chroma(wav) stems = self._get_stemmed_wav(wav, sample_rate) chroma = self._extract_chroma(stems) return chroma @torch.no_grad() def _get_full_chroma_for_cache(self, path: tp.Union[str, Path], x: WavCondition, idx: int) -> torch.Tensor: """Extract chroma from the whole audio waveform at the given path.""" wav, sr = audio_read(path) wav = wav[None].to(self.device) wav = convert_audio(wav, sr, self.sample_rate, to_channels=1) chroma = self._compute_wav_embedding(wav, self.sample_rate)[0] return chroma def _extract_chroma_chunk(self, full_chroma: torch.Tensor, x: WavCondition, idx: int) -> torch.Tensor: """Extract a chunk of chroma from the full chroma derived from the full waveform.""" wav_length = x.wav.shape[-1] seek_time = x.seek_time[idx] assert seek_time is not None, ( "WavCondition seek_time is required " "when extracting chroma chunks from pre-computed chroma.") full_chroma = full_chroma.float() frame_rate = self.sample_rate / self._downsampling_factor() target_length = int(frame_rate * wav_length / self.sample_rate) index = int(frame_rate * seek_time) out = full_chroma[index: index + target_length] out = F.pad(out[None], (0, 0, 0, target_length - out.shape[0]))[0] return out.to(self.device) @torch.no_grad() def _get_wav_embedding(self, x: WavCondition) -> torch.Tensor: """Get the wav embedding from the WavCondition. The conditioner will either extract the embedding on-the-fly computing it from the condition wav directly or will rely on the embedding cache to load the pre-computed embedding if relevant. """ sampled_wav: tp.Optional[torch.Tensor] = None if not self.training and self.eval_wavs is not None:
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. logger = logging.getLogger(__name__) TextCondition = tp.Optional[str] # a text condition can be a string or None (if doesn't exist) ConditionType = tp.Tuple[torch.Tensor, torch.Tensor] # condition, mask class WavCondition(tp.NamedTuple): wav: torch.Tensor length: torch.Tensor sample_rate: tp.List[int] path: tp.List[tp.Optional[str]] = [] seek_time: tp.List[tp.Optional[float]] = [] class WavChordTextCondition(tp.NamedTuple): wav: tp.Union[torch.Tensor,str,tp.List[str]] length: torch.Tensor sample_rate: tp.List[int] path: tp.List[tp.Optional[str]] = [] seek_time: tp.List[tp.Optional[float]] = [] bpm : tp.List[tp.Optional[tp.Union[int, float]]] = [] meter : tp.List[tp.Optional[int]] = [] class JointEmbedCondition(tp.NamedTuple): wav: torch.Tensor text: tp.List[tp.Optional[str]] length: torch.Tensor sample_rate: tp.List[int] path: tp.List[tp.Optional[str]] = [] seek_time: tp.List[tp.Optional[float]] = [] @dataclass class ConditioningAttributes: text: tp.Dict[str, tp.Optional[str]] = field(default_factory=dict) wav: tp.Dict[str, tp.Union[WavCondition,WavChordTextCondition]] = field(default_factory=dict) joint_embed: tp.Dict[str, JointEmbedCondition] = field(default_factory=dict) def __getitem__(self, item): return getattr(self, item) @property def text_attributes(self): return self.text.keys() @property def wav_attributes(self): return self.wav.keys() @property def joint_embed_attributes(self): return self.joint_embed.keys() @property def attributes(self): return { "text": self.text_attributes, "wav": self.wav_attributes, "joint_embed": self.joint_embed_attributes, } def to_flat_dict(self): return { **{f"text.{k}": v for k, v in self.text.items()}, **{f"wav.{k}": v for k, v in self.wav.items()}, **{f"joint_embed.{k}": v for k, v in self.joint_embed.items()} } @classmethod def from_flat_dict(cls, x): out = cls() for k, v in x.items(): kind, att = k.split(".") out[kind][att] = v return out class SegmentWithAttributes(SegmentInfo): """Base class for all dataclasses that are used for conditioning. All child classes should implement `to_condition_attributes` that converts the existing attributes to a dataclass of type ConditioningAttributes. """ def to_condition_attributes(self) -> ConditioningAttributes: raise NotImplementedError() def nullify_condition(condition: ConditionType, dim: int = 1): """Transform an input condition to a null condition. The way it is done by converting it to a single zero vector similarly to how it is done inside WhiteSpaceTokenizer and NoopTokenizer. Args: condition (ConditionType): A tuple of condition and mask (tuple[torch.Tensor, torch.Tensor]) dim (int): The dimension that will be truncated (should be the time dimension) WARNING!: dim should not be the batch dimension! Returns: ConditionType: A tuple of null condition and mask """ assert dim != 0, "dim cannot be the batch dimension!" assert isinstance(condition, tuple) and \ isinstance(condition[0], torch.Tensor) and \ isinstance(condition[1], torch.Tensor), "'nullify_condition' got an unexpected input type!" cond, mask = condition B = cond.shape[0] last_dim = cond.dim() - 1 out = cond.transpose(dim, last_dim) out = 0. * out[..., :1] out = out.transpose(dim, last_dim) mask = torch.zeros((B, 1), device=out.device).int() assert cond.dim() == out.dim() return out, mask def nullify_wav(cond: tp.Union[WavCondition,WavChordTextCondition]) -> tp.Union[WavCondition,WavChordTextCondition]: """Transform a WavCondition to a nullified WavCondition. It replaces the wav by a null tensor, forces its length to 0, and replaces metadata by dummy attributes. Args: cond (WavCondition): Wav condition with wav, tensor of shape [B, T]. Returns: WavCondition: Nullified wav condition. """ if not isinstance(cond, WavChordTextCondition): null_wav, _ = nullify_condition((cond.wav, torch.zeros_like(cond.wav)), dim=cond.wav.dim() - 1) return WavCondition( wav=null_wav, length=torch.tensor([0] * cond.wav.shape[0], device=cond.wav.device), sample_rate=cond.sample_rate, path=[None] * cond.wav.shape[0], seek_time=[None] * cond.wav.shape[0], ) else: return WavChordTextCondition( wav=['N']* len(cond.wav), length=torch.tensor([0] * len(cond.wav), device=cond.length.device), sample_rate=cond.sample_rate, path=[None], seek_time=[None], bpm = cond.bpm, meter = cond.meter ) def nullify_joint_embed(embed: JointEmbedCondition) -> JointEmbedCondition: """Nullify the joint embedding condition by replacing it by a null tensor, forcing its length to 0, and replacing metadata by dummy attributes. Args: cond (JointEmbedCondition): Joint embedding condition with wav and text, wav tensor of shape [B, C, T]. """ null_wav, _ = nullify_condition((embed.wav, torch.zeros_like(embed.wav)), dim=embed.wav.dim() - 1) return JointEmbedCondition( wav=null_wav, text=[None] * len(embed.text), length=torch.LongTensor([0]).to(embed.wav.device), sample_rate=embed.sample_rate, path=[None] * embed.wav.shape[0], seek_time=[0] * embed.wav.shape[0], ) class Tokenizer: """Base tokenizer implementation (in case we want to introduce more advances tokenizers in the future). """ def __call__(self, texts: tp.List[tp.Optional[str]]) -> tp.Tuple[torch.Tensor, torch.Tensor]: raise NotImplementedError() class WhiteSpaceTokenizer(Tokenizer): """This tokenizer should be used for natural language descriptions. For example: ["he didn't, know he's going home.", 'shorter sentence'] => [[78, 62, 31, 4, 78, 25, 19, 34], [59, 77, 0, 0, 0, 0, 0, 0]] """ PUNCTUATION = "?:!.,;" def __init__(self, n_bins: int, pad_idx: int = 0, language: str = "en_core_web_sm", lemma: bool = True, stopwords: bool = True) -> None: self.n_bins = n_bins self.pad_idx = pad_idx self.lemma = lemma self.stopwords = stopwords try: self.nlp = spacy.load(language) except IOError: spacy.cli.download(language) # type: ignore self.nlp = spacy.load(language) @tp.no_type_check def __call__(self, texts: tp.List[tp.Optional[str]], return_text: bool = False) -> tp.Tuple[torch.Tensor, torch.Tensor]: """Take a list of strings and convert them to a tensor of indices. Args: texts (list[str]): List of strings. return_text (bool, optional): Whether to return text as additional tuple item. Defaults to False. Returns: tuple[torch.Tensor, torch.Tensor]: - Indices of words in the LUT. - And a mask indicating where the padding tokens are """ output, lengths = [], [] texts = deepcopy(texts) for i, text in enumerate(texts): # if current sample doesn't have a certain attribute, replace with pad token if text is None: output.append(torch.Tensor([self.pad_idx])) lengths.append(0) continue # convert numbers to words text = re.sub(r"(\d+)", lambda x: num2words(int(x.group(0))), text) # type: ignore # normalize text text = self.nlp(text) # type: ignore # remove stopwords if self.stopwords: text = [w for w in text if not w.is_stop] # type: ignore # remove punctuation text = [w for w in text if w.text not in self.PUNCTUATION] # type: ignore # lemmatize if needed text = [getattr(t, "lemma_" if self.lemma else "text") for t in text] # type: ignore texts[i] = " ".join(text) lengths.append(len(text)) # convert to tensor tokens = torch.Tensor([hash_trick(w, self.n_bins) for w in text]) output.append(tokens) mask = length_to_mask(torch.IntTensor(lengths)).int() padded_output = pad_sequence(output, padding_value=self.pad_idx).int().t() if return_text: return padded_output, mask, texts # type: ignore return padded_output, mask class NoopTokenizer(Tokenizer): """This tokenizer should be used for global conditioners such as: artist, genre, key, etc. The difference between this and WhiteSpaceTokenizer is that NoopTokenizer does not split strings, so "Jeff Buckley" will get it's own index. Whereas WhiteSpaceTokenizer will split it to ["Jeff", "Buckley"] and return an index per word. For example: ["Queen", "ABBA", "Jeff Buckley"] => [43, 55, 101] ["Metal", "Rock", "Classical"] => [0, 223, 51] """ def __init__(self, n_bins: int, pad_idx: int = 0): self.n_bins = n_bins self.pad_idx = pad_idx def __call__(self, texts: tp.List[tp.Optional[str]]) -> tp.Tuple[torch.Tensor, torch.Tensor]: output, lengths = [], [] for text in texts: # if current sample doesn't have a certain attribute, replace with pad token if text is None: output.append(self.pad_idx) lengths.append(0) else: output.append(hash_trick(text, self.n_bins)) lengths.append(1) tokens = torch.LongTensor(output).unsqueeze(1) mask = length_to_mask(torch.IntTensor(lengths)).int() return tokens, mask class BaseConditioner(nn.Module): """Base model for all conditioner modules. We allow the output dim to be different than the hidden dim for two reasons: 1) keep our LUTs small when the vocab is large; 2) make all condition dims consistent. Args: dim (int): Hidden dim of the model. output_dim (int): Output dim of the conditioner. """ def __init__(self, dim: int, output_dim: int): super().__init__() self.dim = dim self.output_dim = output_dim self.output_proj = nn.Linear(dim, output_dim) def tokenize(self, *args, **kwargs) -> tp.Any: """Should be any part of the processing that will lead to a synchronization point, e.g. BPE tokenization with transfer to the GPU. The returned value will be saved and return later when calling forward(). """ raise NotImplementedError() def forward(self, inputs: tp.Any) -> ConditionType: """Gets input that should be used as conditioning (e.g, genre, description or a waveform). Outputs a ConditionType, after the input data was embedded as a dense vector. Returns: ConditionType: - A tensor of size [B, T, D] where B is the batch size, T is the length of the output embedding and D is the dimension of the embedding. - And a mask indicating where the padding tokens. """ raise NotImplementedError() class TextConditioner(BaseConditioner): ... class LUTConditioner(TextConditioner): """Lookup table TextConditioner. Args: n_bins (int): Number of bins. dim (int): Hidden dim of the model (text-encoder/LUT). output_dim (int): Output dim of the conditioner. tokenizer (str): Name of the tokenizer. pad_idx (int, optional): Index for padding token. Defaults to 0. """ def __init__(self, n_bins: int, dim: int, output_dim: int, tokenizer: str, pad_idx: int = 0): super().__init__(dim, output_dim) self.embed = nn.Embedding(n_bins, dim) self.tokenizer: Tokenizer if tokenizer == 'whitespace': self.tokenizer = WhiteSpaceTokenizer(n_bins, pad_idx=pad_idx) elif tokenizer == 'noop': self.tokenizer = NoopTokenizer(n_bins, pad_idx=pad_idx) else: raise ValueError(f"unrecognized tokenizer `{tokenizer}`.") def tokenize(self, x: tp.List[tp.Optional[str]]) -> tp.Tuple[torch.Tensor, torch.Tensor]: device = self.embed.weight.device tokens, mask = self.tokenizer(x) tokens, mask = tokens.to(device), mask.to(device) return tokens, mask def forward(self, inputs: tp.Tuple[torch.Tensor, torch.Tensor]) -> ConditionType: tokens, mask = inputs embeds = self.embed(tokens) embeds = self.output_proj(embeds) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class T5Conditioner(TextConditioner): """T5-based TextConditioner. Args: name (str): Name of the T5 model. output_dim (int): Output dim of the conditioner. finetune (bool): Whether to fine-tune T5 at train time. device (str): Device for T5 Conditioner. autocast_dtype (tp.Optional[str], optional): Autocast dtype. word_dropout (float, optional): Word dropout probability. normalize_text (bool, optional): Whether to apply text normalization. """ MODELS = ["t5-small", "t5-base", "t5-large", "t5-3b", "t5-11b", "google/flan-t5-small", "google/flan-t5-base", "google/flan-t5-large", "google/flan-t5-xl", "google/flan-t5-xxl"] MODELS_DIMS = { "t5-small": 512, "t5-base": 768, "t5-large": 1024, "t5-3b": 1024, "t5-11b": 1024, "google/flan-t5-small": 512, "google/flan-t5-base": 768, "google/flan-t5-large": 1024, "google/flan-t5-3b": 1024, "google/flan-t5-11b": 1024, } def __init__(self, name: str, output_dim: int, finetune: bool, device: str, autocast_dtype: tp.Optional[str] = 'float32', word_dropout: float = 0., normalize_text: bool = False): assert name in self.MODELS, f"Unrecognized t5 model name (should in {self.MODELS})" super().__init__(self.MODELS_DIMS[name], output_dim) self.device = device self.name = name self.finetune = finetune self.word_dropout = word_dropout if autocast_dtype is None or self.device == 'cpu': self.autocast = TorchAutocast(enabled=False) if self.device != 'cpu': logger.warning("T5 has no autocast, this might lead to NaN") else: dtype = getattr(torch, autocast_dtype) assert isinstance(dtype, torch.dtype) logger.info(f"T5 will be evaluated with autocast as {autocast_dtype}") self.autocast = TorchAutocast(enabled=True, device_type=self.device, dtype=dtype) # Let's disable logging temporarily because T5 will vomit some errors otherwise. # thanks https://gist.github.com/simon-weber/7853144 previous_level = logging.root.manager.disable logging.disable(logging.ERROR) with warnings.catch_warnings(): warnings.simplefilter("ignore") try: self.t5_tokenizer = T5Tokenizer.from_pretrained(name) t5 = T5EncoderModel.from_pretrained(name).train(mode=finetune) finally: logging.disable(previous_level) if finetune: self.t5 = t5 else: # this makes sure that the t5 models is not part # of the saved checkpoint self.__dict__['t5'] = t5.to(device) self.normalize_text = normalize_text if normalize_text: self.text_normalizer = WhiteSpaceTokenizer(1, lemma=True, stopwords=True) def tokenize(self, x: tp.List[tp.Optional[str]]) -> tp.Dict[str, torch.Tensor]: # if current sample doesn't have a certain attribute, replace with empty string entries: tp.List[str] = [xi if xi is not None else "" for xi in x] if self.normalize_text: _, _, entries = self.text_normalizer(entries, return_text=True) if self.word_dropout > 0. and self.training: new_entries = [] for entry in entries: words = [word for word in entry.split(" ") if random.random() >= self.word_dropout] new_entries.append(" ".join(words)) entries = new_entries empty_idx = torch.LongTensor([i for i, xi in enumerate(entries) if xi == ""]) inputs = self.t5_tokenizer(entries, return_tensors='pt', padding=True).to(self.device) mask = inputs['attention_mask'] mask[empty_idx, :] = 0 # zero-out index where the input is non-existant return inputs def forward(self, inputs: tp.Dict[str, torch.Tensor]) -> ConditionType: mask = inputs['attention_mask'] with torch.set_grad_enabled(self.finetune), self.autocast: embeds = self.t5(**inputs).last_hidden_state embeds = self.output_proj(embeds.to(self.output_proj.weight)) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class WaveformConditioner(BaseConditioner): """Base class for all conditioners that take a waveform as input. Classes that inherit must implement `_get_wav_embedding` that outputs a continuous tensor, and `_downsampling_factor` that returns the down-sampling factor of the embedding model. Args: dim (int): The internal representation dimension. output_dim (int): Output dimension. device (tp.Union[torch.device, str]): Device. """ def __init__(self, dim: int, output_dim: int, device: tp.Union[torch.device, str]): super().__init__(dim, output_dim) self.device = device # if False no masking is done, used in ChromaStemConditioner when completing by periodicity a sample. self._use_masking = True def tokenize(self, x: WavCondition) -> WavCondition: wav, length, sample_rate, path, seek_time = x assert length is not None return WavCondition(wav.to(self.device), length.to(self.device), sample_rate, path, seek_time) def _get_wav_embedding(self, x: WavCondition) -> torch.Tensor: """Gets as input a WavCondition and returns a dense embedding.""" raise NotImplementedError() def _downsampling_factor(self): """Returns the downsampling factor of the embedding model.""" raise NotImplementedError() def forward(self, x: WavCondition) -> ConditionType: """Extract condition embedding and mask from a waveform and its metadata. Args: x (WavCondition): Waveform condition containing raw waveform and metadata. Returns: ConditionType: a dense vector representing the conditioning along with its mask """ wav, lengths, *_ = x with torch.no_grad(): embeds = self._get_wav_embedding(x) embeds = embeds.to(self.output_proj.weight) embeds = self.output_proj(embeds) if lengths is not None and self._use_masking: lengths = lengths / self._downsampling_factor() mask = length_to_mask(lengths, max_len=embeds.shape[1]).int() # type: ignore else: mask = torch.ones_like(embeds[..., 0]) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class ChromaStemConditioner(WaveformConditioner): """Chroma conditioner based on stems. The ChromaStemConditioner uses DEMUCS to first filter out drums and bass, as the drums and bass often dominate the chroma leading to the chroma features not containing information about the melody. Args: output_dim (int): Output dimension for the conditioner. sample_rate (int): Sample rate for the chroma extractor. n_chroma (int): Number of chroma bins for the chroma extractor. radix2_exp (int): Size of stft window for the chroma extractor (power of 2, e.g. 12 -> 2^12). duration (int): duration used during training. This is later used for correct padding in case we are using chroma as prefix. match_len_on_eval (bool, optional): if True then all chromas are padded to the training duration. Defaults to False. eval_wavs (str, optional): path to a dataset manifest with waveform, this waveforms are used as conditions during eval (for cases where we don't want to leak test conditions like MusicCaps). Defaults to None. n_eval_wavs (int, optional): limits the number of waveforms used for conditioning. Defaults to 0. device (tp.Union[torch.device, str], optional): Device for the conditioner. **kwargs: Additional parameters for the chroma extractor. """ def __init__(self, output_dim: int, sample_rate: int, n_chroma: int, radix2_exp: int, duration: float, match_len_on_eval: bool = True, eval_wavs: tp.Optional[str] = None, n_eval_wavs: int = 0, cache_path: tp.Optional[tp.Union[str, Path]] = None, device: tp.Union[torch.device, str] = 'cpu', **kwargs): super().__init__(dim=n_chroma, output_dim=output_dim, device=device) self.autocast = TorchAutocast(enabled=device != 'cpu', device_type=self.device, dtype=torch.float32) self.sample_rate = sample_rate self.match_len_on_eval = match_len_on_eval if match_len_on_eval: self._use_masking = False self.duration = duration self.__dict__['demucs'] = pretrained.get_model('htdemucs').to(device) stem_sources: list = self.demucs.sources # type: ignore self.stem_indices = torch.LongTensor([stem_sources.index('vocals'), stem_sources.index('other')]).to(device) self.chroma = ChromaExtractor(sample_rate=sample_rate, n_chroma=n_chroma, radix2_exp=radix2_exp, **kwargs).to(device) self.chroma_len = self._get_chroma_len() self.eval_wavs: tp.Optional[torch.Tensor] = self._load_eval_wavs(eval_wavs, n_eval_wavs) self.cache = None if cache_path is not None: self.cache = EmbeddingCache(Path(cache_path) / 'wav', self.device, compute_embed_fn=self._get_full_chroma_for_cache, extract_embed_fn=self._extract_chroma_chunk) def _downsampling_factor(self) -> int: return self.chroma.winhop def _load_eval_wavs(self, path: tp.Optional[str], num_samples: int) -> tp.Optional[torch.Tensor]: """Load pre-defined waveforms from a json. These waveforms will be used for chroma extraction during evaluation. This is done to make the evaluation on MusicCaps fair (we shouldn't see the chromas of MusicCaps). """ if path is None: return None logger.info(f"Loading evaluation wavs from {path}") dataset: AudioDataset = AudioDataset.from_meta( path, segment_duration=self.duration, min_audio_duration=self.duration, sample_rate=self.sample_rate, channels=1) if len(dataset) > 0: eval_wavs = dataset.collater([dataset[i] for i in range(num_samples)]).to(self.device) logger.info(f"Using {len(eval_wavs)} evaluation wavs for chroma-stem conditioner") return eval_wavs else: raise ValueError("Could not find evaluation wavs, check lengths of wavs") def reset_eval_wavs(self, eval_wavs: tp.Optional[torch.Tensor]) -> None: self.eval_wavs = eval_wavs def has_eval_wavs(self) -> bool: return self.eval_wavs is not None def _sample_eval_wavs(self, num_samples: int) -> torch.Tensor: """Sample wavs from a predefined list.""" assert self.eval_wavs is not None, "Cannot sample eval wavs as no eval wavs provided." total_eval_wavs = len(self.eval_wavs) out = self.eval_wavs if num_samples > total_eval_wavs: out = self.eval_wavs.repeat(num_samples // total_eval_wavs + 1, 1, 1) return out[torch.randperm(len(out))][:num_samples] def _get_chroma_len(self) -> int: """Get length of chroma during training.""" dummy_wav = torch.zeros((1, int(self.sample_rate * self.duration)), device=self.device) dummy_chr = self.chroma(dummy_wav) return dummy_chr.shape[1] @torch.no_grad() def _get_stemmed_wav(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor: """Get parts of the wav that holds the melody, extracting the main stems from the wav.""" with self.autocast: wav = convert_audio( wav, sample_rate, self.demucs.samplerate, self.demucs.audio_channels) # type: ignore stems = apply_model(self.demucs, wav, device=self.device) stems = stems[:, self.stem_indices] # extract relevant stems for melody conditioning mix_wav = stems.sum(1) # merge extracted stems to single waveform mix_wav = convert_audio(mix_wav, self.demucs.samplerate, self.sample_rate, 1) # type: ignore return mix_wav @torch.no_grad() def _extract_chroma(self, wav: torch.Tensor) -> torch.Tensor: """Extract chroma features from the waveform.""" with self.autocast: return self.chroma(wav) @torch.no_grad() def _compute_wav_embedding(self, wav: torch.Tensor, sample_rate: int) -> torch.Tensor: """Compute wav embedding, applying stem and chroma extraction.""" # avoid 0-size tensors when we are working with null conds if wav.shape[-1] == 1: return self._extract_chroma(wav) stems = self._get_stemmed_wav(wav, sample_rate) chroma = self._extract_chroma(stems) return chroma @torch.no_grad() def _get_full_chroma_for_cache(self, path: tp.Union[str, Path], x: WavCondition, idx: int) -> torch.Tensor: """Extract chroma from the whole audio waveform at the given path.""" wav, sr = audio_read(path) wav = wav[None].to(self.device) wav = convert_audio(wav, sr, self.sample_rate, to_channels=1) chroma = self._compute_wav_embedding(wav, self.sample_rate)[0] return chroma def _extract_chroma_chunk(self, full_chroma: torch.Tensor, x: WavCondition, idx: int) -> torch.Tensor: """Extract a chunk of chroma from the full chroma derived from the full waveform.""" wav_length = x.wav.shape[-1] seek_time = x.seek_time[idx] assert seek_time is not None, ( "WavCondition seek_time is required " "when extracting chroma chunks from pre-computed chroma.") full_chroma = full_chroma.float() frame_rate = self.sample_rate / self._downsampling_factor() target_length = int(frame_rate * wav_length / self.sample_rate) index = int(frame_rate * seek_time) out = full_chroma[index: index + target_length] out = F.pad(out[None], (0, 0, 0, target_length - out.shape[0]))[0] return out.to(self.device) @torch.no_grad() def _get_wav_embedding(self, x: WavCondition) -> torch.Tensor: """Get the wav embedding from the WavCondition. The conditioner will either extract the embedding on-the-fly computing it from the condition wav directly or will rely on the embedding cache to load the pre-computed embedding if relevant. """ sampled_wav: tp.Optional[torch.Tensor] = None if not self.training and self.eval_wavs is not None:
warn_once(logger, "Using precomputed evaluation wavs!")
15
2023-10-09 09:55:24+00:00
16k
Texaser/MTN
nerf/network.py
[ { "identifier": "trunc_exp", "path": "activation.py", "snippet": "class _trunc_exp(Function):\n def forward(ctx, x):\n def backward(ctx, g):\ndef biased_softplus(x, bias=0):" }, { "identifier": "NeRFRenderer", "path": "nerf/renderer.py", "snippet": "class NeRFRenderer(nn.Module):\n...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from activation import trunc_exp from .renderer import NeRFRenderer from encoding import get_encoder from .utils import safe_normalize
13,514
# TODO: not sure about the details... class ResBlock(nn.Module): def __init__(self, dim_in, dim_out, bias=True): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dense = nn.Linear(self.dim_in, self.dim_out, bias=bias) self.norm = nn.LayerNorm(self.dim_out) self.activation = nn.SiLU(inplace=True) if self.dim_in != self.dim_out: self.skip = nn.Linear(self.dim_in, self.dim_out, bias=False) else: self.skip = None def forward(self, x): # x: [B, C] identity = x out = self.dense(x) out = self.norm(out) if self.skip is not None: identity = self.skip(identity) out += identity out = self.activation(out) return out class BasicBlock(nn.Module): def __init__(self, dim_in, dim_out, bias=True): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dense = nn.Linear(self.dim_in, self.dim_out, bias=bias) self.activation = nn.ReLU(inplace=True) def forward(self, x): # x: [B, C] out = self.dense(x) out = self.activation(out) return out class MLP(nn.Module): def __init__(self, dim_in, dim_out, dim_hidden, num_layers, bias=True, block=BasicBlock): 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): if l == 0: net.append(BasicBlock(self.dim_in, self.dim_hidden, bias=bias)) elif l != num_layers - 1: net.append(block(self.dim_hidden, self.dim_hidden, bias=bias)) else: net.append(nn.Linear(self.dim_hidden, self.dim_out, bias=bias)) self.net = nn.ModuleList(net) def forward(self, x): for l in range(self.num_layers): x = self.net[l](x) return x
# TODO: not sure about the details... class ResBlock(nn.Module): def __init__(self, dim_in, dim_out, bias=True): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dense = nn.Linear(self.dim_in, self.dim_out, bias=bias) self.norm = nn.LayerNorm(self.dim_out) self.activation = nn.SiLU(inplace=True) if self.dim_in != self.dim_out: self.skip = nn.Linear(self.dim_in, self.dim_out, bias=False) else: self.skip = None def forward(self, x): # x: [B, C] identity = x out = self.dense(x) out = self.norm(out) if self.skip is not None: identity = self.skip(identity) out += identity out = self.activation(out) return out class BasicBlock(nn.Module): def __init__(self, dim_in, dim_out, bias=True): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dense = nn.Linear(self.dim_in, self.dim_out, bias=bias) self.activation = nn.ReLU(inplace=True) def forward(self, x): # x: [B, C] out = self.dense(x) out = self.activation(out) return out class MLP(nn.Module): def __init__(self, dim_in, dim_out, dim_hidden, num_layers, bias=True, block=BasicBlock): 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): if l == 0: net.append(BasicBlock(self.dim_in, self.dim_hidden, bias=bias)) elif l != num_layers - 1: net.append(block(self.dim_hidden, self.dim_hidden, bias=bias)) else: net.append(nn.Linear(self.dim_hidden, self.dim_out, bias=bias)) self.net = nn.ModuleList(net) def forward(self, x): for l in range(self.num_layers): x = self.net[l](x) return x
class NeRFNetwork(NeRFRenderer):
1
2023-10-11 04:06:20+00:00
16k
oracle/guardian-ai
guardian_ai/fairness/metrics/core.py
[ { "identifier": "EqualizedOddsScorer", "path": "guardian_ai/fairness/metrics/model.py", "snippet": "class EqualizedOddsScorer(_ModelFairnessScorer):\n \"\"\"\n Measures the disparity of a model's true positive and false positive rates\n between subgroups and the rest of the subgroups.\n\n Th...
from guardian_ai.fairness.metrics.model import ( EqualizedOddsScorer, ErrorRateScorer, FalseDiscoveryRateScorer, FalseNegativeRateScorer, FalseOmissionRateScorer, FalsePositiveRateScorer, ModelStatisticalParityScorer, TheilIndexScorer, TruePositiveRateScorer, equalized_odds, error_rate, false_discovery_rate, false_negative_rate, false_omission_rate, false_positive_rate, model_statistical_parity, theil_index, true_positive_rate, ) from guardian_ai.utils.exception import GuardianAIValueError
13,057
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2023 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ """Core for fairness metrics""" fairness_scorers_dict = { # noqa N816 "statistical_parity": ModelStatisticalParityScorer, "TPR": TruePositiveRateScorer, "FPR": FalsePositiveRateScorer, "FNR": FalseNegativeRateScorer, "FOR": FalseOmissionRateScorer, "FDR": FalseDiscoveryRateScorer, "error_rate": ErrorRateScorer, "equalized_odds": EqualizedOddsScorer, "theil_index": TheilIndexScorer, } def _get_fairness_scorer(metric, protected_attributes, **kwargs): # noqa N802 if metric not in fairness_scorers_dict: raise GuardianAIValueError( f"{metric} is not a supported model fairness metric. Supported " f"metrics are: {list(fairness_scorers_dict)}." ) return fairness_scorers_dict[metric](protected_attributes, **kwargs) fairness_metrics_dict = { "statistical_parity": model_statistical_parity, "TPR": true_positive_rate, "FPR": false_positive_rate, "FNR": false_negative_rate, "FOR": false_omission_rate, "FDR": false_discovery_rate, "error_rate": error_rate, "equalized_odds": equalized_odds,
#!/usr/bin/env python # -*- coding: utf-8 -*-- # Copyright (c) 2023 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ """Core for fairness metrics""" fairness_scorers_dict = { # noqa N816 "statistical_parity": ModelStatisticalParityScorer, "TPR": TruePositiveRateScorer, "FPR": FalsePositiveRateScorer, "FNR": FalseNegativeRateScorer, "FOR": FalseOmissionRateScorer, "FDR": FalseDiscoveryRateScorer, "error_rate": ErrorRateScorer, "equalized_odds": EqualizedOddsScorer, "theil_index": TheilIndexScorer, } def _get_fairness_scorer(metric, protected_attributes, **kwargs): # noqa N802 if metric not in fairness_scorers_dict: raise GuardianAIValueError( f"{metric} is not a supported model fairness metric. Supported " f"metrics are: {list(fairness_scorers_dict)}." ) return fairness_scorers_dict[metric](protected_attributes, **kwargs) fairness_metrics_dict = { "statistical_parity": model_statistical_parity, "TPR": true_positive_rate, "FPR": false_positive_rate, "FNR": false_negative_rate, "FOR": false_omission_rate, "FDR": false_discovery_rate, "error_rate": error_rate, "equalized_odds": equalized_odds,
"theil_index": theil_index,
16
2023-10-09 09:48:50+00:00
16k
IST-DASLab/SparseFinetuning
llmfoundry/models/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "llmfoundry/models/layers/attention.py", "snippet": "def attn_bias_shape(attn_impl: str, n_heads: int, seq_len: int, alibi: bool,\n prefix_lm: bool, causal: bool, use_sequence_id: bool):\n if attn_impl == 'flash':\n return None\n ...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import Any, List, Mapping, MutableMapping, Optional, Tuple, Union from composer.metrics import (InContextLearningLMAccuracy, InContextLearningLMExpectedCalibrationError, InContextLearningMCExpectedCalibrationError, InContextLearningMultipleChoiceAccuracy, InContextLearningQAAccuracy) from composer.metrics.nlp import LanguageCrossEntropy, LanguagePerplexity from composer.models import HuggingFaceModel from composer.utils import dist from omegaconf import DictConfig from omegaconf import OmegaConf as om from transformers import PreTrainedModel, PreTrainedTokenizerBase from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast) from llmfoundry.models.layers.attention import attn_bias_shape, build_attn_bias from llmfoundry.models.layers.blocks import MPTBlock from llmfoundry.models.layers.custom_embedding import SharedEmbedding from llmfoundry.models.layers.fc import FC_CLASS_REGISTRY as FC_CLASS_REGISTRY from llmfoundry.models.layers.ffn import \ FFN_CLASS_REGISTRY as FFN_CLASS_REGISTRY from llmfoundry.models.layers.ffn import MPTMLP as MPTMLP from llmfoundry.models.layers.ffn import build_ffn as build_ffn from llmfoundry.models.layers.norm import NORM_CLASS_REGISTRY from llmfoundry.models.mpt.configuration_mpt import MPTConfig from llmfoundry.models.utils.adapt_tokenizer import ( AutoTokenizerForMOD, # type: ignore (see note), adapt_tokenizer_for_denoising, # type: ignore (see note) ) from llmfoundry.models.utils.hf_prefixlm_converter import ( add_bidirectional_mask_if_missing, # type: ignore (see note) convert_hf_causal_lm_to_prefix_lm, # type: ignore (see note) ) from llmfoundry.models.utils.meta_init_context import \ init_empty_weights # type: ignore (see note) from llmfoundry.models.utils.param_init_fns import ( generic_param_init_fn_, # type: ignore (see note) MODEL_INIT_REGISTRY, ) from llmfoundry.models.layers.flash_attn_triton import flash_attn_func as flash_attn_func from flash_attn.losses.cross_entropy import CrossEntropyLoss as FusedCrossEntropyLoss # type: ignore # isort: skip
11,923
'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.' ) 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) # type: ignore if self.learned_pos_emb: 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)=}; {self.config.n_layers=}).' ) # For attn_impl: triton and flash the past key tensor spec is (batch, seq, dim). # For attn_impl: torch the past key tensor spec is (batch, heads, head_dim, seq). # Here we shift position embedding using the `seq` dim of the past key past_position = past_key_values[0][0].size(1) if self.attn_impl == 'torch': past_position = past_key_values[0][0].size(3) 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 ' + f'{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: # adjust the position indices to account for padding tokens pos = torch.clamp( pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0, ) pos_emb = self.wpe(pos) # type: ignore x = tok_emb + pos_emb else: # ALiBi and NoPE use this path (RoPE will also use this path if / when enabled) x = tok_emb if self.embedding_fraction == 1: x = self.emb_drop(x) # type: ignore else: # this implementation is proposed on page 7 of the GLM-130B paper https://arxiv.org/abs/2210.02414 x_shrunk = (x * self.embedding_fraction) + ( x.detach() * (1 - self.embedding_fraction)) assert isinstance(self.emb_drop, nn.Module) # pyright x = self.emb_drop(x_shrunk) attn_bias, attention_mask = self._attn_bias( device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, ) # initialize the past key values cache if it should be used if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers) ] # type: ignore all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for b_idx, block in enumerate(self.blocks): # type: ignore if output_hidden_states: assert all_hidden_states is not None # pyright all_hidden_states = all_hidden_states + (x,) past_key_value = (past_key_values[b_idx] if past_key_values is not None else None) x, attn_weights, 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 if output_attentions: assert all_self_attns is not None # pyright all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) # type: ignore # add hidden states from the last decoder layer if output_hidden_states: assert all_hidden_states is not None # pyright all_hidden_states = all_hidden_states + (x,) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns, ) # Param Initialization, needed for device='meta' fast initialization def param_init_fn(self, module: nn.Module): init_fn_name = self.config.init_config['name']
# Copyright 2022 MosaicML LLM Foundry authors # SPDX-License-Identifier: Apache-2.0 """A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ # NOTE: All utils are imported directly even if unused so that # HuggingFace can detect all the needed files to copy into its modules folder. # Otherwise, certain modules are missing. # isort: off try: except: pass # isort: on class MPTPreTrainedModel(PreTrainedModel): config_class = MPTConfig base_model_prefix = 'model' _no_split_modules = ['MPTBlock'] 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'] self.learned_pos_emb = config.learned_pos_emb if config.init_device == 'mixed': if dist.get_local_rank() == 0: config.init_device = 'cpu' else: config.init_device = 'meta' 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()] # CogView (https://arxiv.org/abs/2105.13290) and GLM-130B (https://arxiv.org/abs/2210.02414) # both report this helping with stabilizing training self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if self.learned_pos_emb: self.wpe = torch.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': print( f'You are using {config.init_device=}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.' ) self.apply(self.param_init_fn) self.is_causal = not self.prefix_lm # define attn mask 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) # Print verbose info 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.') def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value: nn.Embedding): self.wte = value @torch.no_grad() def _attn_bias( self, device: torch.device, dtype: torch.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 # flash does not support prefix_lm and will incorporate any # attention_mask inside the attention module if self.attn_impl == 'flash': return self.attn_bias, attention_mask if self.attn_bias is not None: # .to(*args, **kwargs) is a no-op if tensor is already on # specified device or of specificed dtype self.attn_bias = self.attn_bias.to(dtype=dtype, device=device) attn_bias = self.attn_bias # If using torch or triton, we incorporate the prefix_mask (if appropriate) if self.prefix_lm: assert isinstance(attn_bias, torch.Tensor) # pyright assert isinstance(prefix_mask, torch.Tensor) # pyright attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask) # If using torch or triton, we incorporate sequence_id (if appropriate) if self.attn_uses_sequence_id and sequence_id is not None: assert isinstance(attn_bias, torch.Tensor) # pyright attn_bias = self._apply_sequence_id(attn_bias, sequence_id) # If using torch or triton, we incorporate attention_mask. This will output # None in place of attention_mask since it will not be further needed in the # attention modules. 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: # clamp to 0 necessary for torch 2.0 compile() _s_k = max(0, attn_bias.size(-1) - s_k) 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}' ) # select seq_len subset of attn mask attn_bias = attn_bias[..., :seq_len, :seq_len] # Mix the causal max and the bidirectional mask to get the full # allowable attention (i.e. full = not accounting for padding yet) 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}' ) # select seq_len subset of attn mask attn_bias = attn_bias[..., :seq_len, :seq_len] # Restrict attention to tokens that share the same value # in sequence_id 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, inputs_embeds: Optional[torch.Tensor] = 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 attention_mask is not None: attention_mask = attention_mask.bool( ) # type: ignore (TODO to figure out the right type here) if prefix_mask is not None: prefix_mask = prefix_mask.bool( ) # type: ignore (TODO to figure out the right type here) # These args are passed in by keyword in huggingface's generate function # https://github.com/huggingface/transformers/blob/68287689f2f0d8b7063c400230b3766987abf18d/src/transformers/generation/utils.py#L2201-L2206 # but have not yet been fully implemented in MPTModel if not return_dict: raise NotImplementedError( 'return_dict False is not implemented yet for MPT') if output_attentions: if self.attn_impl != 'torch': raise NotImplementedError( 'output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.' ) 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.' ) # Raise a not implemented error if input_embeds is not None (this is an arg in huggingface transformers and we need to support it for PEFT) if inputs_embeds is not None: raise NotImplementedError( 'inputs_embeds is not implemented for MPT.') 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.' ) 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) # type: ignore if self.learned_pos_emb: 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)=}; {self.config.n_layers=}).' ) # For attn_impl: triton and flash the past key tensor spec is (batch, seq, dim). # For attn_impl: torch the past key tensor spec is (batch, heads, head_dim, seq). # Here we shift position embedding using the `seq` dim of the past key past_position = past_key_values[0][0].size(1) if self.attn_impl == 'torch': past_position = past_key_values[0][0].size(3) 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 ' + f'{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: # adjust the position indices to account for padding tokens pos = torch.clamp( pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0, ) pos_emb = self.wpe(pos) # type: ignore x = tok_emb + pos_emb else: # ALiBi and NoPE use this path (RoPE will also use this path if / when enabled) x = tok_emb if self.embedding_fraction == 1: x = self.emb_drop(x) # type: ignore else: # this implementation is proposed on page 7 of the GLM-130B paper https://arxiv.org/abs/2210.02414 x_shrunk = (x * self.embedding_fraction) + ( x.detach() * (1 - self.embedding_fraction)) assert isinstance(self.emb_drop, nn.Module) # pyright x = self.emb_drop(x_shrunk) attn_bias, attention_mask = self._attn_bias( device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, ) # initialize the past key values cache if it should be used if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers) ] # type: ignore all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for b_idx, block in enumerate(self.blocks): # type: ignore if output_hidden_states: assert all_hidden_states is not None # pyright all_hidden_states = all_hidden_states + (x,) past_key_value = (past_key_values[b_idx] if past_key_values is not None else None) x, attn_weights, 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 if output_attentions: assert all_self_attns is not None # pyright all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) # type: ignore # add hidden states from the last decoder layer if output_hidden_states: assert all_hidden_states is not None # pyright all_hidden_states = all_hidden_states + (x,) return BaseModelOutputWithPast( last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns, ) # Param Initialization, needed for device='meta' fast initialization def param_init_fn(self, module: nn.Module): init_fn_name = self.config.init_config['name']
MODEL_INIT_REGISTRY[init_fn_name](
16
2023-10-09 15:32:15+00:00
16k
jiangjiechen/auction-arena
src/auctioneer_base.py
[ { "identifier": "Bidder", "path": "src/bidder_base.py", "snippet": "class Bidder(BaseModel):\n name: str\n model_name: str \n budget: int \n desire: str\n plan_strategy: str\n temperature: float = 0.7\n overestimate_percent: int = 10\n correct_belief: bool\n enable_learning: b...
import re import random import inflect from typing import List, Dict from langchain.prompts import PromptTemplate from langchain.chat_models import ChatOpenAI from langchain.callbacks import get_openai_callback from pydantic import BaseModel from collections import defaultdict from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) from .bidder_base import Bidder from .human_bidder import HumanBidder from .item_base import Item from .prompt_base import PARSE_BID_INSTRUCTION
12,958
msg = f"Thank you! This is the {p.ordinal(bid_round)} round of bidding for this item:\n{bidding_history}\n\nNow we have ${self.highest_bid} from {self.highest_bidder.name} for {self.cur_item.name}. The minimum increase over this highest bid is ${int(self.cur_item.price * self.min_markup_pct)}. Do I have any advance on ${self.highest_bid}?" return msg def ask_for_rebid(self, fail_msg: str, bid_price: int): return f"Your bid of ${bid_price} failed, because {fail_msg}: You must reconsider your bid." def get_hammer_msg(self): if self.highest_bidder is None: return f"Since no one bid on {self.cur_item.name}, we'll move on to the next item." else: return f"Sold! {self.cur_item} to {self.highest_bidder} at ${self.highest_bid}! The true value for {self.cur_item} is ${self.cur_item.true_value}."# Thus {self.highest_bidder}'s profit by winning this item is ${self.cur_item.true_value - self.highest_bid}." def check_hammer(self, bid_round: int): # check if the item is sold self.fail_to_sell = False num_bid = self._num_bids_in_round(bid_round) # highest_bidder has already been updated in record_bid(). # so when num_bid == 0 & highest_bidder is None, it means no one bid on this item if self.highest_bidder is None: if num_bid == 0: # failed to sell, as there is no highest bidder self.fail_to_sell = True if self.enable_discount and bid_round < 3: # lower the starting price by 50%. discoutn only applies to the first 3 rounds self.cur_item.lower_price(0.5) is_sold = False else: is_sold = True else: # won't happen raise ValueError(f"highest_bidder is None but num_bid is {num_bid}") else: if self.prev_round_max_bid < 0 and num_bid == 1: # only one bidder in the first round is_sold = True else: self.prev_round_max_bid = self.highest_bid is_sold = self._num_bids_in_round(bid_round) == 0 return is_sold def _num_bids_in_round(self, bid_round: int): # check if there is no bid in the current round cnt = 0 for hist in self.bidding_history[bid_round]: if hist['bid'] > 0: cnt += 1 return cnt def hammer_fall(self): print(f'* Sold! {self.cur_item} (${self.cur_item.true_value}) goes to {self.highest_bidder} at ${self.highest_bid}.') self.auction_logs[f"{self.cur_item.get_desc()}"].append({ 'bidder': self.highest_bidder, 'bid': f"{self.highest_bid} (${self.cur_item.true_value})", # no need for the first $, as it will be added in the self.log() 'bid_round': 'Hammer price (true value)'}) self.cur_item = None self.highest_bidder = None self.highest_bid = -1 self.bidding_history = defaultdict(list) self.prev_round_max_bid = -1 self.fail_to_sell = False def end_auction(self): return len(self.items_queue) == 0 def gather_all_status(self, bidders: List[Bidder]): status = {} for bidder in bidders: status[bidder.name] = { 'profit': bidder.profit, 'items_won': bidder.items_won } return status def parse_bid(self, text: str): prompt = PARSE_BID_INSTRUCTION.format(response=text) with get_openai_callback() as cb: llm = ChatOpenAI(model='gpt-3.5-turbo-0613', temperature=0) result = llm([HumanMessage(content=prompt)]).content self.openai_cost += cb.total_cost bid_number = re.findall(r'\$?\d+', result.replace(',', '')) # find number in the result if '-1' in result: return -1 elif len(bid_number) > 0: return int(bid_number[-1].replace('$', '')) else: print('* Rebid:', text) return None def log(self, bidder_personal_reports: list = [], show_model_name=True): ''' example Apparatus H, starting at $1000. 1st bid: Bidder 1 (gpt-3.5-turbo-16k-0613): $1200 Bidder 2 (gpt-3.5-turbo-16k-0613): $1100 Bidder 3 (gpt-3.5-turbo-16k-0613): Withdrawn Bidder 4 (gpt-3.5-turbo-16k-0613): $1200 2nd bid: Bidder 1 (gpt-3.5-turbo-16k-0613): Withdrawn Bidder 2 (gpt-3.5-turbo-16k-0613): Withdrawn Hammer price: Bidder 4 (gpt-3.5-turbo-16k-0613): $1200 ''' markdown_output = "## Auction Log\n\n" for i, (item, bids) in enumerate(self.auction_logs.items()): markdown_output += f"### {i+1}. {item}\n\n" cur_bid_round = -1 for i, bid in enumerate(bids): if bid['bid_round'] != cur_bid_round: cur_bid_round = bid['bid_round'] if isinstance(bid['bid_round'], int): markdown_output += f"\n#### {p.ordinal(bid['bid_round']+1)} bid:\n\n" else: markdown_output += f"\n#### {bid['bid_round']}:\n\n" bid_price = f"${bid['bid']}" if bid['bid'] != -1 else 'Withdrew'
p = inflect.engine() class Auctioneer(BaseModel): enable_discount: bool = False items: List[Item] = [] cur_item: Item = None highest_bidder: Bidder = None highest_bid: int = -1 bidding_history = defaultdict(list) # history about the bidding war of one item items_queue: List[Item] = [] # updates when a item is taken. auction_logs = defaultdict(list) # history about the bidding war of all items openai_cost = 0 prev_round_max_bid: int = -1 min_bid: int = 0 fail_to_sell = False min_markup_pct = 0.1 class Config: arbitrary_types_allowed = True def init_items(self, items: List[Item]): for item in items: # reset discounted price item.reset_price() self.items = items self.items_queue = items.copy() def summarize_items_info(self): desc = '' for item in self.items: desc += f"- {item.get_desc()}\n" return desc.strip() def present_item(self): cur_item = self.items_queue.pop(0) self.cur_item = cur_item return cur_item def shuffle_items(self): random.shuffle(self.items) self.items_queue = self.items.copy() def record_bid(self, bid_info: dict, bid_round: int): ''' Save the bidding history for each round, log the highest bidder and highest bidding ''' # bid_info: {'bidder': xxx, 'bid': xxx, 'raw_msg': xxx} self.bidding_history[bid_round].append(bid_info) for hist in self.bidding_history[bid_round]: if hist['bid'] > 0: if self.highest_bid < hist['bid']: self.highest_bid = hist['bid'] self.highest_bidder = hist['bidder'] elif self.highest_bid == hist['bid']: # random if there's a tie self.highest_bidder = random.choice([self.highest_bidder, hist['bidder']]) self.auction_logs[f"{self.cur_item.get_desc()}"].append( {'bidder': bid_info['bidder'], 'bid': bid_info['bid'], 'bid_round': bid_round}) def _biddings_to_string(self, bid_round: int): ''' Return a string that summarizes the bidding history in a round ''' # bid_hist_text = '' if bid_round == 0 else f'- {self.highest_bidder}: ${self.highest_bid}\n' bid_hist_text = '' for js in self.bidding_history[bid_round]: if js['bid'] < 0: bid_hist_text += f"- {js['bidder']} withdrew\n" else: bid_hist_text += f"- {js['bidder']}: ${js['bid']}\n" return bid_hist_text.strip() def all_bidding_history_to_string(self): bid_hist_text = '' for bid_round in self.bidding_history: bid_hist_text += f"Round {bid_round}:\n{self._biddings_to_string(bid_round)}\n\n" return bid_hist_text.strip() def ask_for_bid(self, bid_round: int): ''' Ask for bid, return the message to be sent to bidders ''' if self.highest_bidder is None: if bid_round > 0: msg = f"Seeing as we've had no takers at the initial price, we're going to lower the starting bid to ${self.cur_item.price} for {self.cur_item.name} to spark some interest! Do I have any takers?" else: remaining_items = [self.cur_item.name] + [item.name for item in self.items_queue] msg = f"Attention, bidders! {len(remaining_items)} item(s) left, they are: {', '.join(remaining_items)}.\n\nNow, please bid on {self.cur_item}. The starting price for bidding for {self.cur_item} is ${self.cur_item.price}. Anyone interested in this item?" else: bidding_history = self._biddings_to_string(bid_round - 1) msg = f"Thank you! This is the {p.ordinal(bid_round)} round of bidding for this item:\n{bidding_history}\n\nNow we have ${self.highest_bid} from {self.highest_bidder.name} for {self.cur_item.name}. The minimum increase over this highest bid is ${int(self.cur_item.price * self.min_markup_pct)}. Do I have any advance on ${self.highest_bid}?" return msg def ask_for_rebid(self, fail_msg: str, bid_price: int): return f"Your bid of ${bid_price} failed, because {fail_msg}: You must reconsider your bid." def get_hammer_msg(self): if self.highest_bidder is None: return f"Since no one bid on {self.cur_item.name}, we'll move on to the next item." else: return f"Sold! {self.cur_item} to {self.highest_bidder} at ${self.highest_bid}! The true value for {self.cur_item} is ${self.cur_item.true_value}."# Thus {self.highest_bidder}'s profit by winning this item is ${self.cur_item.true_value - self.highest_bid}." def check_hammer(self, bid_round: int): # check if the item is sold self.fail_to_sell = False num_bid = self._num_bids_in_round(bid_round) # highest_bidder has already been updated in record_bid(). # so when num_bid == 0 & highest_bidder is None, it means no one bid on this item if self.highest_bidder is None: if num_bid == 0: # failed to sell, as there is no highest bidder self.fail_to_sell = True if self.enable_discount and bid_round < 3: # lower the starting price by 50%. discoutn only applies to the first 3 rounds self.cur_item.lower_price(0.5) is_sold = False else: is_sold = True else: # won't happen raise ValueError(f"highest_bidder is None but num_bid is {num_bid}") else: if self.prev_round_max_bid < 0 and num_bid == 1: # only one bidder in the first round is_sold = True else: self.prev_round_max_bid = self.highest_bid is_sold = self._num_bids_in_round(bid_round) == 0 return is_sold def _num_bids_in_round(self, bid_round: int): # check if there is no bid in the current round cnt = 0 for hist in self.bidding_history[bid_round]: if hist['bid'] > 0: cnt += 1 return cnt def hammer_fall(self): print(f'* Sold! {self.cur_item} (${self.cur_item.true_value}) goes to {self.highest_bidder} at ${self.highest_bid}.') self.auction_logs[f"{self.cur_item.get_desc()}"].append({ 'bidder': self.highest_bidder, 'bid': f"{self.highest_bid} (${self.cur_item.true_value})", # no need for the first $, as it will be added in the self.log() 'bid_round': 'Hammer price (true value)'}) self.cur_item = None self.highest_bidder = None self.highest_bid = -1 self.bidding_history = defaultdict(list) self.prev_round_max_bid = -1 self.fail_to_sell = False def end_auction(self): return len(self.items_queue) == 0 def gather_all_status(self, bidders: List[Bidder]): status = {} for bidder in bidders: status[bidder.name] = { 'profit': bidder.profit, 'items_won': bidder.items_won } return status def parse_bid(self, text: str): prompt = PARSE_BID_INSTRUCTION.format(response=text) with get_openai_callback() as cb: llm = ChatOpenAI(model='gpt-3.5-turbo-0613', temperature=0) result = llm([HumanMessage(content=prompt)]).content self.openai_cost += cb.total_cost bid_number = re.findall(r'\$?\d+', result.replace(',', '')) # find number in the result if '-1' in result: return -1 elif len(bid_number) > 0: return int(bid_number[-1].replace('$', '')) else: print('* Rebid:', text) return None def log(self, bidder_personal_reports: list = [], show_model_name=True): ''' example Apparatus H, starting at $1000. 1st bid: Bidder 1 (gpt-3.5-turbo-16k-0613): $1200 Bidder 2 (gpt-3.5-turbo-16k-0613): $1100 Bidder 3 (gpt-3.5-turbo-16k-0613): Withdrawn Bidder 4 (gpt-3.5-turbo-16k-0613): $1200 2nd bid: Bidder 1 (gpt-3.5-turbo-16k-0613): Withdrawn Bidder 2 (gpt-3.5-turbo-16k-0613): Withdrawn Hammer price: Bidder 4 (gpt-3.5-turbo-16k-0613): $1200 ''' markdown_output = "## Auction Log\n\n" for i, (item, bids) in enumerate(self.auction_logs.items()): markdown_output += f"### {i+1}. {item}\n\n" cur_bid_round = -1 for i, bid in enumerate(bids): if bid['bid_round'] != cur_bid_round: cur_bid_round = bid['bid_round'] if isinstance(bid['bid_round'], int): markdown_output += f"\n#### {p.ordinal(bid['bid_round']+1)} bid:\n\n" else: markdown_output += f"\n#### {bid['bid_round']}:\n\n" bid_price = f"${bid['bid']}" if bid['bid'] != -1 else 'Withdrew'
if isinstance(bid['bidder'], Bidder) or isinstance(bid['bidder'], HumanBidder):
1
2023-10-08 09:30:57+00:00
16k
SH1ROd/Bert-VITS2-Integration-train-txt-infer
train_ms.py
[ { "identifier": "TextAudioSpeakerLoader", "path": "data_utils.py", "snippet": "class TextAudioSpeakerLoader(torch.utils.data.Dataset):\n \"\"\"\n 1) loads audio, speaker_id, text pairs\n 2) normalizes text and converts them to sequences of integers\n 3) computes spectrograms from...
import os import json import argparse import itertools import math import torch import shutil import torch.multiprocessing as mp import torch.distributed as dist import logging import commons import utils from torch import nn, optim from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from data_utils import ( TextAudioSpeakerLoader, TextAudioSpeakerCollate, DistributedBucketSampler ) from models import ( SynthesizerTrn, MultiPeriodDiscriminator, DurationDiscriminator, ) from losses import ( generator_loss, discriminator_loss, feature_loss, kl_loss ) from mel_processing import mel_spectrogram_torch, spec_to_mel_torch from text.symbols import symbols
10,870
_, optim_g, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g, skip_optimizer=not hps.cont) _, optim_d, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d, skip_optimizer=not hps.cont) epoch_str = max(epoch_str, 1) global_step = (epoch_str - 1) * len(train_loader) except Exception as e: print(e) epoch_str = 1 global_step = 0 else: _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "G_*.pth"), net_g, optim_g, True) _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "D_*.pth"), net_d, optim_d, True) scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) if net_dur_disc is not None: scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR(optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str-2) else: scheduler_dur_disc = None scaler = GradScaler(enabled=hps.train.fp16_run) for epoch in range(epoch_str, hps.train.epochs + 1): if rank == 0: train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval],role=role) else: train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None, role=role) scheduler_g.step() scheduler_d.step() if net_dur_disc is not None: scheduler_dur_disc.step() def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers, role): net_g, net_d, net_dur_disc = nets optim_g, optim_d, optim_dur_disc = optims scheduler_g, scheduler_d, scheduler_dur_disc = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() if net_dur_disc is not None: net_dur_disc.train() for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) speakers = speakers.cuda(rank, non_blocking=True) tone = tone.cuda(rank, non_blocking=True) language = language.cuda(rank, non_blocking=True) bert = bert.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): y_hat, l_length, attn, ids_slice, x_mask, z_mask, \ (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax ) y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach()) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
logging.getLogger('numba').setLevel(logging.WARNING) torch.backends.cudnn.benchmark = True torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.set_float32_matmul_precision('medium') 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'] = '65280' hps = utils.get_hparams() role='' for t in hps.data.spk2id.items(): role=t[0] if not hps.cont: folder_path = f"./logs/{role}" if not os.path.exists(folder_path): os.makedirs(folder_path) print(f"文件夹 '{role}' 已创建在 './logs/' 目录下。") else: print(f"文件夹 '{role}' 已经存在于 './logs/' 目录下。") shutil.copy('./pretrained_models/D_0.pth',f'./logs/{role}/D_0.pth') shutil.copy('./pretrained_models/G_0.pth',f'./logs/{role}/G_0.pth') shutil.copy('./pretrained_models/DUR_0.pth',f'./logs/{role}/DUR_0.pth') mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps, role)) def run(rank, n_gpus, hps, role): 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= 'gloo' if os.name == 'nt' else 'nccl', init_method='env://', world_size=n_gpus, rank=rank) torch.manual_seed(hps.train.seed) torch.cuda.set_device(rank) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True) collate_fn = TextAudioSpeakerCollate() train_loader = DataLoader(train_dataset, num_workers=2, 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=0, shuffle=False, batch_size=1, pin_memory=True, drop_last=False, collate_fn=collate_fn) 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 net_dur_disc = DurationDiscriminator( hps.model.hidden_channels, hps.model.hidden_channels, 3, 0.1, gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, ).cuda(rank) 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 net_g = SynthesizerTrn( len(symbols), hps.data.filter_length // 2 + 1, hps.train.segment_size // hps.data.hop_length, n_speakers=hps.data.n_speakers, mas_noise_scale_initial = mas_noise_scale_initial, noise_scale_delta = noise_scale_delta, **hps.model).cuda(rank) freeze_enc = getattr(hps.model, "freeze_enc", False) if freeze_enc: print("freeze encoder !!!") for param in net_g.enc_p.parameters(): param.requires_grad = False net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) optim_g = torch.optim.AdamW( filter(lambda p: p.requires_grad, net_g.parameters()), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps) optim_d = torch.optim.AdamW( net_d.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps) if net_dur_disc is not None: optim_dur_disc = torch.optim.AdamW( net_dur_disc.parameters(), hps.train.learning_rate, betas=hps.train.betas, eps=hps.train.eps) else: optim_dur_disc = None net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True) net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True) if net_dur_disc is not None: net_dur_disc = DDP(net_dur_disc, device_ids=[rank], find_unused_parameters=True) pretrain_dir = None if pretrain_dir is None: try: if net_dur_disc is not None: _, optim_dur_disc, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, skip_optimizer=not hps.cont) _, optim_g, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, optim_g, skip_optimizer=not hps.cont) _, optim_d, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, optim_d, skip_optimizer=not hps.cont) epoch_str = max(epoch_str, 1) global_step = (epoch_str - 1) * len(train_loader) except Exception as e: print(e) epoch_str = 1 global_step = 0 else: _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "G_*.pth"), net_g, optim_g, True) _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "D_*.pth"), net_d, optim_d, True) scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) if net_dur_disc is not None: scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR(optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str-2) else: scheduler_dur_disc = None scaler = GradScaler(enabled=hps.train.fp16_run) for epoch in range(epoch_str, hps.train.epochs + 1): if rank == 0: train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval],role=role) else: train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None, role=role) scheduler_g.step() scheduler_d.step() if net_dur_disc is not None: scheduler_dur_disc.step() def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers, role): net_g, net_d, net_dur_disc = nets optim_g, optim_d, optim_dur_disc = optims scheduler_g, scheduler_d, scheduler_dur_disc = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() if net_dur_disc is not None: net_dur_disc.train() for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) speakers = speakers.cuda(rank, non_blocking=True) tone = tone.cuda(rank, non_blocking=True) language = language.cuda(rank, non_blocking=True) bert = bert.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): y_hat, l_length, attn, ids_slice, x_mask, z_mask, \ (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax ) y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach()) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel
loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
9
2023-10-10 02:23:23+00:00
16k
sakemin/cog-musicgen-chord
audiocraft/modules/conditioners.py
[ { "identifier": "ChromaExtractor", "path": "audiocraft/modules/chroma.py", "snippet": "class ChromaExtractor(nn.Module):\n \"\"\"Chroma extraction and quantization.\n\n Args:\n sample_rate (int): Sample rate for the chroma extraction.\n n_chroma (int): Number of chroma bins for the c...
from collections import defaultdict from copy import deepcopy from dataclasses import dataclass, field from itertools import chain from pathlib import Path from num2words import num2words from transformers import RobertaTokenizer, T5EncoderModel, T5Tokenizer # type: ignore from torch import nn from torch.nn.utils.rnn import pad_sequence from .chroma import ChromaExtractor from .chord_chroma import ChordExtractor from .streaming import StreamingModule from .transformer import create_sin_embedding from ..data.audio import audio_read from ..data.audio_dataset import SegmentInfo from ..data.audio_utils import convert_audio from ..environment import AudioCraftEnvironment from ..quantization import ResidualVectorQuantizer from ..utils.autocast import TorchAutocast from ..utils.cache import EmbeddingCache from ..utils.utils import collate, hash_trick, length_to_mask, load_clap_state_dict, warn_once from .btc.utils import chords from demucs import pretrained from audiocraft.data.audio_dataset import AudioDataset from demucs.apply import apply_model from demucs.audio import convert_audio from demucs import pretrained from audiocraft.data.audio_dataset import AudioDataset from demucs.apply import apply_model from demucs.audio import convert_audio import logging import math import random import re import typing as tp import warnings import einops import spacy import torch import torch.nn.functional as F import numpy as np import laion_clap # type: ignore
13,447
entries: tp.List[str] = [xi if xi is not None else "" for xi in x] if self.normalize_text: _, _, entries = self.text_normalizer(entries, return_text=True) if self.word_dropout > 0. and self.training: new_entries = [] for entry in entries: words = [word for word in entry.split(" ") if random.random() >= self.word_dropout] new_entries.append(" ".join(words)) entries = new_entries empty_idx = torch.LongTensor([i for i, xi in enumerate(entries) if xi == ""]) inputs = self.t5_tokenizer(entries, return_tensors='pt', padding=True).to(self.device) mask = inputs['attention_mask'] mask[empty_idx, :] = 0 # zero-out index where the input is non-existant return inputs def forward(self, inputs: tp.Dict[str, torch.Tensor]) -> ConditionType: mask = inputs['attention_mask'] with torch.set_grad_enabled(self.finetune), self.autocast: embeds = self.t5(**inputs).last_hidden_state embeds = self.output_proj(embeds.to(self.output_proj.weight)) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class WaveformConditioner(BaseConditioner): """Base class for all conditioners that take a waveform as input. Classes that inherit must implement `_get_wav_embedding` that outputs a continuous tensor, and `_downsampling_factor` that returns the down-sampling factor of the embedding model. Args: dim (int): The internal representation dimension. output_dim (int): Output dimension. device (tp.Union[torch.device, str]): Device. """ def __init__(self, dim: int, output_dim: int, device: tp.Union[torch.device, str]): super().__init__(dim, output_dim) self.device = device # if False no masking is done, used in ChromaStemConditioner when completing by periodicity a sample. self._use_masking = True def tokenize(self, x: WavCondition) -> WavCondition: wav, length, sample_rate, path, seek_time = x assert length is not None return WavCondition(wav.to(self.device), length.to(self.device), sample_rate, path, seek_time) def _get_wav_embedding(self, x: WavCondition) -> torch.Tensor: """Gets as input a WavCondition and returns a dense embedding.""" raise NotImplementedError() def _downsampling_factor(self): """Returns the downsampling factor of the embedding model.""" raise NotImplementedError() def forward(self, x: WavCondition) -> ConditionType: """Extract condition embedding and mask from a waveform and its metadata. Args: x (WavCondition): Waveform condition containing raw waveform and metadata. Returns: ConditionType: a dense vector representing the conditioning along with its mask """ wav, lengths, *_ = x with torch.no_grad(): embeds = self._get_wav_embedding(x) embeds = embeds.to(self.output_proj.weight) embeds = self.output_proj(embeds) if lengths is not None and self._use_masking: lengths = lengths / self._downsampling_factor() mask = length_to_mask(lengths, max_len=embeds.shape[1]).int() # type: ignore else: mask = torch.ones_like(embeds[..., 0]) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class ChromaStemConditioner(WaveformConditioner): """Chroma conditioner based on stems. The ChromaStemConditioner uses DEMUCS to first filter out drums and bass, as the drums and bass often dominate the chroma leading to the chroma features not containing information about the melody. Args: output_dim (int): Output dimension for the conditioner. sample_rate (int): Sample rate for the chroma extractor. n_chroma (int): Number of chroma bins for the chroma extractor. radix2_exp (int): Size of stft window for the chroma extractor (power of 2, e.g. 12 -> 2^12). duration (int): duration used during training. This is later used for correct padding in case we are using chroma as prefix. match_len_on_eval (bool, optional): if True then all chromas are padded to the training duration. Defaults to False. eval_wavs (str, optional): path to a dataset manifest with waveform, this waveforms are used as conditions during eval (for cases where we don't want to leak test conditions like MusicCaps). Defaults to None. n_eval_wavs (int, optional): limits the number of waveforms used for conditioning. Defaults to 0. device (tp.Union[torch.device, str], optional): Device for the conditioner. **kwargs: Additional parameters for the chroma extractor. """ def __init__(self, output_dim: int, sample_rate: int, n_chroma: int, radix2_exp: int, duration: float, match_len_on_eval: bool = True, eval_wavs: tp.Optional[str] = None, n_eval_wavs: int = 0, cache_path: tp.Optional[tp.Union[str, Path]] = None, device: tp.Union[torch.device, str] = 'cpu', **kwargs): super().__init__(dim=n_chroma, output_dim=output_dim, device=device) self.autocast = TorchAutocast(enabled=device != 'cpu', device_type=self.device, dtype=torch.float32) self.sample_rate = sample_rate self.match_len_on_eval = match_len_on_eval if match_len_on_eval: self._use_masking = False self.duration = duration self.__dict__['demucs'] = pretrained.get_model('htdemucs').to(device) stem_sources: list = self.demucs.sources # type: ignore self.stem_indices = torch.LongTensor([stem_sources.index('vocals'), stem_sources.index('other')]).to(device) self.chroma = ChromaExtractor(sample_rate=sample_rate, n_chroma=n_chroma, radix2_exp=radix2_exp, **kwargs).to(device) self.chroma_len = self._get_chroma_len() self.eval_wavs: tp.Optional[torch.Tensor] = self._load_eval_wavs(eval_wavs, n_eval_wavs) self.cache = None if cache_path is not None:
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. logger = logging.getLogger(__name__) TextCondition = tp.Optional[str] # a text condition can be a string or None (if doesn't exist) ConditionType = tp.Tuple[torch.Tensor, torch.Tensor] # condition, mask class WavCondition(tp.NamedTuple): wav: torch.Tensor length: torch.Tensor sample_rate: tp.List[int] path: tp.List[tp.Optional[str]] = [] seek_time: tp.List[tp.Optional[float]] = [] class WavChordTextCondition(tp.NamedTuple): wav: tp.Union[torch.Tensor,str,tp.List[str]] length: torch.Tensor sample_rate: tp.List[int] path: tp.List[tp.Optional[str]] = [] seek_time: tp.List[tp.Optional[float]] = [] bpm : tp.List[tp.Optional[tp.Union[int, float]]] = [] meter : tp.List[tp.Optional[int]] = [] class JointEmbedCondition(tp.NamedTuple): wav: torch.Tensor text: tp.List[tp.Optional[str]] length: torch.Tensor sample_rate: tp.List[int] path: tp.List[tp.Optional[str]] = [] seek_time: tp.List[tp.Optional[float]] = [] @dataclass class ConditioningAttributes: text: tp.Dict[str, tp.Optional[str]] = field(default_factory=dict) wav: tp.Dict[str, tp.Union[WavCondition,WavChordTextCondition]] = field(default_factory=dict) joint_embed: tp.Dict[str, JointEmbedCondition] = field(default_factory=dict) def __getitem__(self, item): return getattr(self, item) @property def text_attributes(self): return self.text.keys() @property def wav_attributes(self): return self.wav.keys() @property def joint_embed_attributes(self): return self.joint_embed.keys() @property def attributes(self): return { "text": self.text_attributes, "wav": self.wav_attributes, "joint_embed": self.joint_embed_attributes, } def to_flat_dict(self): return { **{f"text.{k}": v for k, v in self.text.items()}, **{f"wav.{k}": v for k, v in self.wav.items()}, **{f"joint_embed.{k}": v for k, v in self.joint_embed.items()} } @classmethod def from_flat_dict(cls, x): out = cls() for k, v in x.items(): kind, att = k.split(".") out[kind][att] = v return out class SegmentWithAttributes(SegmentInfo): """Base class for all dataclasses that are used for conditioning. All child classes should implement `to_condition_attributes` that converts the existing attributes to a dataclass of type ConditioningAttributes. """ def to_condition_attributes(self) -> ConditioningAttributes: raise NotImplementedError() def nullify_condition(condition: ConditionType, dim: int = 1): """Transform an input condition to a null condition. The way it is done by converting it to a single zero vector similarly to how it is done inside WhiteSpaceTokenizer and NoopTokenizer. Args: condition (ConditionType): A tuple of condition and mask (tuple[torch.Tensor, torch.Tensor]) dim (int): The dimension that will be truncated (should be the time dimension) WARNING!: dim should not be the batch dimension! Returns: ConditionType: A tuple of null condition and mask """ assert dim != 0, "dim cannot be the batch dimension!" assert isinstance(condition, tuple) and \ isinstance(condition[0], torch.Tensor) and \ isinstance(condition[1], torch.Tensor), "'nullify_condition' got an unexpected input type!" cond, mask = condition B = cond.shape[0] last_dim = cond.dim() - 1 out = cond.transpose(dim, last_dim) out = 0. * out[..., :1] out = out.transpose(dim, last_dim) mask = torch.zeros((B, 1), device=out.device).int() assert cond.dim() == out.dim() return out, mask def nullify_wav(cond: tp.Union[WavCondition,WavChordTextCondition]) -> tp.Union[WavCondition,WavChordTextCondition]: """Transform a WavCondition to a nullified WavCondition. It replaces the wav by a null tensor, forces its length to 0, and replaces metadata by dummy attributes. Args: cond (WavCondition): Wav condition with wav, tensor of shape [B, T]. Returns: WavCondition: Nullified wav condition. """ if not isinstance(cond, WavChordTextCondition): null_wav, _ = nullify_condition((cond.wav, torch.zeros_like(cond.wav)), dim=cond.wav.dim() - 1) return WavCondition( wav=null_wav, length=torch.tensor([0] * cond.wav.shape[0], device=cond.wav.device), sample_rate=cond.sample_rate, path=[None] * cond.wav.shape[0], seek_time=[None] * cond.wav.shape[0], ) else: return WavChordTextCondition( wav=['N']* len(cond.wav), length=torch.tensor([0] * len(cond.wav), device=cond.length.device), sample_rate=cond.sample_rate, path=[None], seek_time=[None], bpm = cond.bpm, meter = cond.meter ) def nullify_joint_embed(embed: JointEmbedCondition) -> JointEmbedCondition: """Nullify the joint embedding condition by replacing it by a null tensor, forcing its length to 0, and replacing metadata by dummy attributes. Args: cond (JointEmbedCondition): Joint embedding condition with wav and text, wav tensor of shape [B, C, T]. """ null_wav, _ = nullify_condition((embed.wav, torch.zeros_like(embed.wav)), dim=embed.wav.dim() - 1) return JointEmbedCondition( wav=null_wav, text=[None] * len(embed.text), length=torch.LongTensor([0]).to(embed.wav.device), sample_rate=embed.sample_rate, path=[None] * embed.wav.shape[0], seek_time=[0] * embed.wav.shape[0], ) class Tokenizer: """Base tokenizer implementation (in case we want to introduce more advances tokenizers in the future). """ def __call__(self, texts: tp.List[tp.Optional[str]]) -> tp.Tuple[torch.Tensor, torch.Tensor]: raise NotImplementedError() class WhiteSpaceTokenizer(Tokenizer): """This tokenizer should be used for natural language descriptions. For example: ["he didn't, know he's going home.", 'shorter sentence'] => [[78, 62, 31, 4, 78, 25, 19, 34], [59, 77, 0, 0, 0, 0, 0, 0]] """ PUNCTUATION = "?:!.,;" def __init__(self, n_bins: int, pad_idx: int = 0, language: str = "en_core_web_sm", lemma: bool = True, stopwords: bool = True) -> None: self.n_bins = n_bins self.pad_idx = pad_idx self.lemma = lemma self.stopwords = stopwords try: self.nlp = spacy.load(language) except IOError: spacy.cli.download(language) # type: ignore self.nlp = spacy.load(language) @tp.no_type_check def __call__(self, texts: tp.List[tp.Optional[str]], return_text: bool = False) -> tp.Tuple[torch.Tensor, torch.Tensor]: """Take a list of strings and convert them to a tensor of indices. Args: texts (list[str]): List of strings. return_text (bool, optional): Whether to return text as additional tuple item. Defaults to False. Returns: tuple[torch.Tensor, torch.Tensor]: - Indices of words in the LUT. - And a mask indicating where the padding tokens are """ output, lengths = [], [] texts = deepcopy(texts) for i, text in enumerate(texts): # if current sample doesn't have a certain attribute, replace with pad token if text is None: output.append(torch.Tensor([self.pad_idx])) lengths.append(0) continue # convert numbers to words text = re.sub(r"(\d+)", lambda x: num2words(int(x.group(0))), text) # type: ignore # normalize text text = self.nlp(text) # type: ignore # remove stopwords if self.stopwords: text = [w for w in text if not w.is_stop] # type: ignore # remove punctuation text = [w for w in text if w.text not in self.PUNCTUATION] # type: ignore # lemmatize if needed text = [getattr(t, "lemma_" if self.lemma else "text") for t in text] # type: ignore texts[i] = " ".join(text) lengths.append(len(text)) # convert to tensor tokens = torch.Tensor([hash_trick(w, self.n_bins) for w in text]) output.append(tokens) mask = length_to_mask(torch.IntTensor(lengths)).int() padded_output = pad_sequence(output, padding_value=self.pad_idx).int().t() if return_text: return padded_output, mask, texts # type: ignore return padded_output, mask class NoopTokenizer(Tokenizer): """This tokenizer should be used for global conditioners such as: artist, genre, key, etc. The difference between this and WhiteSpaceTokenizer is that NoopTokenizer does not split strings, so "Jeff Buckley" will get it's own index. Whereas WhiteSpaceTokenizer will split it to ["Jeff", "Buckley"] and return an index per word. For example: ["Queen", "ABBA", "Jeff Buckley"] => [43, 55, 101] ["Metal", "Rock", "Classical"] => [0, 223, 51] """ def __init__(self, n_bins: int, pad_idx: int = 0): self.n_bins = n_bins self.pad_idx = pad_idx def __call__(self, texts: tp.List[tp.Optional[str]]) -> tp.Tuple[torch.Tensor, torch.Tensor]: output, lengths = [], [] for text in texts: # if current sample doesn't have a certain attribute, replace with pad token if text is None: output.append(self.pad_idx) lengths.append(0) else: output.append(hash_trick(text, self.n_bins)) lengths.append(1) tokens = torch.LongTensor(output).unsqueeze(1) mask = length_to_mask(torch.IntTensor(lengths)).int() return tokens, mask class BaseConditioner(nn.Module): """Base model for all conditioner modules. We allow the output dim to be different than the hidden dim for two reasons: 1) keep our LUTs small when the vocab is large; 2) make all condition dims consistent. Args: dim (int): Hidden dim of the model. output_dim (int): Output dim of the conditioner. """ def __init__(self, dim: int, output_dim: int): super().__init__() self.dim = dim self.output_dim = output_dim self.output_proj = nn.Linear(dim, output_dim) def tokenize(self, *args, **kwargs) -> tp.Any: """Should be any part of the processing that will lead to a synchronization point, e.g. BPE tokenization with transfer to the GPU. The returned value will be saved and return later when calling forward(). """ raise NotImplementedError() def forward(self, inputs: tp.Any) -> ConditionType: """Gets input that should be used as conditioning (e.g, genre, description or a waveform). Outputs a ConditionType, after the input data was embedded as a dense vector. Returns: ConditionType: - A tensor of size [B, T, D] where B is the batch size, T is the length of the output embedding and D is the dimension of the embedding. - And a mask indicating where the padding tokens. """ raise NotImplementedError() class TextConditioner(BaseConditioner): ... class LUTConditioner(TextConditioner): """Lookup table TextConditioner. Args: n_bins (int): Number of bins. dim (int): Hidden dim of the model (text-encoder/LUT). output_dim (int): Output dim of the conditioner. tokenizer (str): Name of the tokenizer. pad_idx (int, optional): Index for padding token. Defaults to 0. """ def __init__(self, n_bins: int, dim: int, output_dim: int, tokenizer: str, pad_idx: int = 0): super().__init__(dim, output_dim) self.embed = nn.Embedding(n_bins, dim) self.tokenizer: Tokenizer if tokenizer == 'whitespace': self.tokenizer = WhiteSpaceTokenizer(n_bins, pad_idx=pad_idx) elif tokenizer == 'noop': self.tokenizer = NoopTokenizer(n_bins, pad_idx=pad_idx) else: raise ValueError(f"unrecognized tokenizer `{tokenizer}`.") def tokenize(self, x: tp.List[tp.Optional[str]]) -> tp.Tuple[torch.Tensor, torch.Tensor]: device = self.embed.weight.device tokens, mask = self.tokenizer(x) tokens, mask = tokens.to(device), mask.to(device) return tokens, mask def forward(self, inputs: tp.Tuple[torch.Tensor, torch.Tensor]) -> ConditionType: tokens, mask = inputs embeds = self.embed(tokens) embeds = self.output_proj(embeds) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class T5Conditioner(TextConditioner): """T5-based TextConditioner. Args: name (str): Name of the T5 model. output_dim (int): Output dim of the conditioner. finetune (bool): Whether to fine-tune T5 at train time. device (str): Device for T5 Conditioner. autocast_dtype (tp.Optional[str], optional): Autocast dtype. word_dropout (float, optional): Word dropout probability. normalize_text (bool, optional): Whether to apply text normalization. """ MODELS = ["t5-small", "t5-base", "t5-large", "t5-3b", "t5-11b", "google/flan-t5-small", "google/flan-t5-base", "google/flan-t5-large", "google/flan-t5-xl", "google/flan-t5-xxl"] MODELS_DIMS = { "t5-small": 512, "t5-base": 768, "t5-large": 1024, "t5-3b": 1024, "t5-11b": 1024, "google/flan-t5-small": 512, "google/flan-t5-base": 768, "google/flan-t5-large": 1024, "google/flan-t5-3b": 1024, "google/flan-t5-11b": 1024, } def __init__(self, name: str, output_dim: int, finetune: bool, device: str, autocast_dtype: tp.Optional[str] = 'float32', word_dropout: float = 0., normalize_text: bool = False): assert name in self.MODELS, f"Unrecognized t5 model name (should in {self.MODELS})" super().__init__(self.MODELS_DIMS[name], output_dim) self.device = device self.name = name self.finetune = finetune self.word_dropout = word_dropout if autocast_dtype is None or self.device == 'cpu': self.autocast = TorchAutocast(enabled=False) if self.device != 'cpu': logger.warning("T5 has no autocast, this might lead to NaN") else: dtype = getattr(torch, autocast_dtype) assert isinstance(dtype, torch.dtype) logger.info(f"T5 will be evaluated with autocast as {autocast_dtype}") self.autocast = TorchAutocast(enabled=True, device_type=self.device, dtype=dtype) # Let's disable logging temporarily because T5 will vomit some errors otherwise. # thanks https://gist.github.com/simon-weber/7853144 previous_level = logging.root.manager.disable logging.disable(logging.ERROR) with warnings.catch_warnings(): warnings.simplefilter("ignore") try: self.t5_tokenizer = T5Tokenizer.from_pretrained(name) t5 = T5EncoderModel.from_pretrained(name).train(mode=finetune) finally: logging.disable(previous_level) if finetune: self.t5 = t5 else: # this makes sure that the t5 models is not part # of the saved checkpoint self.__dict__['t5'] = t5.to(device) self.normalize_text = normalize_text if normalize_text: self.text_normalizer = WhiteSpaceTokenizer(1, lemma=True, stopwords=True) def tokenize(self, x: tp.List[tp.Optional[str]]) -> tp.Dict[str, torch.Tensor]: # if current sample doesn't have a certain attribute, replace with empty string entries: tp.List[str] = [xi if xi is not None else "" for xi in x] if self.normalize_text: _, _, entries = self.text_normalizer(entries, return_text=True) if self.word_dropout > 0. and self.training: new_entries = [] for entry in entries: words = [word for word in entry.split(" ") if random.random() >= self.word_dropout] new_entries.append(" ".join(words)) entries = new_entries empty_idx = torch.LongTensor([i for i, xi in enumerate(entries) if xi == ""]) inputs = self.t5_tokenizer(entries, return_tensors='pt', padding=True).to(self.device) mask = inputs['attention_mask'] mask[empty_idx, :] = 0 # zero-out index where the input is non-existant return inputs def forward(self, inputs: tp.Dict[str, torch.Tensor]) -> ConditionType: mask = inputs['attention_mask'] with torch.set_grad_enabled(self.finetune), self.autocast: embeds = self.t5(**inputs).last_hidden_state embeds = self.output_proj(embeds.to(self.output_proj.weight)) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class WaveformConditioner(BaseConditioner): """Base class for all conditioners that take a waveform as input. Classes that inherit must implement `_get_wav_embedding` that outputs a continuous tensor, and `_downsampling_factor` that returns the down-sampling factor of the embedding model. Args: dim (int): The internal representation dimension. output_dim (int): Output dimension. device (tp.Union[torch.device, str]): Device. """ def __init__(self, dim: int, output_dim: int, device: tp.Union[torch.device, str]): super().__init__(dim, output_dim) self.device = device # if False no masking is done, used in ChromaStemConditioner when completing by periodicity a sample. self._use_masking = True def tokenize(self, x: WavCondition) -> WavCondition: wav, length, sample_rate, path, seek_time = x assert length is not None return WavCondition(wav.to(self.device), length.to(self.device), sample_rate, path, seek_time) def _get_wav_embedding(self, x: WavCondition) -> torch.Tensor: """Gets as input a WavCondition and returns a dense embedding.""" raise NotImplementedError() def _downsampling_factor(self): """Returns the downsampling factor of the embedding model.""" raise NotImplementedError() def forward(self, x: WavCondition) -> ConditionType: """Extract condition embedding and mask from a waveform and its metadata. Args: x (WavCondition): Waveform condition containing raw waveform and metadata. Returns: ConditionType: a dense vector representing the conditioning along with its mask """ wav, lengths, *_ = x with torch.no_grad(): embeds = self._get_wav_embedding(x) embeds = embeds.to(self.output_proj.weight) embeds = self.output_proj(embeds) if lengths is not None and self._use_masking: lengths = lengths / self._downsampling_factor() mask = length_to_mask(lengths, max_len=embeds.shape[1]).int() # type: ignore else: mask = torch.ones_like(embeds[..., 0]) embeds = (embeds * mask.unsqueeze(-1)) return embeds, mask class ChromaStemConditioner(WaveformConditioner): """Chroma conditioner based on stems. The ChromaStemConditioner uses DEMUCS to first filter out drums and bass, as the drums and bass often dominate the chroma leading to the chroma features not containing information about the melody. Args: output_dim (int): Output dimension for the conditioner. sample_rate (int): Sample rate for the chroma extractor. n_chroma (int): Number of chroma bins for the chroma extractor. radix2_exp (int): Size of stft window for the chroma extractor (power of 2, e.g. 12 -> 2^12). duration (int): duration used during training. This is later used for correct padding in case we are using chroma as prefix. match_len_on_eval (bool, optional): if True then all chromas are padded to the training duration. Defaults to False. eval_wavs (str, optional): path to a dataset manifest with waveform, this waveforms are used as conditions during eval (for cases where we don't want to leak test conditions like MusicCaps). Defaults to None. n_eval_wavs (int, optional): limits the number of waveforms used for conditioning. Defaults to 0. device (tp.Union[torch.device, str], optional): Device for the conditioner. **kwargs: Additional parameters for the chroma extractor. """ def __init__(self, output_dim: int, sample_rate: int, n_chroma: int, radix2_exp: int, duration: float, match_len_on_eval: bool = True, eval_wavs: tp.Optional[str] = None, n_eval_wavs: int = 0, cache_path: tp.Optional[tp.Union[str, Path]] = None, device: tp.Union[torch.device, str] = 'cpu', **kwargs): super().__init__(dim=n_chroma, output_dim=output_dim, device=device) self.autocast = TorchAutocast(enabled=device != 'cpu', device_type=self.device, dtype=torch.float32) self.sample_rate = sample_rate self.match_len_on_eval = match_len_on_eval if match_len_on_eval: self._use_masking = False self.duration = duration self.__dict__['demucs'] = pretrained.get_model('htdemucs').to(device) stem_sources: list = self.demucs.sources # type: ignore self.stem_indices = torch.LongTensor([stem_sources.index('vocals'), stem_sources.index('other')]).to(device) self.chroma = ChromaExtractor(sample_rate=sample_rate, n_chroma=n_chroma, radix2_exp=radix2_exp, **kwargs).to(device) self.chroma_len = self._get_chroma_len() self.eval_wavs: tp.Optional[torch.Tensor] = self._load_eval_wavs(eval_wavs, n_eval_wavs) self.cache = None if cache_path is not None:
self.cache = EmbeddingCache(Path(cache_path) / 'wav', self.device,
10
2023-10-09 09:52:24+00:00
16k
RVC-Project/Retrieval-based-Voice-Conversion
rvc/modules/vc/modules.py
[ { "identifier": "Config", "path": "rvc/configs/config.py", "snippet": "class Config:\n def __new__(cls):\n if not hasattr(cls, \"_instance\"):\n cls._instance = super().__new__(cls)\n return cls._instance\n\n def __init__(self):\n self.device: str = \"cuda:0\"\n ...
import logging import os import traceback import numpy as np import soundfile as sf import torch from collections import OrderedDict from io import BytesIO from pathlib import Path from rvc.configs.config import Config from rvc.lib.audio import load_audio, wav2 from rvc.lib.infer_pack.models import ( SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono, SynthesizerTrnMs768NSFsid, SynthesizerTrnMs768NSFsid_nono, ) from rvc.modules.vc.pipeline import Pipeline from rvc.modules.vc.utils import *
11,768
logger: logging.Logger = logging.getLogger(__name__) class VC: def __init__(self): self.n_spk: any = None self.tgt_sr: int | None = None self.net_g = None
logger: logging.Logger = logging.getLogger(__name__) class VC: def __init__(self): self.n_spk: any = None self.tgt_sr: int | None = None self.net_g = None
self.pipeline: Pipeline | None = None
7
2023-10-14 09:52:31+00:00
16k
zhijie-group/LOVECon
video_diffusion/pipelines/stable_diffusion_controlnet.py
[ { "identifier": "UNetPseudo3DConditionModel", "path": "video_diffusion/models/unet_3d_condition.py", "snippet": "class UNetPseudo3DConditionModel(ModelMixin, ConfigMixin):\n _supports_gradient_checkpointing = True\n\n @register_to_config\n def __init__(\n self,\n sample_size: Opti...
import inspect import os, sys import PIL import torch import numpy as np import json import diffusers import bitsandbytes from dataclasses import dataclass from typing import Callable, List, Optional, Union,Dict,Any from einops import rearrange from tqdm import trange, tqdm from diffusers.utils import is_accelerate_available from packaging import version from transformers import CLIPTextModel, CLIPTokenizer from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL from diffusers.pipeline_utils import DiffusionPipeline from diffusers.schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from diffusers.utils import deprecate, logging from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from ..models.unet_3d_condition import UNetPseudo3DConditionModel from ..models.controlnet_3d_condition import ControlNetPseudo3DModel from video_diffusion.prompt_attention import attention_util from accelerate import cpu_offload
11,286
# code mostly taken from https://github.com/huggingface/diffusers logger = logging.get_logger(__name__) # pylint: disable=invalid-name class SpatioTemporalStableDiffusionControlnetPipeline(DiffusionPipeline): r""" Pipeline for text-to-video generation using Spatio-Temporal Stable Diffusion. """ _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNetPseudo3DConditionModel,
# code mostly taken from https://github.com/huggingface/diffusers logger = logging.get_logger(__name__) # pylint: disable=invalid-name class SpatioTemporalStableDiffusionControlnetPipeline(DiffusionPipeline): r""" Pipeline for text-to-video generation using Spatio-Temporal Stable Diffusion. """ _optional_components = [] def __init__( self, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, unet: UNetPseudo3DConditionModel,
controlnet : ControlNetPseudo3DModel,
1
2023-10-09 14:38:28+00:00
16k
mlpc-ucsd/MaskCLIP
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "maskclip/config.py", "snippet": "def add_maskformer2_config(cfg):\n \"\"\"\n Add config for MASK_FORMER.\n \"\"\"\n # NOTE: configs from original maskformer\n # data config\n # select the dataset mapper\n cfg.INPUT.DATASET_MAPPER_NA...
from shapely.errors import ShapelyDeprecationWarning from collections import OrderedDict from typing import Any, Dict, List, Set from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.data import MetadataCatalog, build_detection_train_loader from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, ) from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler from detectron2.solver.build import maybe_add_gradient_clipping from detectron2.utils.logger import setup_logger from maskclip import ( COCOInstanceNewBaselineDatasetMapper, COCOPanopticNewBaselineDatasetMapper, InstanceSegEvaluator, MaskFormerInstanceDatasetMapper, MaskFormerPanopticDatasetMapper, MaskFormerSemanticDatasetMapper, SemanticSegmentorWithTTA, add_maskformer2_config, ) import warnings import copy import itertools import logging import os import torch import detectron2.utils.comm as comm
11,476
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings('ignore', category=ShapelyDeprecationWarning) except: pass class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Cityscapes if evaluator_type == "cityscapes_instance": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesInstanceEvaluator(dataset_name) if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesSemSegEvaluator(dataset_name) if evaluator_type == "cityscapes_panoptic_seg": if cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesSemSegEvaluator(dataset_name)) if cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesInstanceEvaluator(dataset_name)) # ADE20K if evaluator_type == "ade20k_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) # LVIS if evaluator_type == "lvis": return LVISEvaluator(dataset_name, output_dir=output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic": mapper = MaskFormerSemanticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Panoptic segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_panoptic":
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MaskFormer Training Script. This script is a simplified version of the training script in detectron2/tools. """ try: # ignore ShapelyDeprecationWarning from fvcore warnings.filterwarnings('ignore', category=ShapelyDeprecationWarning) except: pass class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Cityscapes if evaluator_type == "cityscapes_instance": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesInstanceEvaluator(dataset_name) if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesSemSegEvaluator(dataset_name) if evaluator_type == "cityscapes_panoptic_seg": if cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesSemSegEvaluator(dataset_name)) if cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesInstanceEvaluator(dataset_name)) # ADE20K if evaluator_type == "ade20k_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) # LVIS if evaluator_type == "lvis": return LVISEvaluator(dataset_name, output_dir=output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic": mapper = MaskFormerSemanticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Panoptic segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_panoptic":
mapper = MaskFormerPanopticDatasetMapper(cfg, True)
4
2023-10-13 02:32:25+00:00
16k
mlpc-ucsd/MasQCLIP
train_net.py
[ { "identifier": "add_maskformer2_config", "path": "masqclip/config.py", "snippet": "def add_maskformer2_config(cfg):\n \"\"\"\n Add config for MASK_FORMER.\n \"\"\"\n # NOTE: configs from original maskformer\n # data config\n # select the dataset mapper\n cfg.INPUT.DATASET_MAPPER_NA...
import copy import itertools import logging import os import torch import detectron2.utils.comm as comm import warnings from collections import OrderedDict from typing import Any, Dict, List, Set from detectron2.checkpoint import DetectionCheckpointer from detectron2.config import get_cfg from detectron2.data import MetadataCatalog, build_detection_train_loader from detectron2.engine import ( DefaultTrainer, default_argument_parser, default_setup, launch, ) from detectron2.evaluation import ( CityscapesInstanceEvaluator, CityscapesSemSegEvaluator, COCOEvaluator, COCOPanopticEvaluator, DatasetEvaluators, LVISEvaluator, SemSegEvaluator, verify_results, ) from detectron2.projects.deeplab import add_deeplab_config, build_lr_scheduler from detectron2.solver.build import maybe_add_gradient_clipping from detectron2.utils.logger import setup_logger from masqclip import ( COCOInstanceNewBaselineDatasetMapper, COCOPanopticNewBaselineDatasetMapper, InstanceSegEvaluator, MaskFormerInstanceDatasetMapper, MaskFormerPanopticDatasetMapper, MaskFormerSemanticDatasetMapper, SemanticSegmentorWithTTA, add_maskformer2_config, add_masqclip_config, )
12,249
@classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic": mapper = MaskFormerSemanticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Panoptic segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_panoptic": mapper = MaskFormerPanopticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Instance segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_instance": mapper = MaskFormerInstanceDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # coco instance segmentation lsj new baseline elif cfg.INPUT.DATASET_MAPPER_NAME == "coco_instance_lsj": mapper = COCOInstanceNewBaselineDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # coco panoptic segmentation lsj new baseline elif cfg.INPUT.DATASET_MAPPER_NAME == "coco_panoptic_lsj": mapper = COCOPanopticNewBaselineDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) else: mapper = None return build_detection_train_loader(cfg, mapper=mapper) @classmethod def build_lr_scheduler(cls, cfg, optimizer): """ It now calls :func:`detectron2.solver.build_lr_scheduler`. Overwrite it if you'd like a different scheduler. """ return build_lr_scheduler(cfg, optimizer) @classmethod def build_optimizer(cls, cfg, model): weight_decay_norm = cfg.SOLVER.WEIGHT_DECAY_NORM weight_decay_embed = cfg.SOLVER.WEIGHT_DECAY_EMBED defaults = {} defaults["lr"] = cfg.SOLVER.BASE_LR defaults["weight_decay"] = cfg.SOLVER.WEIGHT_DECAY norm_module_types = ( torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.SyncBatchNorm, # NaiveSyncBatchNorm inherits from BatchNorm2d torch.nn.GroupNorm, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.LayerNorm, torch.nn.LocalResponseNorm, ) params: List[Dict[str, Any]] = [] memo: Set[torch.nn.parameter.Parameter] = set() for module_name, module in model.named_modules(): for module_param_name, value in module.named_parameters(recurse=False): if not value.requires_grad: continue # Avoid duplicating parameters if value in memo: continue memo.add(value) hyperparams = copy.copy(defaults) if "backbone" in module_name: hyperparams["lr"] = hyperparams["lr"] * cfg.SOLVER.BACKBONE_MULTIPLIER if ( "relative_position_bias_table" in module_param_name or "absolute_pos_embed" in module_param_name ): print(module_param_name) hyperparams["weight_decay"] = 0.0 if isinstance(module, norm_module_types): hyperparams["weight_decay"] = weight_decay_norm if isinstance(module, torch.nn.Embedding): hyperparams["weight_decay"] = weight_decay_embed params.append({"params": [value], **hyperparams}) def maybe_add_full_model_gradient_clipping(optim): # detectron2 doesn't have full model gradient clipping now clip_norm_val = cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE enable = ( cfg.SOLVER.CLIP_GRADIENTS.ENABLED and cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model" and clip_norm_val > 0.0 ) class FullModelGradientClippingOptimizer(optim): def step(self, closure=None): all_params = itertools.chain(*[x["params"] for x in self.param_groups]) torch.nn.utils.clip_grad_norm_(all_params, clip_norm_val) super().step(closure=closure) return FullModelGradientClippingOptimizer if enable else optim optimizer_type = cfg.SOLVER.OPTIMIZER if optimizer_type == "SGD": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)( params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM ) elif optimizer_type == "ADAMW": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)( params, cfg.SOLVER.BASE_LR ) else: raise NotImplementedError(f"no optimizer type {optimizer_type}") if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model": optimizer = maybe_add_gradient_clipping(cfg, optimizer) return optimizer @classmethod def test_with_TTA(cls, cfg, model): logger = logging.getLogger("detectron2.trainer") # In the end of training, run an evaluation with TTA. logger.info("Running inference with test-time augmentation ...")
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ MasQCLIP Training Script. """ # MasQCLIP warnings.filterwarnings("ignore") class Trainer(DefaultTrainer): """ Extension of the Trainer class adapted to MaskFormer. """ @classmethod def build_evaluator(cls, cfg, dataset_name, output_folder=None): """ Create evaluator(s) for a given dataset. This uses the special metadata "evaluator_type" associated with each builtin dataset. For your own dataset, you can simply create an evaluator manually in your script and do not have to worry about the hacky if-else logic here. """ if output_folder is None: output_folder = os.path.join(cfg.OUTPUT_DIR, "inference") evaluator_list = [] evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type # semantic segmentation if evaluator_type in ["sem_seg", "ade20k_panoptic_seg"]: evaluator_list.append( SemSegEvaluator( dataset_name, distributed=True, output_dir=output_folder, ) ) # instance segmentation if evaluator_type == "coco": evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) # panoptic segmentation if evaluator_type in [ "coco_panoptic_seg", "ade20k_panoptic_seg", "cityscapes_panoptic_seg", "mapillary_vistas_panoptic_seg", ]: if cfg.MODEL.MASK_FORMER.TEST.PANOPTIC_ON: evaluator_list.append(COCOPanopticEvaluator(dataset_name, output_folder)) # COCO if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(COCOEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "coco_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Mapillary Vistas if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) if evaluator_type == "mapillary_vistas_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: evaluator_list.append(SemSegEvaluator(dataset_name, distributed=True, output_dir=output_folder)) # Cityscapes if evaluator_type == "cityscapes_instance": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesInstanceEvaluator(dataset_name) if evaluator_type == "cityscapes_sem_seg": assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." return CityscapesSemSegEvaluator(dataset_name) if evaluator_type == "cityscapes_panoptic_seg": if cfg.MODEL.MASK_FORMER.TEST.SEMANTIC_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesSemSegEvaluator(dataset_name)) if cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: assert ( torch.cuda.device_count() > comm.get_rank() ), "CityscapesEvaluator currently do not work with multiple machines." evaluator_list.append(CityscapesInstanceEvaluator(dataset_name)) # ADE20K if evaluator_type == "ade20k_panoptic_seg" and cfg.MODEL.MASK_FORMER.TEST.INSTANCE_ON: evaluator_list.append(InstanceSegEvaluator(dataset_name, output_dir=output_folder)) # LVIS if evaluator_type == "lvis": return LVISEvaluator(dataset_name, output_dir=output_folder) if len(evaluator_list) == 0: raise NotImplementedError( "no Evaluator for the dataset {} with the type {}".format( dataset_name, evaluator_type ) ) elif len(evaluator_list) == 1: return evaluator_list[0] return DatasetEvaluators(evaluator_list) @classmethod def build_train_loader(cls, cfg): # Semantic segmentation dataset mapper if cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_semantic": mapper = MaskFormerSemanticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Panoptic segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_panoptic": mapper = MaskFormerPanopticDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # Instance segmentation dataset mapper elif cfg.INPUT.DATASET_MAPPER_NAME == "mask_former_instance": mapper = MaskFormerInstanceDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # coco instance segmentation lsj new baseline elif cfg.INPUT.DATASET_MAPPER_NAME == "coco_instance_lsj": mapper = COCOInstanceNewBaselineDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) # coco panoptic segmentation lsj new baseline elif cfg.INPUT.DATASET_MAPPER_NAME == "coco_panoptic_lsj": mapper = COCOPanopticNewBaselineDatasetMapper(cfg, True) return build_detection_train_loader(cfg, mapper=mapper) else: mapper = None return build_detection_train_loader(cfg, mapper=mapper) @classmethod def build_lr_scheduler(cls, cfg, optimizer): """ It now calls :func:`detectron2.solver.build_lr_scheduler`. Overwrite it if you'd like a different scheduler. """ return build_lr_scheduler(cfg, optimizer) @classmethod def build_optimizer(cls, cfg, model): weight_decay_norm = cfg.SOLVER.WEIGHT_DECAY_NORM weight_decay_embed = cfg.SOLVER.WEIGHT_DECAY_EMBED defaults = {} defaults["lr"] = cfg.SOLVER.BASE_LR defaults["weight_decay"] = cfg.SOLVER.WEIGHT_DECAY norm_module_types = ( torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d, torch.nn.SyncBatchNorm, # NaiveSyncBatchNorm inherits from BatchNorm2d torch.nn.GroupNorm, torch.nn.InstanceNorm1d, torch.nn.InstanceNorm2d, torch.nn.InstanceNorm3d, torch.nn.LayerNorm, torch.nn.LocalResponseNorm, ) params: List[Dict[str, Any]] = [] memo: Set[torch.nn.parameter.Parameter] = set() for module_name, module in model.named_modules(): for module_param_name, value in module.named_parameters(recurse=False): if not value.requires_grad: continue # Avoid duplicating parameters if value in memo: continue memo.add(value) hyperparams = copy.copy(defaults) if "backbone" in module_name: hyperparams["lr"] = hyperparams["lr"] * cfg.SOLVER.BACKBONE_MULTIPLIER if ( "relative_position_bias_table" in module_param_name or "absolute_pos_embed" in module_param_name ): print(module_param_name) hyperparams["weight_decay"] = 0.0 if isinstance(module, norm_module_types): hyperparams["weight_decay"] = weight_decay_norm if isinstance(module, torch.nn.Embedding): hyperparams["weight_decay"] = weight_decay_embed params.append({"params": [value], **hyperparams}) def maybe_add_full_model_gradient_clipping(optim): # detectron2 doesn't have full model gradient clipping now clip_norm_val = cfg.SOLVER.CLIP_GRADIENTS.CLIP_VALUE enable = ( cfg.SOLVER.CLIP_GRADIENTS.ENABLED and cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model" and clip_norm_val > 0.0 ) class FullModelGradientClippingOptimizer(optim): def step(self, closure=None): all_params = itertools.chain(*[x["params"] for x in self.param_groups]) torch.nn.utils.clip_grad_norm_(all_params, clip_norm_val) super().step(closure=closure) return FullModelGradientClippingOptimizer if enable else optim optimizer_type = cfg.SOLVER.OPTIMIZER if optimizer_type == "SGD": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.SGD)( params, cfg.SOLVER.BASE_LR, momentum=cfg.SOLVER.MOMENTUM ) elif optimizer_type == "ADAMW": optimizer = maybe_add_full_model_gradient_clipping(torch.optim.AdamW)( params, cfg.SOLVER.BASE_LR ) else: raise NotImplementedError(f"no optimizer type {optimizer_type}") if not cfg.SOLVER.CLIP_GRADIENTS.CLIP_TYPE == "full_model": optimizer = maybe_add_gradient_clipping(cfg, optimizer) return optimizer @classmethod def test_with_TTA(cls, cfg, model): logger = logging.getLogger("detectron2.trainer") # In the end of training, run an evaluation with TTA. logger.info("Running inference with test-time augmentation ...")
model = SemanticSegmentorWithTTA(cfg, model)
7
2023-10-13 02:43:53+00:00
16k